const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BoostCompanion-BkvUCyD3.js","assets/BoostPanel-CHmvgjmV.js","assets/useAssistantChat-5pbISssp.js","assets/useSmartQueue-COQLirOp.js","assets/useBoostGift-Ci-D61_u.js","assets/rotate-ccw-lQkPCQXx.js","assets/sun-DubH_BBi.js","assets/announcements-CHWMrHjI.js","assets/pause-DsGaswt-.js","assets/bell-off-Cb6nL_Ur.js","assets/LeadSiteHome-Dy_hVUOG.js","assets/useLeadSiteSearchSuggestions-CsEH7G_b.js","assets/hash-BfJyfZcc.js","assets/map-DoKPSbBo.js","assets/AgentReviewsSection-BHc6MmQy.js","assets/credits-PIR_bev7.js","assets/ExchangeListingsSection-DE8L6Z8C.js","assets/leadSiteAgent--GbV6IdE.js","assets/ScrollLivingHero-aUTO6Zyn.js","assets/LeadSiteLuxuryHome-BgX8M3M9.js","assets/RecentSalesSnapshot-DhRAujaL.js","assets/LeadSiteExchangeListings-DK9QCT--.js","assets/truck-D3tWdz9S.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-Cl8Ytng8.js","assets/use-in-view-DGOONr6k.js","assets/tree-pine-bJZWxZ9V.js","assets/mountain-Dnsn265f.js","assets/LeadSiteSearch-QIkzG9es.js","assets/ListingCardExtras-B93tuPtG.js","assets/bell-ring-C4lqffR1.js","assets/useInfiniteQuery-CR1bGd8q.js","assets/LeadSiteMap-Dz67JDBa.js","assets/LeadSiteLuxurySearch-BcMKZNdM.js","assets/LeadSiteListingDetail-DP_3MMIx.js","assets/ListingVideoTour-CJFy9Wlo.js","assets/expand-Dm4dKIi1.js","assets/car-eYxiJ4gp.js","assets/thermometer-DHh4R85P.js","assets/snowflake-Cd8_GMHR.js","assets/waves-DwYkB-sl.js","assets/useListingVideos-tMFODT1V.js","assets/LeadSiteLuxuryListingDetail-BG0sQbW0.js","assets/LeadSiteAbout-Bf42ZGMD.js","assets/LeadSiteLuxuryAbout-CtN-ploN.js","assets/ExpReadySpotlight-BBIfdRmS.js","assets/LeadSiteBlog-Biq8Zf1k.js","assets/renderPostContent-Czn49UfS.js","assets/LeadSiteCommunity-BJi6lTOs.js","assets/wine-Dz0lbg5h.js","assets/trees-C2S8n076.js","assets/plane-DFM4prnO.js","assets/music-BW9erdZw.js","assets/LeadSiteSellers-BqfVC3_Y.js","assets/LeadSiteCityPage-DNuxh0LP.js","assets/CityFaqSection-D8gET10q.js","assets/LeadSiteFocusPage-D_YjiIO4.js","assets/LeadSiteExpReady-Ca7s6PpP.js","assets/paintbrush-DTnOED-R.js","assets/OrgSiteLayout-CMVDchqm.js","assets/orgSiteBrand-DKMUe12O.js","assets/OrgSiteHome-CB_HBL_G.js","assets/OrgSiteAgents-D0tjvDNn.js","assets/OrgSitePages-YpUZTaHB.js","assets/OrgSiteListings-YG8jUT2x.js","assets/CanvaSupport-pXnYyLld.js","assets/unplug-BHXOCaj-.js","assets/SmsOptIn-BNwuFIzm.js","assets/signpost-DXMTxHw1.js","assets/ConnectChatGPT-DuhVplw_.js","assets/circle-check-big-CQGr1Qje.js","assets/SubscriptionSuccess-InG6Ryt1.js","assets/SetupBrokerage-C8Gj6lOm.js","assets/InviteSignup-OIPxll0j.js","assets/eye-off-mClW_4Na.js","assets/CoachingHub-jC6TasGZ.js","assets/useCoaching-CuOMOIET.js","assets/CoachAgentWorkspace-oCGykJGe.js","assets/CoachingFiles-CZPz8srM.js","assets/folder-open-DAAY_sH2.js","assets/save-MJGXdCAD.js","assets/MyCoach-BkUdeN6I.js","assets/CoachReviews-BOzXLbhT.js","assets/circle-x-BZ5cKpxH.js","assets/AdminCoaching-COO_pamw.js","assets/arrow-left-right-UB_0QCn5.js","assets/user-minus-BkEDQYg8.js","assets/inbox-Ci17VS5Q.js","assets/CoachBilling-BOZwIQI3.js","assets/credit-card-3pzdQbxk.js","assets/CoachSettings-Bcfh1llz.js","assets/GoogleCalendarCard-BpccHx8D.js","assets/calendar-off-BC9t0DW5.js","assets/useCoachGoogleCalendar-B2vl_J_D.js","assets/link-bGfUG-T9.js","assets/Microsoft365Return-CtGATC0B.js","assets/useMicrosoft365-LeQQFQww.js","assets/freshAccessToken-CVBYZRH7.js","assets/CoachWaitlist-CaGYTdRF.js","assets/mail-check-BBjlbXLv.js","assets/CoachProfile-CE8guHnf.js","assets/Trial-BQFHSe7h.js","assets/testimonial-avatar-5-DBoTqx4u.js","assets/TrialSuccess-B4C4bU3c.js","assets/party-popper-DvfH1CLd.js","assets/LaborDaySale-D7NOd0ls.js","assets/OpenHouseInviteModal-Cs6CXT3j.js","assets/infinity-V6Juy9v2.js","assets/workflow-C0MZSnXe.js","assets/BrokerageLaborDaySale-Bp6Q6CNy.js","assets/BrokerageSolutions-BwHUgJcV.js","assets/receipt-Cmu7AoEP.js","assets/scale-Den4oSva.js","assets/pencil-line-4Xw5TcU5.js","assets/Upgrade-CFfDAWyh.js","assets/log-in-DWBKLoO5.js","assets/InstagramGift-D53xlWYV.js","assets/VideoShare-sso_ILMR.js","assets/VideoPageTemplates-DY7k-ahk.js","assets/flag-BUXCWQsK.js","assets/message-circle-heart-SnsPjW7W.js","assets/door-open-lklKW1D6.js","assets/brain-DBN7bPd8.js","assets/coffee-ApwWjGrE.js","assets/CommercialWizard-C2DIXnrh.js","assets/useListingExchange-CSlO5GSz.js","assets/useTeamListingAccess-DamH_qhw.js","assets/CommercialWorkspace-Ck9kLo1D.js","assets/ListingSocialDialog-C6E89XyI.js","assets/useAgentBrand-CNA4BkVF.js","assets/listingGraphic-jesxFSmt.js","assets/ListingPhotoGrid-CuotFjxC.js","assets/sortable.esm-w4qfYB68.js","assets/grip-vertical-B5_dDBsj.js","assets/ShareListingDialog-_n_qCSqO.js","assets/EmailListingToSphereDialog-aJ2KEm28.js","assets/index-8eaGL-W7.js","assets/separator-C_Mgg4M7.js","assets/GmailComposeDialog-DvzNfyKr.js","assets/useMassEmailReady-Cx9WsDNk.js","assets/useSenderIdentity-1hxGGRJI.js","assets/useVerifiedSenderCheck-DceysGCb.js","assets/VerifySenderRequiredDialog-Ca5USKls.js","assets/useContactIntakePage-DtYTJsmX.js","assets/ToContactAutocomplete-Z-N9xxnr.js","assets/outlookSend-Xi57ADZ9.js","assets/paperclip-DOg8Wv3w.js","assets/file-search-mEbU3kk9.js","assets/qr-code-DptkbvKb.js","assets/CommercialPitchPreview-DF5yfQV9.js","assets/PublicLiveEvent-DgzweO-s.js","assets/pin-HO4PQBWP.js","assets/arrow-up-CPpSvga8.js","assets/useLiveEngagement-ErIMDEVP.js","assets/sparkle-DNodqs-R.js","assets/LiveEvents-BJa6rWJQ.js","assets/AdminPageHeader-DbVqvyna.js","assets/useLiveEvents-BftsPhq8.js","assets/image-plus-CY_lPSzp.js","assets/LiveEventConsole-iPcks758.js","assets/mouse-pointer-click-DDso2DTw.js","assets/ban-D8E9T5FG.js","assets/Dashboard-tgdoy-RT.js","assets/useContentEngagement-ChiYjiHw.js","assets/usePrograms-BdP0vlw3.js","assets/timezone-BUccVhEp.js","assets/addMilliseconds-Dyxlt3j9.js","assets/isWithinInterval-DpGJsgX9.js","assets/useGmailIntegration-BBZ1r_oR.js","assets/GoalTargetsDialog-BiVvMzAK.js","assets/useBrokerageContent-BGyh2QfE.js","assets/beta-badge-c9tSVkr7.js","assets/useEventGamification-B4P_kErH.js","assets/RelationshipHealthWidget-D2_Lycgm.js","assets/useRelationshipScore-DXDn83Tr.js","assets/file-image-DHbL4hP-.js","assets/Profile-B8uxWCqa.js","assets/RichTextEditor-CwifR9tZ.js","assets/index-CF4lllD5.js","assets/index-kS8oxU3a.js","assets/index-CVBG_YV4.js","assets/heading-1-BXVsd3dJ.js","assets/heading-2-Bwp7tcgP.js","assets/undo-DfxzjYyj.js","assets/list-ordered-By_3g7at.js","assets/align-left-DTVA9PmD.js","assets/align-right-Sp4_m1SN.js","assets/ImageCropper-DgLGk4v5.js","assets/zoom-out-DrCFpwcf.js","assets/rotate-cw-BSeKGEsv.js","assets/ImageCropper-D8Md-CES.css","assets/useBrandKit-DGKGeJk-.js","assets/useStagingStudio-CEHV_ISt.js","assets/checkoutTab-DPrAD7yT.js","assets/BrokerageLogoUpload-BJGmG7_h.js","assets/user-round-DeMWQpso.js","assets/mail-x-ChpVqXAL.js","assets/Events-N2S_ogAg.js","assets/EventLeaderboard-_MiiAVM5.js","assets/medal-VgY7pVPz.js","assets/MainStageSchedule-CZC6YxBp.js","assets/history-DjZr-mz0.js","assets/EventDetail-CeaxAYo3.js","assets/ShareButton-DwQJLnh1.js","assets/user-cog-Cs8DY--W.js","assets/Apps-B6oEFeaD.js","assets/monitor-play-CYhhJAVW.js","assets/skip-forward-BeYHzGhV.js","assets/Templates-C1Drzs_J.js","assets/TemplateDetail-Ao6m_-NU.js","assets/Programs-tJPe0uNg.js","assets/ProgramDetail-Bl-sRSdb.js","assets/accordion-4IQ-UrSi.js","assets/index-CtZrYQ7m.js","assets/ProgramEnroll-D5xhLmwp.js","assets/tag-Cjfc2pgs.js","assets/ProgramWorkspace-BwSXmOOx.js","assets/file-spreadsheet-CKlrTDuL.js","assets/layout-template-B10saYRy.js","assets/Programs-BMuJQCo3.js","assets/route-CL0eyvdT.js","assets/collapsible-D0NrG_C6.js","assets/AcademyVideoDetail-DWtd9cxQ.js","assets/LinkedTemplatePills-Bw0BCVyr.js","assets/ToolboxDetail-kMJjpJvG.js","assets/SocialSwag-BzKKBrJv.js","assets/SocialStudio-DmRfj0Jk.js","assets/CanvaImportDialog-D_H6_iLl.js","assets/useCanvaMailStudio-svQxIXxX.js","assets/unlink-CQ1937QV.js","assets/platforms-BU4fSLla.js","assets/music-2-BVOC9ANA.js","assets/jpegConvert-O58liG-S.js","assets/repeat-2-DDEqugOt.js","assets/type-Dyd6x1Jf.js","assets/settings-2-CVTn1ovT.js","assets/scheduleTz-DvB_qqNl.js","assets/calendarTz-JHe45SGp.js","assets/YouTubePublishing-CSoIZ-FJ.js","assets/useCalendarTimezone-BngRCTKM.js","assets/CalendarSettingsDialog-C-tWRSGs.js","assets/earth-CrUY9Fm8.js","assets/tiktokCallbackError-HhZqZSBp.js","assets/edgeError-RXA9RD1T.js","assets/jszip.min-CvXY060g.js","assets/MarketingStudio-Qg9R0309.js","assets/message-square-quote-CeuL5ey3.js","assets/BrandKit-DMR7tLtc.js","assets/useBrandPresets-90JMO9I0.js","assets/BrandingBarEditor-CCKmnADb.js","assets/ReactKonvaCore-DjT2uxK5.js","assets/index-C_u1ltoW.js","assets/ListingTemplates-D8iIXCOD.js","assets/index-xVp0PEHv.js","assets/EditorialTemplate-D3MSOHws.js","assets/PersonalBranding-CrJlSD9S.js","assets/toggle-group-DvlR7xpZ.js","assets/SocialSwagDetail-BUElcx82.js","assets/Community-BREF_PaX.js","assets/MentionTextarea-Dt4duPUH.js","assets/reply-BmkBMLts.js","assets/pin-off-DfzjMAiC.js","assets/Support-DrpNetRl.js","assets/SupportAttachmentList-Dw7Y-6Mp.js","assets/file-video-C5w9AKKM.js","assets/BrokerageResources-C73tsD-7.js","assets/AdminDashboard-C1bu7dvH.js","assets/coins-BSvF4808.js","assets/shopping-bag-CXaYOopP.js","assets/flask-conical-QxVrVpRC.js","assets/database-vKdtCa3K.js","assets/MemberManagement-CMxdxeC8.js","assets/SendCelebrationDialog-DKS59JSA.js","assets/sortable-table-head-COhqFd2r.js","assets/arrow-down-B59uOlal.js","assets/useTeams-BZde-yHO.js","assets/CreateTeamDialog-Deq1TOjA.js","assets/TeamSharedAssetsView-QEh_ZROu.js","assets/LeadPondView-DuRniAx7.js","assets/arrow-right-left-DwPuxRQB.js","assets/sticky-note-BtaKN-Co.js","assets/droplets-Ch21Vmrm.js","assets/hand-BevVdbu3.js","assets/contact-DnVnTI3H.js","assets/crown-C7I0glM2.js","assets/calendar-heart-C-QxtHQC.js","assets/UnassignedMembers-WF2ZfT4d.js","assets/InviteCodes-CTWw6ivF.js","assets/Events-C4u38cbD.js","assets/useNotifications-DFlOwBEN.js","assets/repeat-C1ZPh7nt.js","assets/MCPAuditLog-adI1JNiK.js","assets/shield-alert-CJHczFhe.js","assets/Templates-q3ap7P9w.js","assets/Academy-CnpVDLuV.js","assets/LinkedTemplatePicker-D2Yi3b8L.js","assets/Toolbox-BofQGCF0.js","assets/SocialSwag-CDpVwIhY.js","assets/SocialSwag2-DuH99XnS.js","assets/Community-C1Hk1bx5.js","assets/Analytics-Bv0N1J4w.js","assets/ShareAnalytics-DyAAy9fa.js","assets/mouse-pointer-Be9kHOz4.js","assets/panels-top-left-BDoTlHj3.js","assets/LineChart-D1DkpIwk.js","assets/chrome-BNUuhMY1.js","assets/BrokerageResources-UuD8aRQG.js","assets/DashboardManagement-AW02Y8xn.js","assets/SupportTickets-C15UxvKV.js","assets/EmailTemplates-DVAiNG7R.js","assets/index-BBKy9vZ0.js","assets/code-BMkY3iK7.js","assets/variable-BT6IaMEs.js","assets/monitor-DeMGJg56.js","assets/AgentEmailTemplates-Du8PHG2w.js","assets/BrokerageDashboard-DomdwKvc.js","assets/BrokerageLenderReport-ZwdxhqcY.js","assets/MyBrokerage-XRpgm56k.js","assets/useBrokerageOnboarding-DP69uyxc.js","assets/OnboardingChecklist-p7JDq3UI.js","assets/BrokerageContent-ClYbAV_J.js","assets/BrokerageHelpBoard-CcG0YtKi.js","assets/useBrokerageHelpBoard-BvD9Kuja.js","assets/BrokerageHelpBoardNew-CPUAzWXQ.js","assets/BrokerageHelpBoardDetail-B-Bd1WNl.js","assets/Newsletters-hD9bJsMS.js","assets/useMailingAddressGate-Daofkk7n.js","assets/NewsletterGraphicsPicker-COZ7sq-6.js","assets/underline-Cp15rE_k.js","assets/SenderAddressDialog-DWJ1TcWa.js","assets/uploadBase64Images-UwPlgcUs.js","assets/SendNewsletterDialog-BMbitAXs.js","assets/undo-2-Bobtxc_3.js","assets/useContactCustomTags-BK3RWLMr.js","assets/useSmartLists-CW4VK7fu.js","assets/code-xml-DY3f74Km.js","assets/list-filter-DAB1tcqI.js","assets/NewsletterDetail-D9kDFFFv.js","assets/Newsletters-s4du9FHV.js","assets/library-DrF-3Ul4.js","assets/MemberBroadcasts-DEvnNnKh.js","assets/bookmark-plus-COU0EFTv.js","assets/BoostAnnouncements-Bs4Y7aEY.js","assets/NewsletterGraphics-CQpoKoF7.js","assets/Wishlist-CMJYnnQ6.js","assets/WishlistDetail-y_y3p71o.js","assets/LevelUpBrief-Bo-XmGxM.js","assets/AdditionalServices-BlpsT24i.js","assets/Discounts-DAxqDjQ_.js","assets/Subscriptions-deZ-VfVG.js","assets/instagramEmailReview-DK4Cq88H.js","assets/InstagramGiftEmails-B28KksEN.js","assets/Referrals-DRWIKPNn.js","assets/AgentOSControlCenter-DQXIlqcl.js","assets/AskAI-DWYU8Ld3.js","assets/InnerCircleHome-8S_36Ps5.js","assets/SnoozeContactDialog-GMAz9ft9.js","assets/pen-tool-DO6qpdJW.js","assets/milestoneMail-Cs6qfJaR.js","assets/handoff-B7AOa2Ye.js","assets/milestones-De303X1G.js","assets/stamp-BKq-prz_.js","assets/list-todo-C8Izhd7-.js","assets/mail-open-BmXvCa7B.js","assets/InnerCircleContacts-5BGCEHUu.js","assets/mailingAddress-BJ5Zh-Ye.js","assets/SyncDirectionSelector-HmVsIA0Z.js","assets/refresh-ccw-B30jNSDI.js","assets/merge-DopDfYGm.js","assets/ContactCriteriaForm-Cs1Lfkp-.js","assets/usePopbys-B-10DN_N.js","assets/ContactTagChip-B8nruzJ1.js","assets/info-BFnn_fTc.js","assets/RelationshipScoreBadge-Ca6jFLbB.js","assets/MailStudioHandoffButton-BRzyNd8-.js","assets/useVideoShareTracking-DuXVsdRx.js","assets/EnrollContactsDialog-Bme9OvCG.js","assets/useDripCampaigns-ClLKxIQ2.js","assets/CampaignBuilderDialog-44yha6l9.js","assets/quill.snow-wpIGVvSN.js","assets/quill-BzY4kI8E.css","assets/braces-BUeR5hch.js","assets/VideoLibraryPicker-DHrK8TaG.js","assets/VideoUploadDialog-BNpR7r5V.js","assets/useVideoTouch-CVY4KlSV.js","assets/NeighborhoodFilter-K6lITgF2.js","assets/useNeighborhoods-C1jo3vgQ.js","assets/sphereMap-CrDX8560.js","assets/sprout-B-K1nDiB.js","assets/ContactAvatar-QgMcov7M.js","assets/user-x-CzSZYWPV.js","assets/map-pinned-CKiqv23m.js","assets/InnerCircleContactDetail-DoW3kQUC.js","assets/useLenders-BL7JhL9i.js","assets/SendToLenderDialog-B_xC3hUx.js","assets/useCMA-KgICBr7k.js","assets/useClientPortal-CywVagbn.js","assets/futureSeller-oxlR0MvT.js","assets/useSentEmails-C-uPol2f.js","assets/propertyService-CUvaowGX.js","assets/building-BXzE8R7W.js","assets/archive-B9WUiQ_m.js","assets/useContactFinder-DkSoTeiQ.js","assets/SentEmails-Ca_Dc-tA.js","assets/InnerCirclePlans-DPVtimWy.js","assets/pen-bNqtN7oY.js","assets/CMAList-CTZHdRbj.js","assets/SendCMADialog-Bidb1tZO.js","assets/UpgradeLockedCard-Ct_ddO-_.js","assets/CMABuilder-CiY9ZNZh.js","assets/VideoRecorder-Cw-DXZUB.js","assets/flip-horizontal-CoL8QDWb.js","assets/videoSegmentation-23AN6N06.js","assets/monitor-up-Cf4wsgqw.js","assets/mic-COqFaxWy.js","assets/ListingPresentations-Dh3ghvE3.js","assets/session-D1OuN40c.js","assets/jspdf.es.min-BT8mPeOL.js","assets/SendPresentationDialog-Kxebckna.js","assets/ListingPresentationBuilder-Cv9bl_fA.js","assets/PdfCanvasPreview-DBQv-G-0.js","assets/pdf.worker.min-DVMGg98K.js","assets/ImageUploadField-BlCrUBnv.js","assets/move-CZZKCki4.js","assets/InnerCirclePopbys-CBXw4bvU.js","assets/locate-DLug6qQ6.js","assets/navigation-KDuc43F6.js","assets/ListingExchange-C4qimD-M.js","assets/ListingLaunchKitModal-BnUyatPQ.js","assets/ListingSelectionBar-DvZ5Qhmc.js","assets/musicVideoHandoff-Bs6IOG8F.js","assets/ListingDetail-BhP9AiO-.js","assets/ListingForm-qJglCrSt.js","assets/CustomizeListingPage-Cpe6rj3Q.js","assets/box-CLBh2-pQ.js","assets/VideoStudio-CBfBIpsJ.js","assets/wifi-BuW0xyAg.js","assets/VideoShareWithTemplate-B63kqaUB.js","assets/stageInvite-DzEhBCh1.js","assets/interactive-DIPuWtuI.js","assets/browser-CjSdxGTc.js","assets/tv-B2CvuQlz.js","assets/video-off-skC4QB4T.js","assets/guestRoom-BxZRuP_L.js","assets/kits-DACmZcCF.js","assets/BackdropPanel-CiC1Z6a_.js","assets/ListingPhotoImport-ZnUpZxDt.js","assets/images-Wvr8Gxg4.js","assets/panel-right-close-oJ-V677s.js","assets/clapperboard-BNAS51ER.js","assets/scissors-BejKEPTA.js","assets/switch-camera-C-x0IEhP.js","assets/MainStageGate-CR9rl-Xn.js","assets/survey-D3wevp60.js","assets/phone-off-CtNPL3ML.js","assets/eraser-CLEPqpIN.js","assets/theater-8I287T2E.js","assets/MainStageAdmin-DJ9H0iPH.js","assets/StudioKitsAdmin-C3Yy0-b6.js","assets/StudioGuestJoin-BKN45m-y.js","assets/VideoLibrary-Dn_AzY2F.js","assets/tags-CgGZ0lS7.js","assets/hard-drive-BXtSpoBZ.js","assets/DealPipeline-CC27PGAe.js","assets/lucide-react-C-9r2MOB.js","assets/archive-restore-DktB72ka.js","assets/arrow-down-left-KQS46PwY.js","assets/arrow-down-right-D1ox_M5U.js","assets/badge-check-DahbEmDv.js","assets/circle-user-BYdD9xpm.js","assets/beaker-CYBKiZaE.js","assets/brain-circuit-B8DftHb-.js","assets/calendar-x-DbNBaL6b.js","assets/chart-line-BCvUjDBG.js","assets/file-code-8iBHhwqi.js","assets/table-jKpYQ7Le.js","assets/circle-dollar-sign-BWSRI4tW.js","assets/clock-3-DPWlqOiK.js","assets/sunset-CHlZ7P_A.js","assets/cloud-upload-C1m_zps7.js","assets/corner-down-right-wfWSg-PR.js","assets/file-check-2-DBi5Jy6H.js","assets/hammer-B5zmem0c.js","assets/file-down-C9ow0Ss0.js","assets/file-plus-2-7X_UzVIH.js","assets/piggy-bank-D8w1958U.js","assets/folder-plus-qteaR0so.js","assets/folder-CNtPmSyD.js","assets/footprints-CJMgjx63.js","assets/gem-BDeVmaFc.js","assets/hand-heart-CRIxhZ0V.js","assets/heading-3-BkRv-aZG.js","assets/heart-handshake-B3IbpQIf.js","assets/id-card-CEZvDGtc.js","assets/locate-fixed-szz6GBk7.js","assets/list-plus-CeNQZvx2.js","assets/lock-keyhole-BBTXUu6e.js","assets/mail-plus-BSArZc5A.js","assets/mail-warning-BujkoNcW.js","assets/message-square-more-Ckr_sHXR.js","assets/message-square-plus-za6RvAit.js","assets/message-square-reply-BluL-AFq.js","assets/messages-square-B2_Eg5jj.js","assets/mouse-pointer-2-DrFOUxSV.js","assets/skip-back-r8JZt9hM.js","assets/octagon-alert-Dwh6i7P7.js","assets/power-off-8hUj20iD.js","assets/power-DGPTUUqC.js","assets/printer-CTwDoZAV.js","assets/rectangle-vertical-BcsCrm9o.js","assets/scroll-text-BSHks3NP.js","assets/shield-off-DuJDyg1N.js","assets/shield-question-DGFsbTSj.js","assets/shuffle-yudGSK6N.js","assets/table-2-BOckFCt-.js","assets/text-cursor-input-DEOY70E8.js","assets/thumbs-down-BEVx35Nt.js","assets/twitter-pgkzO-MA.js","assets/user-round-check-D-Xajn6z.js","assets/user-round-search-BXZl9ns1.js","assets/users-round-B0dNrUWP.js","assets/useCommissionPlans-DzI5ofUp.js","assets/ComplianceMessageThread-CpbWG_PD.js","assets/SendForSignatureDialog-D7gBf0kV.js","assets/useFormEnvelopes-C42TrqEr.js","assets/PortalInviteDialog-CvbfY8WW.js","assets/CardVideoRecorderDialog-CM1Bogkr.js","assets/PlaybookLibraryDialog-Djwc2dNA.js","assets/LenderPartnerDialog-C0nvL8Q5.js","assets/PhotoUploadField-LZtHB9S0.js","assets/PortalListView-BvIUK9v1.js","assets/complianceMetrics-Ce83UgLe.js","assets/FormsLibrary-CW5oKrma.js","assets/FormPlacementEditor-BLcfP5hI.js","assets/TransactionCoordinator-DLGy9RXf.js","assets/PortalReferrals-DlYEx_d9.js","assets/usePortalReferrals-uts9Mke4.js","assets/AgentVendors-80FLyR_4.js","assets/VendorFormDialog-LFzGk-F-.js","assets/BrokerageForms-n5vl1iaa.js","assets/BrokerageVendors-BTPMnC9v.js","assets/ClientPortalsHub-DJgmEVGW.js","assets/PortalMessagesPanel-CPmC0m_H.js","assets/ClientPortalDetail-iNnxEFY-.js","assets/MyCardEditor-PhaaA2FA.js","assets/CardBlocksEditor-CnQ2ICEL.js","assets/Integrations-CTjGJJmx.js","assets/SesIntegrationCard-DZcDlj2c.js","assets/RecruitVerifiedSenders-DZgRtuPh.js","assets/Microsoft365Card-DcZmGhwd.js","assets/BrowserExtension-CzdzFWq-.js","assets/IntegrationsGmailCallback-1ObFkgk0.js","assets/IntegrationsMetaCallback-COkQJi3U.js","assets/AgentActivation-D-ekz1VT.js","assets/MembershipReviews-DE4wWt0v.js","assets/LeadNotifications-DRiLYpz3.js","assets/WeeklyDigest-DMDpAu5x.js","assets/AgentPoints-BxUtwwVU.js","assets/AgentCards-Ber6IDUs.js","assets/Marketplace-BUEYX6-n.js","assets/RewardStore-iRtpUJ3l.js","assets/usePointRewardSettings-DwCZoIA-.js","assets/Integrations-CryLvWSe.js","assets/SocialConnections-BG-rHpJL.js","assets/SocialAutopilot-CRNynGSx.js","assets/McpUpdates-D06ziFoY.js","assets/NotificationSettings-CR4HTBhq.js","assets/PresentationAnalytics-LMLAAUOv.js","assets/ListingPresentationStudioAdmin-DSgWSsr_.js","assets/ListingRevivalAdmin-MTNfIl_0.js","assets/useListingRevivalAccess-DYeaBMLf.js","assets/GuestBookAnalytics-CCb74CX9.js","assets/IntegrationsCallback-Dtc4Vzh5.js","assets/AdminRecruiting-37gqPIG8.js","assets/RecruitPipelineStageEditor-sqRdSWkb.js","assets/index-CoCa8sU9.js","assets/BrokerageRecruiting-Cb0OrOCk.js","assets/600-BSKZD_mM.css","assets/BrokerageOnboarding-BPWsNxft.js","assets/BrokerageTransactions-IQ1JlEkZ.js","assets/useDealEscrow-DdRbYyeb.js","assets/BrokerageOperations-DuYEZ2EA.js","assets/renewals-zDG8yyR4.js","assets/WebsitesHub-CpugxUXL.js","assets/useMyWebsites-D_sMRpoK.js","assets/TeamWebsite-CFrRUPVS.js","assets/OrgSiteBuilder-ClhXkoEb.js","assets/SiteSwitcher-DB-fzjbo.js","assets/BrokerageWebsite-4xti_wD5.js","assets/BrokerageCommissionPlans-Dn5FmNN7.js","assets/BrokerageContentActivity-CdLkQiVd.js","assets/BetaSocialPostGenerator-hfieDzGZ.js","assets/AdminLMS-DYqcUCsi.js","assets/useLMS-CbWBkRE7.js","assets/AdminCourseDetail-rWBasbaX.js","assets/LevelUpU-DYWYELfV.js","assets/LevelUpUCourse-CCPCn58_.js","assets/MobileAgentApp-DvgetW7C.js","assets/StagingStudio-BL8VxtBn.js","assets/presets-BaI_J6pZ.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-1qdVCfj1.js","assets/BuyCreditsDialog-CyZ2OFcc.js","assets/StagingLibrary-B9ZawrS2.js","assets/StagingCredits-BYlflo60.js","assets/AgentWallet-CS2FKzFC.js","assets/useHomeReel-OVtGGwMl.js","assets/StagingSharePage-BJe5vZGA.js","assets/StagingStudioAdmin-CvCOWaWN.js","assets/ContactFinderAdmin-C2sSF_gX.js","assets/PostcardManager-DMFRmM27.js","assets/PostcardZoneEditor-BblagvMM.js","assets/usePostcardZones-7aL_nVCu.js","assets/MailStudioTemplates-D_JtiA1r.js","assets/HomeReelManager-BYwCPuNI.js","assets/videoRenderSink-KDd1M0JO.js","assets/AdminMusicVideos-BJznJfQn.js","assets/AdminVideoLab-C0a2SAII.js","assets/BoostPreview-DKzvQLa8.js","assets/AdminCredits-B3nI5Sd5.js","assets/MailStudio-CrWIViMv.js","assets/farmToCrm-BLKDtw4F.js","assets/artwork-DBLM2_hb.js","assets/MailStudio-D-BotKHo.css","assets/InnerCirclePopbyMap-BfiyHZnu.js","assets/SphereMap-C2oQS8Lq.js","assets/PropertyIntelligenceDashboard-CPtHuDy8.js","assets/LiveVisitorFeed-DbPRq-XF.js","assets/LeadSites-DbdCRuhu.js","assets/LeadSiteEditor-Ddnco6Rk.js","assets/ImageUrlField-BE84ll_O.js","assets/HomepageModuleManager-BhO3gDqT.js","assets/VideoUrlField-CV3KGRek.js","assets/AdminLeadSiteThemes-Du73jChV.js","assets/AdminFreeWebsiteOfferStudio-mqvybYl4.js","assets/AdminMlsFeeds-YZaiBWCv.js","assets/AdminWebsiteRequests-DKQ8sbjB.js","assets/NeedAWebsite-D-ta1UQm.js","assets/MLSListings-ByAPDZcA.js","assets/MLSListingDetail-LVvgJvPh.js","assets/WebsiteActivityPage-CkPklE9w.js","assets/PublicRecruitForm-vhTv1Ng2.js","assets/PublicEventInviteUnsubscribe-BUVyIPzp.js","assets/SocialConnections-oByQsA5K.js","assets/SocialConnectionsCallback-_-on99YE.js","assets/LinkedInCallback-AjpANj5t.js","assets/TikTokCallback-Dclqb4oT.js","assets/MarketplaceCart-CXrsC7RT.js","assets/MarketplaceOrderDetail-BsQe-3dE.js","assets/RewardStore-BZU7D4Vn.js","assets/ReferFriends-Cf04-dox.js","assets/SmartPresentations-DjdW2V97.js","assets/useSmartPresentations-CFo1AtoN.js","assets/SmartPresentationCreate-DDzvNb3Z.js","assets/TeleprompterOverlay-DYfHRRF0.js","assets/GuestBook-B0RpZS2w.js","assets/SignDocument-BQ6vR6vc.js","assets/Blog-CeSsLzgv.js","assets/TrialCTA-JgdWlKNR.js","assets/BlogPost-BJWo5qy1.js","assets/AdminBlog-8gXmvGfx.js","assets/ReviewLanding-gIv5ucvi.js","assets/ReviewIntake-D3fzqgt-.js","assets/PublicReviewsPage-C4ZxEagF.js","assets/PublicReviewSubmit-DEbcVco_.js","assets/Reviews-CgmhvyZT.js","assets/LenderHub-S_fBHTmO.js","assets/states-BVqvKcH4.js","assets/LendersLanding-BwqlFfxa.js","assets/LendingPartners-BigV0Ze9.js","assets/AdminLenders-CoqNwuiI.js","assets/CardStudio-CmFXRX5j.js","assets/ListingStudio-BCT6YhbL.js","assets/SmartDrips-C-6yoCsj.js","assets/WeeklyReels-FYaCmvMJ.js","assets/ReelCard-Dgi5x5un.js","assets/useWeeklyReels-BHbpldRl.js","assets/WeeklyReelsOnboarding-C3nJN8Nx.js","assets/WeeklyReelsAdmin-DISH1hy_.js","assets/AttractLayout-BrxaU7JW.js","assets/useAttractSettings-Cv82bklx.js","assets/useAttractIntelligence-BeByV9sT.js","assets/HealthScoreBadge-idej4Cnl.js","assets/AttractToday-CmTA4UzA.js","assets/useAttractIntelSync-CTWwaFFO.js","assets/useAttractAgents-CGbz-kpV.js","assets/useAttractFollowUps-DCsRQmKs.js","assets/useAttractActivities-Bht8KGEP.js","assets/RecommendationCard-BNsMJGq8.js","assets/QuickAddRelationship-DV4mH_et.js","assets/relationshipStages-Buh5_cBI.js","assets/useAttractEvents-Djfls_jW.js","assets/AttractRelationships-CHxdMzns.js","assets/AttractPageHeader-DPY2lbgL.js","assets/AgentEditSheet-B8jwblTv.js","assets/AttractFollowUp-vY8ZasUZ.js","assets/AttractTemplates-CNSOATMs.js","assets/AttractReports-BH2sewcr.js","assets/AttractSettings-CsrupXBW.js","assets/AttractToolkit-CRGkk0BY.js","assets/Objections-Otx5uwaQ.js","assets/AttractCalculator-DFc8zylx.js","assets/attractionPageTemplate-C9AaZMgq.js","assets/AttractEventList-CieuGmxE.js","assets/AttractEventBuilder-Cv0L3W69.js","assets/useAttractKits-RScF-FiV.js","assets/AttractEventDetail-BtDAPuWz.js","assets/AttractEventCheckIn-BYsQ00Qx.js","assets/AttractOnboarding--jGZwPOC.js","assets/ContentStudio-Che7zqBM.js","assets/KitList-BeA53PFs.js","assets/KitBuilder-pBS6sH6b.js","assets/KitPreview-CDy0mK7h.js","assets/KitAnalytics-BacOuerW.js","assets/KitTemplates-Dm13xRMq.js","assets/AttractAgentDetail-DRkjv8QD.js","assets/AttractOpportunities-D__St6Oa.js","assets/AttractIntelligenceDebug-CTzDBXKX.js","assets/PublicAttractKit-j4diF7eW.js","assets/PublicAttractEvent-L2cExoBj.js","assets/PublicAttractionPage-D41HTTcs.js","assets/AttractionPageView-BueB88xX.js","assets/RevivalLanding-DTzV6oR4.js","assets/types-Bbp_6W6m.js","assets/RevivalPlan-_rWiyUfe.js","assets/revivalPdf-wXZtL1Ca.js","assets/ListingRevival-Cus2Dq9K.js","assets/useListingRevival-D3VJZDHe.js","assets/AreaChart-6D_OAkhO.js","assets/RevivalCampaignWizard-BGDkX2wG.js","assets/campaignMail-Dt-_hToo.js","assets/RevivalCampaignDetail-EEupn-cT.js","assets/LetterEditor-FNg1Bf5j.js","assets/FsboBreakthrough-BdmD3dOb.js","assets/useFsboBreakthrough-CCOc3J_B.js","assets/types-CK1tolb7.js","assets/FsboPropertyDialog-Dt7YuMo7.js","assets/FsboCampaignWizard-u3m9z2mB.js","assets/FsboCampaignDetail-Bb8vuH2e.js","assets/FsboLanding-Cvy0PryD.js","assets/publicApi-BEaFpcRg.js","assets/FsboGuide-ytYDLII7.js","assets/FsboBreakthroughAdmin-B1E48rqJ.js","assets/AttractLandingPageBuilder-CgWw1CvX.js","assets/AttractAccess-nv0dHJvv.js","assets/Teams-DiDq8hMM.js","assets/MyTeam-DB9G-CJi.js","assets/TeamLeaderSettings-BUApC8WI.js","assets/TeamHub-Db8E_ABy.js","assets/SchedulerSettings-CQ0QBMgf.js","assets/MyCalendar-DLupxMyI.js","assets/BookingManagePage-Cew2uH68.js","assets/LandingPages-DlQVKEq3.js","assets/BuyerMatch-x3tx7eBC.js","assets/SendBuyerMatchEmailDialog-9-UL7Asi.js","assets/BuyerMatchEditor-CiCJoDVs.js","assets/matching-BdEgbJjD.js","assets/PublicBuyerMatch-Bh4CWH-H.js","assets/LandingPageEditor-CdKcG9OB.js","assets/LandingPageDefaults-DWGauuDZ.js","assets/WebsiteAppsHub-CHsF_kks.js","assets/ClaimFreeLeadSiteCard-B8UXqbql.js","assets/useWebsiteApps-BM9KnNxs.js","assets/ClaimWebsite-Bi7CSp_m.js","assets/VideoGreeterEditor-BtlIRawG.js","assets/ExitIntentEditor-sKAxD0iC.js","assets/widgetTemplates-keLygp7O.js","assets/LeadMagnetEditor-Cujj-60d.js","assets/RelationshipScorecard-BVE7obpy.js","assets/SphereGaps-EuybS2Zb.js","assets/ConnectPageSettings-CC3j2Nmq.js","assets/EmailCampaigns-BUwUn_TF.js","assets/sesRequest-DLnLEA0I.js","assets/EmailCompliance-B_9R7RHk.js","assets/EmailCampaignComposer-C9bzL80b.js","assets/EditorModeSelector-C3cClmb7.js","assets/EmailCampaignDetail-BUh7I9pC.js","assets/SharedCampaignTemplates-BXSllPag.js","assets/TemplateEditorDialog-Do9LnKry.js","assets/AgentTemplates-DxTfyiEC.js","assets/TheLocalMoveHome-CCqZM9DZ.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-DPS7KYln.js","assets/TheLocalMoveCheckout-tKpZMdHZ.js","assets/AdminWebsiteOrders-UHn-mTVr.js"])))=>i.map(i=>d[i]); var hNe=Object.defineProperty;var KQ=t=>{throw TypeError(t)};var fNe=(t,e,r)=>e in t?hNe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var un=(t,e,r)=>fNe(t,typeof e!="symbol"?e+"":e,r),dB=(t,e,r)=>e.has(t)||KQ("Cannot "+r);var Tt=(t,e,r)=>(dB(t,e,"read from private field"),r?r.call(t):e.get(t)),Xn=(t,e,r)=>e.has(t)?KQ("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),vn=(t,e,r,n)=>(dB(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ui=(t,e,r)=>(dB(t,e,"access private method"),r);var cP=(t,e,r,n)=>({set _(i){vn(t,e,i,r)},get _(){return Tt(t,e,n)}});function mNe(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 o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();var Ql=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 pNe(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 Oue={exports:{}},dO={},Fue={exports:{}},Yi={};/** * @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 Gk=Symbol.for("react.element"),gNe=Symbol.for("react.portal"),yNe=Symbol.for("react.fragment"),xNe=Symbol.for("react.strict_mode"),_Ne=Symbol.for("react.profiler"),vNe=Symbol.for("react.provider"),bNe=Symbol.for("react.context"),wNe=Symbol.for("react.forward_ref"),SNe=Symbol.for("react.suspense"),TNe=Symbol.for("react.memo"),ENe=Symbol.for("react.lazy"),YQ=Symbol.iterator;function ANe(t){return t===null||typeof t!="object"?null:(t=YQ&&t[YQ]||t["@@iterator"],typeof t=="function"?t:null)}var Bue={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},zue=Object.assign,$ue={};function TS(t,e,r){this.props=t,this.context=e,this.refs=$ue,this.updater=r||Bue}TS.prototype.isReactComponent={};TS.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")};TS.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Uue(){}Uue.prototype=TS.prototype;function rG(t,e,r){this.props=t,this.context=e,this.refs=$ue,this.updater=r||Bue}var nG=rG.prototype=new Uue;nG.constructor=rG;zue(nG,TS.prototype);nG.isPureReactComponent=!0;var ZQ=Array.isArray,Vue=Object.prototype.hasOwnProperty,iG={current:null},que={key:!0,ref:!0,__self:!0,__source:!0};function Gue(t,e,r){var n,i={},o=null,c=null;if(e!=null)for(n in e.ref!==void 0&&(c=e.ref),e.key!==void 0&&(o=""+e.key),e)Vue.call(e,n)&&!que.hasOwnProperty(n)&&(i[n]=e[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1>>1,ve=me[Se];if(0>>1;Sei(at,Ie))Eti(_t,at)?(me[Se]=_t,me[Et]=Ie,Se=Et):(me[Se]=at,me[rt]=Ie,Se=rt);else if(Eti(_t,Ie))me[Se]=_t,me[Et]=Ie,Se=Et;else break e}}return Pe}function i(me,Pe){var Ie=me.sortIndex-Pe.sortIndex;return Ie!==0?Ie:me.id-Pe.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;t.unstable_now=function(){return o.now()}}else{var c=Date,s=c.now();t.unstable_now=function(){return c.now()-s}}var f=[],p=[],y=1,_=null,T=3,E=!1,k=!1,P=!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(me){for(var Pe=r(p);Pe!==null;){if(Pe.callback===null)n(p);else if(Pe.startTime<=me)n(p),Pe.sortIndex=Pe.expirationTime,e(f,Pe);else break;Pe=r(p)}}function V(me){if(P=!1,B(me),!k)if(r(f)!==null)k=!0,Ae(G);else{var Pe=r(p);Pe!==null&&be(V,Pe.startTime-me)}}function G(me,Pe){k=!1,P&&(P=!1,D(Q),Q=-1),E=!0;var Ie=T;try{for(B(Pe),_=r(f);_!==null&&(!(_.expirationTime>Pe)||me&&!ue());){var Se=_.callback;if(typeof Se=="function"){_.callback=null,T=_.priorityLevel;var ve=Se(_.expirationTime<=Pe);Pe=t.unstable_now(),typeof ve=="function"?_.callback=ve:_===r(f)&&n(f),B(Pe)}else n(f);_=r(f)}if(_!==null)var We=!0;else{var rt=r(p);rt!==null&&be(V,rt.startTime-Pe),We=!1}return We}finally{_=null,T=Ie,E=!1}}var W=!1,Z=null,Q=-1,re=5,se=-1;function ue(){return!(t.unstable_now()-seme||125Se?(me.sortIndex=Ie,e(p,me),r(f)===null&&me===r(p)&&(P?(D(Q),Q=-1):P=!0,be(V,Ie-Se))):(me.sortIndex=ve,e(f,me),k||E||(k=!0,Ae(G))),me},t.unstable_shouldYield=ue,t.unstable_wrapCallback=function(me){var Pe=T;return function(){var Ie=T;T=Pe;try{return me.apply(this,arguments)}finally{T=Ie}}}})(Zue);Yue.exports=Zue;var ONe=Yue.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 FNe=I,ud=ONe;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"),p6=Object.prototype.hasOwnProperty,BNe=/^[: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]*$/,QQ={},JQ={};function zNe(t){return p6.call(JQ,t)?!0:p6.call(QQ,t)?!1:BNe.test(t)?JQ[t]=!0:(QQ[t]=!0,!1)}function $Ne(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 UNe(t,e,r,n){if(e===null||typeof e>"u"||$Ne(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 iu(t,e,r,n,i,o,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=o,this.removeEmptyString=c}var nc={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){nc[t]=new iu(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];nc[e]=new iu(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){nc[t]=new iu(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){nc[t]=new iu(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){nc[t]=new iu(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){nc[t]=new iu(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){nc[t]=new iu(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){nc[t]=new iu(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){nc[t]=new iu(t,5,!1,t.toLowerCase(),null,!1,!1)});var oG=/[\-:]([a-z])/g;function lG(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(oG,lG);nc[e]=new iu(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(oG,lG);nc[e]=new iu(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(oG,lG);nc[e]=new iu(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){nc[t]=new iu(t,1,!1,t.toLowerCase(),null,!1,!1)});nc.xlinkHref=new iu("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){nc[t]=new iu(t,1,!1,t.toLowerCase(),null,!0,!0)});function cG(t,e,r,n){var i=nc.hasOwnProperty(e)?nc[e]:null;(i!==null?i.type!==0:n||!(2s||i[c]!==o[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{mB=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?uA(t):""}function VNe(t){switch(t.tag){case 5:return uA(t.type);case 16:return uA("Lazy");case 13:return uA("Suspense");case 19:return uA("SuspenseList");case 0:case 2:case 15:return t=pB(t.type,!1),t;case 11:return t=pB(t.type.render,!1),t;case 1:return t=pB(t.type,!0),t;default:return""}}function _6(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 _w:return"Fragment";case xw:return"Portal";case g6:return"Profiler";case uG:return"StrictMode";case y6:return"Suspense";case x6:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case Jue:return(t.displayName||"Context")+".Consumer";case Que:return(t._context.displayName||"Context")+".Provider";case dG:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case hG:return e=t.displayName||null,e!==null?e:_6(t.type)||"Memo";case iy:e=t._payload,t=t._init;try{return _6(t(e))}catch{}}return null}function qNe(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 _6(e);case 8:return e===uG?"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 Hy(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function tde(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function GNe(t){var e=tde(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,o=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(c){n=""+c,o.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 hP(t){t._valueTracker||(t._valueTracker=GNe(t))}function rde(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=tde(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function ML(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 v6(t,e){var r=e.checked;return no({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function tJ(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=Hy(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 nde(t,e){e=e.checked,e!=null&&cG(t,"checked",e,!1)}function b6(t,e){nde(t,e);var r=Hy(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")?w6(t,e.type,r):e.hasOwnProperty("defaultValue")&&w6(t,e.type,Hy(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function rJ(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 w6(t,e,r){(e!=="number"||ML(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var dA=Array.isArray;function $w(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=fP.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function aj(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},HNe=["Webkit","ms","Moz","O"];Object.keys(EA).forEach(function(t){HNe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),EA[e]=EA[t]})});function ode(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 lde(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=ode(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var WNe=no({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 E6(t,e){if(e){if(WNe[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 A6(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 j6=null;function fG(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var k6=null,Uw=null,Vw=null;function sJ(t){if(t=Kk(t)){if(typeof k6!="function")throw Error(Vr(280));var e=t.stateNode;e&&(e=gO(e),k6(t.stateNode,t.type,e))}}function cde(t){Uw?Vw?Vw.push(t):Vw=[t]:Uw=t}function ude(){if(Uw){var t=Uw,e=Vw;if(Vw=Uw=null,sJ(t),e)for(t=0;t>>=0,t===0?32:31-(iPe(t)/sPe|0)|0}var mP=64,pP=4194304;function hA(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 zL(t,e){var r=t.pendingLanes;if(r===0)return 0;var n=0,i=t.suspendedLanes,o=t.pingedLanes,c=r&268435455;if(c!==0){var s=c&~i;s!==0?n=hA(s):(o&=c,o!==0&&(n=hA(o)))}else c=r&~i,c!==0?n=hA(c):o!==0&&(n=hA(o));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,o=e&-e,i>=o||i===16&&(o&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 Hk(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-ef(e),t[e]=r}function cPe(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=jA),mJ=" ",pJ=!1;function Ide(t,e){switch(t){case"keyup":return OPe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Nde(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var vw=!1;function BPe(t,e){switch(t){case"compositionend":return Nde(e);case"keypress":return e.which!==32?null:(pJ=!0,mJ);case"textInput":return t=e.data,t===mJ&&pJ?null:t;default:return null}}function zPe(t,e){if(vw)return t==="compositionend"||!bG&&Ide(t,e)?(t=kde(),GR=xG=Ey=null,vw=!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=_J(r)}}function Dde(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Dde(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Mde(){for(var t=window,e=ML();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=ML(t.document)}return e}function wG(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 YPe(t){var e=Mde(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&Dde(r.ownerDocument.documentElement,r)){if(n!==null&&wG(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,o=Math.min(n.start,i);n=n.end===void 0?o:Math.min(n.end,i),!t.extend&&o>n&&(i=n,n=o,o=i),i=vJ(r,o);var c=vJ(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(),o>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,bw=null,L6=null,CA=null,D6=!1;function bJ(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;D6||bw==null||bw!==ML(n)||(n=bw,"selectionStart"in n&&wG(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}),CA&&hj(CA,n)||(CA=n,n=VL(L6,"onSelect"),0Tw||(t.current=$6[Tw],$6[Tw]=null,Tw--)}function ya(t,e){Tw++,$6[Tw]=t.current,t.current=e}var Wy={},bc=hx(Wy),Cu=hx(!1),R_=Wy;function E1(t,e){var r=t.type.contextTypes;if(!r)return Wy;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=e[o];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function Iu(t){return t=t.childContextTypes,t!=null}function GL(){Ra(Cu),Ra(bc)}function kJ(t,e,r){if(bc.current!==Wy)throw Error(Vr(168));ya(bc,e),ya(Cu,r)}function Gde(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,qNe(t)||"Unknown",i));return no({},r,n)}function HL(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||Wy,R_=bc.current,ya(bc,t),ya(Cu,Cu.current),!0}function CJ(t,e,r){var n=t.stateNode;if(!n)throw Error(Vr(169));r?(t=Gde(t,e,R_),n.__reactInternalMemoizedMergedChildContext=t,Ra(Cu),Ra(bc),ya(bc,t)):Ra(Cu),ya(Cu,r)}var yp=null,yO=!1,CB=!1;function Hde(t){yp===null?yp=[t]:yp.push(t)}function oRe(t){yO=!0,Hde(t)}function fx(){if(!CB&&yp!==null){CB=!0;var t=0,e=Vs;try{var r=yp;for(Vs=1;t>=c,i-=c,bp=1<<32-ef(e)+i|r<Q?(re=Z,Z=null):re=Z.sibling;var se=T(D,Z,B[Q],V);if(se===null){Z===null&&(Z=re);break}t&&Z&&se.alternate===null&&e(D,Z),M=o(se,M,Q),W===null?G=se:W.sibling=se,W=se,Z=re}if(Q===B.length)return r(D,Z),za&&K0(D,Q),G;if(Z===null){for(;QQ?(re=Z,Z=null):re=Z.sibling;var ue=T(D,Z,se.value,V);if(ue===null){Z===null&&(Z=re);break}t&&Z&&ue.alternate===null&&e(D,Z),M=o(ue,M,Q),W===null?G=ue:W.sibling=ue,W=ue,Z=re}if(se.done)return r(D,Z),za&&K0(D,Q),G;if(Z===null){for(;!se.done;Q++,se=B.next())se=_(D,se.value,V),se!==null&&(M=o(se,M,Q),W===null?G=se:W.sibling=se,W=se);return za&&K0(D,Q),G}for(Z=n(D,Z);!se.done;Q++,se=B.next())se=E(Z,D,Q,se.value,V),se!==null&&(t&&se.alternate!==null&&Z.delete(se.key===null?Q:se.key),M=o(se,M,Q),W===null?G=se:W.sibling=se,W=se);return t&&Z.forEach(function(_e){return e(D,_e)}),za&&K0(D,Q),G}function R(D,M,B,V){if(typeof B=="object"&&B!==null&&B.type===_w&&B.key===null&&(B=B.props.children),typeof B=="object"&&B!==null){switch(B.$$typeof){case dP:e:{for(var G=B.key,W=M;W!==null;){if(W.key===G){if(G=B.type,G===_w){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===iy&&PJ(G)===W.type){r(D,W.sibling),M=i(W,B.props),M.ref=N2(D,W,B),M.return=D,D=M;break e}r(D,W);break}else e(D,W);W=W.sibling}B.type===_w?(M=j_(B.props.children,D.mode,V,B.key),M.return=D,D=M):(V=JR(B.type,B.key,B.props,null,D.mode,V),V.ref=N2(D,M,B),V.return=D,D=V)}return c(D);case xw: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=OB(B,D.mode,V),M.return=D,D=M}return c(D);case iy:return W=B._init,R(D,M,W(B._payload),V)}if(dA(B))return k(D,M,B,V);if(A2(B))return P(D,M,B,V);wP(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=MB(B,D.mode,V),M.return=D,D=M),c(D)):r(D,M)}return R}var j1=Zde(!0),Xde=Zde(!1),YL=hx(null),ZL=null,jw=null,AG=null;function jG(){AG=jw=ZL=null}function kG(t){var e=YL.current;Ra(YL),t._currentValue=e}function q6(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 Gw(t,e){ZL=t,AG=jw=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Au=!0),t.firstContext=null)}function ih(t){var e=t._currentValue;if(AG!==t)if(t={context:t,memoizedValue:e,next:null},jw===null){if(ZL===null)throw Error(Vr(308));jw=t,ZL.dependencies={lanes:0,firstContext:t}}else jw=jw.next=t;return e}var a_=null;function CG(t){a_===null?a_=[t]:a_.push(t)}function Qde(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,CG(e)):(r.next=i.next,i.next=r),e.interleaved=r,Mp(t,n)}function Mp(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 sy=!1;function IG(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Jde(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 Ap(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Dy(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,ps&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Mp(t,r)}return i=n.interleaved,i===null?(e.next=e,CG(n)):(e.next=i.next,i.next=e),n.interleaved=e,Mp(t,r)}function WR(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,pG(t,r)}}function RJ(t,e){var r=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,o=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};o===null?i=o=c:o=o.next=c,r=r.next}while(r!==null);o===null?i=o=e:o=o.next=e}else i=o=e;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:o,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;sy=!1;var o=i.firstBaseUpdate,c=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var f=s,p=f.next;f.next=null,c===null?o=p:c.next=p,c=f;var y=t.alternate;y!==null&&(y=y.updateQueue,s=y.lastBaseUpdate,s!==c&&(s===null?y.firstBaseUpdate=p:s.next=p,y.lastBaseUpdate=f))}if(o!==null){var _=i.baseState;c=0,y=p=f=null,s=o;do{var T=s.lane,E=s.eventTime;if((n&T)===T){y!==null&&(y=y.next={eventTime:E,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});e:{var k=t,P=s;switch(T=e,E=r,P.tag){case 1:if(k=P.payload,typeof k=="function"){_=k.call(E,_,T);break e}_=k;break e;case 3:k.flags=k.flags&-65537|128;case 0:if(k=P.payload,T=typeof k=="function"?k.call(E,_,T):k,T==null)break e;_=no({},_,T);break e;case 2:sy=!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},y===null?(p=y=E,f=_):y=y.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(y===null&&(f=_),i.baseState=f,i.firstBaseUpdate=p,i.lastBaseUpdate=y,e=i.shared.interleaved,e!==null){i=e;do c|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);M_|=c,t.lanes=c,t.memoizedState=_}}function LJ(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=NB.transition;NB.transition={};try{t(!1),e()}finally{Vs=r,NB.transition=n}}function ghe(){return sh().memoizedState}function dRe(t,e,r){var n=Oy(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},yhe(t))xhe(e,r);else if(r=Qde(t,e,r,n),r!==null){var i=eu();tf(r,t,n,i),_he(r,e,n)}}function hRe(t,e,r){var n=Oy(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(yhe(t))xhe(e,i);else{var o=t.alternate;if(t.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var c=e.lastRenderedState,s=o(c,r);if(i.hasEagerState=!0,i.eagerState=s,af(s,c)){var f=e.interleaved;f===null?(i.next=i,CG(e)):(i.next=f.next,f.next=i),e.interleaved=i;return}}catch{}finally{}r=Qde(t,e,i,n),r!==null&&(i=eu(),tf(r,t,n,i),_he(r,e,n))}}function yhe(t){var e=t.alternate;return t===to||e!==null&&e===to}function xhe(t,e){IA=JL=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function _he(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,pG(t,r)}}var eD={readContext:ih,useCallback:mc,useContext:mc,useEffect:mc,useImperativeHandle:mc,useInsertionEffect:mc,useLayoutEffect:mc,useMemo:mc,useReducer:mc,useRef:mc,useState:mc,useDebugValue:mc,useDeferredValue:mc,useTransition:mc,useMutableSource:mc,useSyncExternalStore:mc,useId:mc,unstable_isNewReconciler:!1},fRe={readContext:ih,useCallback:function(t,e){return Bf().memoizedState=[t,e===void 0?null:e],t},useContext:ih,useEffect:MJ,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,YR(4194308,4,dhe.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=Bf();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Bf();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=dRe.bind(null,to,t),[n.memoizedState,t]},useRef:function(t){var e=Bf();return t={current:t},e.memoizedState=t},useState:DJ,useDebugValue:FG,useDeferredValue:function(t){return Bf().memoizedState=t},useTransition:function(){var t=DJ(!1),e=t[0];return t=uRe.bind(null,t[1]),Bf().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=to,i=Bf();if(za){if(r===void 0)throw Error(Vr(407));r=r()}else{if(r=e(),Ll===null)throw Error(Vr(349));D_&30||nhe(n,e,r)}i.memoizedState=r;var o={value:r,getSnapshot:e};return i.queue=o,MJ(she.bind(null,n,o,t),[t]),n.flags|=2048,vj(9,ihe.bind(null,n,o,r,e),void 0,null),r},useId:function(){var t=Bf(),e=Ll.identifierPrefix;if(za){var r=wp,n=bp;r=(n&~(1<<32-ef(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=xj++,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[Wf]=e,t[pj]=n,Che(t,e,!1,!1),e.stateNode=t;e:{switch(c=A6(r,n),r){case"dialog":Ca("cancel",t),Ca("close",t),i=n;break;case"iframe":case"object":case"embed":Ca("load",t),i=n;break;case"video":case"audio":for(i=0;iI1&&(e.flags|=128,n=!0,P2(o,!1),e.lanes=4194304)}else{if(!n)if(t=QL(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),P2(o,!0),o.tail===null&&o.tailMode==="hidden"&&!c.alternate&&!za)return pc(e),null}else 2*Ao()-o.renderingStartTime>I1&&r!==1073741824&&(e.flags|=128,n=!0,P2(o,!1),e.lanes=4194304);o.isBackwards?(c.sibling=e.child,e.child=c):(r=o.last,r!==null?r.sibling=c:e.child=c,o.last=c)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Ao(),e.sibling=null,r=Qa.current,ya(Qa,n?r&1|2:r&1),e):(pc(e),null);case 22:case 23:return qG(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Xu&1073741824&&(pc(e),e.subtreeFlags&6&&(e.flags|=8192)):pc(e),null;case 24:return null;case 25:return null}throw Error(Vr(156,e.tag))}function bRe(t,e){switch(TG(e),e.tag){case 1:return Iu(e.type)&&GL(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return k1(),Ra(Cu),Ra(bc),RG(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return PG(e),null;case 13:if(Ra(Qa),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Vr(340));A1()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Ra(Qa),null;case 4:return k1(),null;case 10:return kG(e.type._context),null;case 22:case 23:return qG(),null;case 24:return null;default:return null}}var TP=!1,xc=!1,wRe=typeof WeakSet=="function"?WeakSet:Set,An=null;function kw(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){fo(t,e,n)}else r.current=null}function J6(t,e,r){try{r()}catch(n){fo(t,e,n)}}var WJ=!1;function SRe(t,e){if(M6=$L,t=Mde(),wG(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,o=n.focusNode;n=n.focusOffset;try{r.nodeType,o.nodeType}catch{r=null;break e}var c=0,s=-1,f=-1,p=0,y=0,_=t,T=null;t:for(;;){for(var E;_!==r||i!==0&&_.nodeType!==3||(s=c+i),_!==o||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&&++p===i&&(s=c),T===o&&++y===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(O6={focusedElem:t,selectionRange:r},$L=!1,An=e;An!==null;)if(e=An,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,An=t;else for(;An!==null;){e=An;try{var k=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(k!==null){var P=k.memoizedProps,R=k.memoizedState,D=e.stateNode,M=D.getSnapshotBeforeUpdate(e.elementType===e.type?P:Fh(e.type,P),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){fo(e,e.return,V)}if(t=e.sibling,t!==null){t.return=e.return,An=t;break}An=e.return}return k=WJ,WJ=!1,k}function NA(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 o=i.destroy;i.destroy=void 0,o!==void 0&&J6(e,r,o)}i=i.next}while(i!==n)}}function vO(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 eU(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 Phe(t){var e=t.alternate;e!==null&&(t.alternate=null,Phe(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Wf],delete e[pj],delete e[z6],delete e[sRe],delete e[aRe])),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 Rhe(t){return t.tag===5||t.tag===3||t.tag===4}function KJ(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Rhe(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 tU(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=qL));else if(n!==4&&(t=t.child,t!==null))for(tU(t,e,r),t=t.sibling;t!==null;)tU(t,e,r),t=t.sibling}function rU(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(rU(t,e,r),t=t.sibling;t!==null;)rU(t,e,r),t=t.sibling}var Vl=null,$h=!1;function $g(t,e,r){for(r=r.child;r!==null;)Lhe(t,e,r),r=r.sibling}function Lhe(t,e,r){if(rm&&typeof rm.onCommitFiberUnmount=="function")try{rm.onCommitFiberUnmount(hO,r)}catch{}switch(r.tag){case 5:xc||kw(r,e);case 6:var n=Vl,i=$h;Vl=null,$g(t,e,r),Vl=n,$h=i,Vl!==null&&($h?(t=Vl,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):Vl.removeChild(r.stateNode));break;case 18:Vl!==null&&($h?(t=Vl,r=r.stateNode,t.nodeType===8?kB(t.parentNode,r):t.nodeType===1&&kB(t,r),uj(t)):kB(Vl,r.stateNode));break;case 4:n=Vl,i=$h,Vl=r.stateNode.containerInfo,$h=!0,$g(t,e,r),Vl=n,$h=i;break;case 0:case 11:case 14:case 15:if(!xc&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var o=i,c=o.destroy;o=o.tag,c!==void 0&&(o&2||o&4)&&J6(r,e,c),i=i.next}while(i!==n)}$g(t,e,r);break;case 1:if(!xc&&(kw(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(s){fo(r,e,s)}$g(t,e,r);break;case 21:$g(t,e,r);break;case 22:r.mode&1?(xc=(n=xc)||r.memoizedState!==null,$g(t,e,r),xc=n):$g(t,e,r);break;default:$g(t,e,r)}}function YJ(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new wRe),e.forEach(function(n){var i=PRe.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Ih(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~o}if(n=i,n=Ao()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*ERe(n/1960))-n,10t?16:t,Ay===null)var n=!1;else{if(t=Ay,Ay=null,nD=0,ps&6)throw Error(Vr(331));var i=ps;for(ps|=4,An=t.current;An!==null;){var o=An,c=o.child;if(An.flags&16){var s=o.deletions;if(s!==null){for(var f=0;fAo()-UG?A_(t,0):$G|=r),Nu(t,e)}function Uhe(t,e){e===0&&(t.mode&1?(e=pP,pP<<=1,!(pP&130023424)&&(pP=4194304)):e=1);var r=eu();t=Mp(t,e),t!==null&&(Hk(t,e,r),Nu(t,r))}function NRe(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),Uhe(t,r)}function PRe(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),Uhe(t,r)}var Vhe;Vhe=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||Cu.current)Au=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return Au=!1,_Re(t,e,r);Au=!!(t.flags&131072)}else Au=!1,za&&e.flags&1048576&&Wde(e,KL,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;ZR(t,e),t=e.pendingProps;var i=E1(e,bc.current);Gw(e,r),i=DG(null,e,n,t,i,r);var o=MG();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,Iu(n)?(o=!0,HL(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,IG(e),i.updater=_O,e.stateNode=i,i._reactInternals=e,H6(e,n,t,r),e=Y6(null,e,n,!0,o,r)):(e.tag=0,za&&o&&SG(e),Vc(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(ZR(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=LRe(n),t=Fh(n,t),i){case 0:e=K6(null,e,n,t,r);break e;case 1:e=qJ(null,e,n,t,r);break e;case 11:e=UJ(null,e,n,t,r);break e;case 14:e=VJ(null,e,n,Fh(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:Fh(n,i),K6(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Fh(n,i),qJ(t,e,n,i,r);case 3:e:{if(Ahe(e),t===null)throw Error(Vr(387));n=e.pendingProps,o=e.memoizedState,i=o.element,Jde(t,e),XL(e,n,null,r);var c=e.memoizedState;if(n=c.element,o.isDehydrated)if(o={element:n,isDehydrated:!1,cache:c.cache,pendingSuspenseBoundaries:c.pendingSuspenseBoundaries,transitions:c.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=C1(Error(Vr(423)),e),e=GJ(t,e,n,r,i);break e}else if(n!==i){i=C1(Error(Vr(424)),e),e=GJ(t,e,n,r,i);break e}else for(nd=Ly(e.stateNode.containerInfo.firstChild),ad=e,za=!0,Gh=null,r=Xde(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(A1(),n===i){e=Op(t,e,r);break e}Vc(t,e,n,r)}e=e.child}return e;case 5:return ehe(e),t===null&&V6(e),n=e.type,i=e.pendingProps,o=t!==null?t.memoizedProps:null,c=i.children,F6(n,i)?c=null:o!==null&&F6(n,o)&&(e.flags|=32),Ehe(t,e),Vc(t,e,c,r),e.child;case 6:return t===null&&V6(e),null;case 13:return jhe(t,e,r);case 4:return NG(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=j1(e,null,n,r):Vc(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Fh(n,i),UJ(t,e,n,i,r);case 7:return Vc(t,e,e.pendingProps,r),e.child;case 8:return Vc(t,e,e.pendingProps.children,r),e.child;case 12:return Vc(t,e,e.pendingProps.children,r),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,o=e.memoizedProps,c=i.value,ya(YL,n._currentValue),n._currentValue=c,o!==null)if(af(o.value,c)){if(o.children===i.children&&!Cu.current){e=Op(t,e,r);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var s=o.dependencies;if(s!==null){c=o.child;for(var f=s.firstContext;f!==null;){if(f.context===n){if(o.tag===1){f=Ap(-1,r&-r),f.tag=2;var p=o.updateQueue;if(p!==null){p=p.shared;var y=p.pending;y===null?f.next=f:(f.next=y.next,y.next=f),p.pending=f}}o.lanes|=r,f=o.alternate,f!==null&&(f.lanes|=r),q6(o.return,r,e),s.lanes|=r;break}f=f.next}}else if(o.tag===10)c=o.type===e.type?null:o.child;else if(o.tag===18){if(c=o.return,c===null)throw Error(Vr(341));c.lanes|=r,s=c.alternate,s!==null&&(s.lanes|=r),q6(c,r,e),c=o.sibling}else c=o.child;if(c!==null)c.return=o;else for(c=o;c!==null;){if(c===e){c=null;break}if(o=c.sibling,o!==null){o.return=c.return,c=o;break}c=c.return}o=c}Vc(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,Gw(e,r),i=ih(i),n=n(i),e.flags|=1,Vc(t,e,n,r),e.child;case 14:return n=e.type,i=Fh(n,e.pendingProps),i=Fh(n.type,i),VJ(t,e,n,i,r);case 15:return She(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Fh(n,i),ZR(t,e),e.tag=1,Iu(n)?(t=!0,HL(e)):t=!1,Gw(e,r),vhe(e,n,i),H6(e,n,i,r),Y6(null,e,n,!0,t,r);case 19:return khe(t,e,r);case 22:return The(t,e,r)}throw Error(Vr(156,e.tag))};function qhe(t,e){return yde(t,e)}function RRe(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 RRe(t,e,r,n)}function HG(t){return t=t.prototype,!(!t||!t.isReactComponent)}function LRe(t){if(typeof t=="function")return HG(t)?1:0;if(t!=null){if(t=t.$$typeof,t===dG)return 11;if(t===hG)return 14}return 2}function Fy(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 JR(t,e,r,n,i,o){var c=2;if(n=t,typeof t=="function")HG(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case _w:return j_(r.children,i,o,e);case uG:c=8,i|=8;break;case g6:return t=Zd(12,r,e,i|2),t.elementType=g6,t.lanes=o,t;case y6:return t=Zd(13,r,e,i),t.elementType=y6,t.lanes=o,t;case x6:return t=Zd(19,r,e,i),t.elementType=x6,t.lanes=o,t;case ede:return wO(r,i,o,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case Que:c=10;break e;case Jue:c=9;break e;case dG:c=11;break e;case hG:c=14;break e;case iy: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=o,e}function j_(t,e,r,n){return t=Zd(7,t,n,e),t.lanes=r,t}function wO(t,e,r,n){return t=Zd(22,t,n,e),t.elementType=ede,t.lanes=r,t.stateNode={isHidden:!1},t}function MB(t,e,r){return t=Zd(6,t,null,e),t.lanes=r,t}function OB(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 DRe(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=yB(0),this.expirationTimes=yB(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=yB(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function WG(t,e,r,n,i,o,c,s,f){return t=new DRe(t,e,r,s,f),e===1?(e=1,o===!0&&(e|=8)):e=0,o=Zd(3,null,null,e),t.current=o,o.stateNode=t,o.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},IG(o),t}function MRe(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Khe)}catch(t){console.error(t)}}Khe(),Kue.exports=xd;var Yp=Kue.exports;const Yhe=ds(Yp);var Zhe,nee=Yp;Zhe=nee.createRoot,nee.hydrateRoot;const $Re="modulepreload",URe=function(t){return"/"+t},iee={},Fe=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=URe(f),f in iee)return;iee[f]=!0;const p=f.endsWith(".css"),y=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const _=document.createElement("link");if(_.rel=p?"stylesheet":$Re,p||(_.as="script"),_.crossOrigin="",_.href=f,s&&_.setAttribute("nonce",s),document.head.appendChild(_),p)return new Promise((T,E)=>{_.addEventListener("load",T),_.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(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"&&o(s.reason);return e().catch(o)})},VRe=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),qRe=t=>t.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function GRe(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")||VRe.has(t))}function Xhe(t){return Qhe(t)!==null}function Qhe(t){const e=qRe(t);return GRe(e)?null:e}const HRe=1,WRe=1e6;let FB=0;function KRe(){return FB=(FB+1)%Number.MAX_SAFE_INTEGER,FB.toString()}const BB=new Map,see=t=>{if(BB.has(t))return;const e=setTimeout(()=>{BB.delete(t),LA({type:"REMOVE_TOAST",toastId:t})},WRe);BB.set(t,e)},YRe=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,HRe)};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?see(r):t.toasts.forEach(n=>{see(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)}}},eL=[];let tL={toasts:[]};function LA(t){tL=YRe(tL,t),eL.forEach(e=>{e(tL)})}function Ts({...t}){const e=KRe(),r=i=>LA({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>LA({type:"DISMISS_TOAST",toastId:e});return LA({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function Jhe(){const[t,e]=I.useState(tL);return I.useEffect(()=>(eL.push(e),()=>{const r=eL.indexOf(e);r>-1&&eL.splice(r,1)}),[t]),{...t,toast:Ts,dismiss:r=>LA({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 aee(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Fp(...t){return e=>{let r=!1;const n=t.map(i=>{const o=aee(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{children:c,...s}=o,f=I.useMemo(()=>s,Object.values(s));return a.jsx(r.Provider,{value:f,children:c})};n.displayName=t+"Provider";function i(o){const c=I.useContext(r);if(c)return c;if(e!==void 0)return e;throw new Error(`\`${o}\` must be used within \`${t}\``)}return[n,i]}function Yo(t,e=[]){let r=[];function n(o,c){const s=I.createContext(c),f=r.length;r=[...r,c];const p=_=>{var D;const{scope:T,children:E,...k}=_,P=((D=T==null?void 0:T[t])==null?void 0:D[f])||s,R=I.useMemo(()=>k,Object.values(k));return a.jsx(P.Provider,{value:R,children:E})};p.displayName=o+"Provider";function y(_,T){var P;const E=((P=T==null?void 0:T[t])==null?void 0:P[f])||s,k=I.useContext(E);if(k)return k;if(c!==void 0)return c;throw new Error(`\`${_}\` must be used within \`${o}\``)}return[p,y]}const i=()=>{const o=r.map(c=>I.createContext(c));return function(s){const f=(s==null?void 0:s[t])||o;return I.useMemo(()=>({[`__scope${t}`]:{...s,[t]:f}}),[s,f])}};return i.scopeName=t,[n,XRe(i,...e)]}function XRe(...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(o){const c=n.reduce((s,{useScope:f,scopeName:p})=>{const _=f(o)[`__scope${p}`];return{...s,..._}},{});return I.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])}};return r.scopeName=e.scopeName,r}function Ky(t){const e=QRe(t),r=I.forwardRef((n,i)=>{const{children:o,...c}=n,s=I.Children.toArray(o),f=s.find(JRe);if(f){const p=f.props.children,y=s.map(_=>_===f?I.Children.count(p)>1?I.Children.only(null):I.isValidElement(p)?p.props.children:null:_);return a.jsx(e,{...c,ref:i,children:I.isValidElement(p)?I.cloneElement(p,void 0,y):null})}return a.jsx(e,{...c,ref:i,children:o})});return r.displayName=`${t}.Slot`,r}var efe=Ky("Slot");function QRe(t){const e=I.forwardRef((r,n)=>{const{children:i,...o}=r;if(I.isValidElement(i)){const c=tLe(i),s=eLe(o,i.props);return i.type!==I.Fragment&&(s.ref=n?Fp(n,c):c),I.cloneElement(i,s)}return I.Children.count(i)>1?I.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var tfe=Symbol("radix.slottable");function rfe(t){const e=({children:r})=>a.jsx(a.Fragment,{children:r});return e.displayName=`${t}.Slottable`,e.__radixId=tfe,e}function JRe(t){return I.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===tfe}function eLe(t,e){const r={...e};for(const n in e){const i=t[n],o=e[n];/^on[A-Z]/.test(n)?i&&o?r[n]=(...s)=>{const f=o(...s);return i(...s),f}:i&&(r[n]=i):n==="style"?r[n]={...i,...o}:n==="className"&&(r[n]=[i,o].filter(Boolean).join(" "))}return{...t,...r}}function tLe(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 Zk(t){const e=t+"CollectionProvider",[r,n]=Yo(e),[i,o]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=P=>{const{scope:R,children:D}=P,M=Xe.useRef(null),B=Xe.useRef(new Map).current;return a.jsx(i,{scope:R,itemMap:B,collectionRef:M,children:D})};c.displayName=e;const s=t+"CollectionSlot",f=Ky(s),p=Xe.forwardRef((P,R)=>{const{scope:D,children:M}=P,B=o(s,D),V=Kn(R,B.collectionRef);return a.jsx(f,{ref:V,children:M})});p.displayName=s;const y=t+"CollectionItemSlot",_="data-radix-collection-item",T=Ky(y),E=Xe.forwardRef((P,R)=>{const{scope:D,children:M,...B}=P,V=Xe.useRef(null),G=Kn(R,V),W=o(y,D);return Xe.useEffect(()=>(W.itemMap.set(V,{ref:V,...B}),()=>void W.itemMap.delete(V))),a.jsx(T,{[_]:"",ref:G,children:M})});E.displayName=y;function k(P){const R=o(t+"CollectionConsumer",P);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,Z)=>B.indexOf(W.ref.current)-B.indexOf(Z.ref.current))},[R.collectionRef,R.itemMap])}return[{Provider:c,Slot:p,ItemSlot:E},k,n]}var rLe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rn=rLe.reduce((t,e)=>{const r=Ky(`Primitive.${e}`),n=I.forwardRef((i,o)=>{const{asChild:c,...s}=i,f=c?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a.jsx(f,{...s,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function XG(t,e){t&&Yp.flushSync(()=>t.dispatchEvent(e))}function po(t){const e=I.useRef(t);return I.useEffect(()=>{e.current=t}),I.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}function nLe(t,e=globalThis==null?void 0:globalThis.document){const r=po(t);I.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 iLe="DismissableLayer",oU="dismissableLayer.update",sLe="dismissableLayer.pointerDownOutside",aLe="dismissableLayer.focusOutside",oee,nfe=I.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),rv=I.forwardRef((t,e)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:c,onDismiss:s,...f}=t,p=I.useContext(nfe),[y,_]=I.useState(null),T=(y==null?void 0:y.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,E]=I.useState({}),k=Kn(e,Z=>_(Z)),P=Array.from(p.layers),[R]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),D=P.indexOf(R),M=y?P.indexOf(y):-1,B=p.layersWithOutsidePointerEventsDisabled.size>0,V=M>=D,G=lLe(Z=>{const Q=Z.target,re=[...p.branches].some(se=>se.contains(Q));!V||re||(i==null||i(Z),c==null||c(Z),Z.defaultPrevented||s==null||s())},T),W=cLe(Z=>{const Q=Z.target;[...p.branches].some(se=>se.contains(Q))||(o==null||o(Z),c==null||c(Z),Z.defaultPrevented||s==null||s())},T);return nLe(Z=>{M===p.layers.size-1&&(n==null||n(Z),!Z.defaultPrevented&&s&&(Z.preventDefault(),s()))},T),I.useEffect(()=>{if(y)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(oee=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),lee(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=oee)}},[y,T,r,p]),I.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),lee())},[y,p]),I.useEffect(()=>{const Z=()=>E({});return document.addEventListener(oU,Z),()=>document.removeEventListener(oU,Z)},[]),a.jsx(rn.div,{...f,ref:k,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)})});rv.displayName=iLe;var oLe="DismissableLayerBranch",ife=I.forwardRef((t,e)=>{const r=I.useContext(nfe),n=I.useRef(null),i=Kn(e,n);return I.useEffect(()=>{const o=n.current;if(o)return r.branches.add(o),()=>{r.branches.delete(o)}},[r.branches]),a.jsx(rn.div,{...t,ref:i})});ife.displayName=oLe;function lLe(t,e=globalThis==null?void 0:globalThis.document){const r=po(t),n=I.useRef(!1),i=I.useRef(()=>{});return I.useEffect(()=>{const o=s=>{if(s.target&&!n.current){let f=function(){sfe(sLe,r,p,{discrete:!0})};const p={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",o)},0);return()=>{window.clearTimeout(c),e.removeEventListener("pointerdown",o),e.removeEventListener("click",i.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function cLe(t,e=globalThis==null?void 0:globalThis.document){const r=po(t),n=I.useRef(!1);return I.useEffect(()=>{const i=o=>{o.target&&!n.current&&sfe(aLe,r,{originalEvent:o},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function lee(){const t=new CustomEvent(oU);document.dispatchEvent(t)}function sfe(t,e,r,{discrete:n}){const i=r.originalEvent.target,o=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?XG(i,o):i.dispatchEvent(o)}var uLe=rv,dLe=ife,Po=globalThis!=null&&globalThis.document?I.useLayoutEffect:()=>{},hLe="Portal",jS=I.forwardRef((t,e)=>{var s;const{container:r,...n}=t,[i,o]=I.useState(!1);Po(()=>o(!0),[]);const c=r||i&&((s=globalThis==null?void 0:globalThis.document)==null?void 0:s.body);return c?Yhe.createPortal(a.jsx(rn.div,{...n,ref:e}),c):null});jS.displayName=hLe;function fLe(t,e){return I.useReducer((r,n)=>e[r][n]??r,t)}var pl=t=>{const{present:e,children:r}=t,n=mLe(e),i=typeof r=="function"?r({present:n.isPresent}):I.Children.only(r),o=Kn(n.ref,pLe(i));return typeof r=="function"||n.isPresent?I.cloneElement(i,{ref:o}):null};pl.displayName="Presence";function mLe(t){const[e,r]=I.useState(),n=I.useRef(null),i=I.useRef(t),o=I.useRef("none"),c=t?"mounted":"unmounted",[s,f]=fLe(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return I.useEffect(()=>{const p=jP(n.current);o.current=s==="mounted"?p:"none"},[s]),Po(()=>{const p=n.current,y=i.current;if(y!==t){const T=o.current,E=jP(p);t?f("MOUNT"):E==="none"||(p==null?void 0:p.display)==="none"?f("UNMOUNT"):f(y&&T!==E?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,f]),Po(()=>{if(e){let p;const y=e.ownerDocument.defaultView??window,_=E=>{const P=jP(n.current).includes(E.animationName);if(E.target===e&&P&&(f("ANIMATION_END"),!i.current)){const R=e.style.animationFillMode;e.style.animationFillMode="forwards",p=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=R)})}},T=E=>{E.target===e&&(o.current=jP(n.current))};return e.addEventListener("animationstart",T),e.addEventListener("animationcancel",_),e.addEventListener("animationend",_),()=>{y.clearTimeout(p),e.removeEventListener("animationstart",T),e.removeEventListener("animationcancel",_),e.removeEventListener("animationend",_)}}else f("ANIMATION_END")},[e,f]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:I.useCallback(p=>{n.current=p?getComputedStyle(p):null,r(p)},[])}}function jP(t){return(t==null?void 0:t.animationName)||"none"}function pLe(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 gLe=aG[" useInsertionEffect ".trim().toString()]||Po;function dd({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){const[i,o,c]=yLe({defaultProp:e,onChange:r}),s=t!==void 0,f=s?t:i;{const y=I.useRef(t!==void 0);I.useEffect(()=>{const _=y.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.`),y.current=s},[s,n])}const p=I.useCallback(y=>{var _;if(s){const T=xLe(y)?y(t):y;T!==t&&((_=c.current)==null||_.call(c,T))}else o(y)},[s,t,o,c]);return[f,p]}function yLe({defaultProp:t,onChange:e}){const[r,n]=I.useState(t),i=I.useRef(r),o=I.useRef(e);return gLe(()=>{o.current=e},[e]),I.useEffect(()=>{var c;i.current!==r&&((c=o.current)==null||c.call(o,r),i.current=r)},[r,i]),[r,n,o]}function xLe(t){return typeof t=="function"}var afe=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"}),_Le="VisuallyHidden",jO=I.forwardRef((t,e)=>a.jsx(rn.span,{...t,ref:e,style:{...afe,...t.style}}));jO.displayName=_Le;var vLe=jO,QG="ToastProvider",[JG,bLe,wLe]=Zk("Toast"),[ofe,mVt]=Yo("Toast",[wLe]),[SLe,kO]=ofe(QG),lfe=t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:c}=t,[s,f]=I.useState(null),[p,y]=I.useState(0),_=I.useRef(!1),T=I.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${QG}\`. Expected non-empty \`string\`.`),a.jsx(JG.Provider,{scope:e,children:a.jsx(SLe,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:o,toastCount:p,viewport:s,onViewportChange:f,onToastAdd:I.useCallback(()=>y(E=>E+1),[]),onToastRemove:I.useCallback(()=>y(E=>E-1),[]),isFocusedToastEscapeKeyDownRef:_,isClosePausedRef:T,children:c})})};lfe.displayName=QG;var cfe="ToastViewport",TLe=["F8"],lU="toast.viewportPause",cU="toast.viewportResume",ufe=I.forwardRef((t,e)=>{const{__scopeToast:r,hotkey:n=TLe,label:i="Notifications ({hotkey})",...o}=t,c=kO(cfe,r),s=bLe(r),f=I.useRef(null),p=I.useRef(null),y=I.useRef(null),_=I.useRef(null),T=Kn(e,_,c.onViewportChange),E=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),k=c.toastCount>0;I.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]),I.useEffect(()=>{const R=f.current,D=_.current;if(k&&R&&D){const M=()=>{if(!c.isClosePausedRef.current){const W=new CustomEvent(lU);D.dispatchEvent(W),c.isClosePausedRef.current=!0}},B=()=>{if(c.isClosePausedRef.current){const W=new CustomEvent(cU);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)}}},[k,c.isClosePausedRef]);const P=I.useCallback(({tabbingDirection:R})=>{const M=s().map(B=>{const V=B.ref.current,G=[V,...OLe(V)];return R==="forwards"?G:G.reverse()});return(R==="forwards"?M.reverse():M).flat()},[s]);return I.useEffect(()=>{const R=_.current;if(R){const D=M=>{var G,W,Z;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=p.current)==null||G.focus();return}const _e=P({tabbingDirection:re?"backwards":"forwards"}),we=_e.findIndex(Ce=>Ce===Q);zB(_e.slice(we+1))?M.preventDefault():re?(W=p.current)==null||W.focus():(Z=y.current)==null||Z.focus()}};return R.addEventListener("keydown",D),()=>R.removeEventListener("keydown",D)}},[s,P]),a.jsxs(dLe,{ref:f,role:"region","aria-label":i.replace("{hotkey}",E),tabIndex:-1,style:{pointerEvents:k?void 0:"none"},children:[k&&a.jsx(uU,{ref:p,onFocusFromOutsideViewport:()=>{const R=P({tabbingDirection:"forwards"});zB(R)}}),a.jsx(JG.Slot,{scope:r,children:a.jsx(rn.ol,{tabIndex:-1,...o,ref:T})}),k&&a.jsx(uU,{ref:y,onFocusFromOutsideViewport:()=>{const R=P({tabbingDirection:"backwards"});zB(R)}})]})});ufe.displayName=cfe;var dfe="ToastFocusProxy",uU=I.forwardRef((t,e)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...i}=t,o=kO(dfe,r);return a.jsx(jO,{"aria-hidden":!0,tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:c=>{var p;const s=c.relatedTarget;!((p=o.viewport)!=null&&p.contains(s))&&n()}})});uU.displayName=dfe;var Xk="Toast",ELe="toast.swipeStart",ALe="toast.swipeMove",jLe="toast.swipeCancel",kLe="toast.swipeEnd",hfe=I.forwardRef((t,e)=>{const{forceMount:r,open:n,defaultOpen:i,onOpenChange:o,...c}=t,[s,f]=dd({prop:n,defaultProp:i??!0,onChange:o,caller:Xk});return a.jsx(pl,{present:r||s,children:a.jsx(NLe,{open:s,...c,ref:e,onClose:()=>f(!1),onPause:po(t.onPause),onResume:po(t.onResume),onSwipeStart:Or(t.onSwipeStart,p=>{p.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Or(t.onSwipeMove,p=>{const{x:y,y:_}=p.detail.delta;p.currentTarget.setAttribute("data-swipe","move"),p.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${y}px`),p.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${_}px`)}),onSwipeCancel:Or(t.onSwipeCancel,p=>{p.currentTarget.setAttribute("data-swipe","cancel"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),p.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Or(t.onSwipeEnd,p=>{const{x:y,y:_}=p.detail.delta;p.currentTarget.setAttribute("data-swipe","end"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),p.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${y}px`),p.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${_}px`),f(!1)})})})});hfe.displayName=Xk;var[CLe,ILe]=ofe(Xk,{onClose(){}}),NLe=I.forwardRef((t,e)=>{const{__scopeToast:r,type:n="foreground",duration:i,open:o,onClose:c,onEscapeKeyDown:s,onPause:f,onResume:p,onSwipeStart:y,onSwipeMove:_,onSwipeCancel:T,onSwipeEnd:E,...k}=t,P=kO(Xk,r),[R,D]=I.useState(null),M=Kn(e,Ce=>D(Ce)),B=I.useRef(null),V=I.useRef(null),G=i||P.duration,W=I.useRef(0),Z=I.useRef(G),Q=I.useRef(0),{onToastAdd:re,onToastRemove:se}=P,ue=po(()=>{var Me;(R==null?void 0:R.contains(document.activeElement))&&((Me=P.viewport)==null||Me.focus()),c()}),_e=I.useCallback(Ce=>{!Ce||Ce===1/0||(window.clearTimeout(Q.current),W.current=new Date().getTime(),Q.current=window.setTimeout(ue,Ce))},[ue]);I.useEffect(()=>{const Ce=P.viewport;if(Ce){const Me=()=>{_e(Z.current),p==null||p()},Ae=()=>{const be=new Date().getTime()-W.current;Z.current=Z.current-be,window.clearTimeout(Q.current),f==null||f()};return Ce.addEventListener(lU,Ae),Ce.addEventListener(cU,Me),()=>{Ce.removeEventListener(lU,Ae),Ce.removeEventListener(cU,Me)}}},[P.viewport,G,f,p,_e]),I.useEffect(()=>{o&&!P.isClosePausedRef.current&&_e(G)},[o,G,P.isClosePausedRef,_e]),I.useEffect(()=>(re(),()=>se()),[re,se]);const we=I.useMemo(()=>R?_fe(R):null,[R]);return P.viewport?a.jsxs(a.Fragment,{children:[we&&a.jsx(PLe,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:we}),a.jsx(CLe,{scope:r,onClose:ue,children:Yp.createPortal(a.jsx(JG.ItemSlot,{scope:r,children:a.jsx(uLe,{asChild:!0,onEscapeKeyDown:Or(s,()=>{P.isFocusedToastEscapeKeyDownRef.current||ue(),P.isFocusedToastEscapeKeyDownRef.current=!1}),children:a.jsx(rn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":P.swipeDirection,...k,ref:M,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Or(t.onKeyDown,Ce=>{Ce.key==="Escape"&&(s==null||s(Ce.nativeEvent),Ce.nativeEvent.defaultPrevented||(P.isFocusedToastEscapeKeyDownRef.current=!0,ue()))}),onPointerDown:Or(t.onPointerDown,Ce=>{Ce.button===0&&(B.current={x:Ce.clientX,y:Ce.clientY})}),onPointerMove:Or(t.onPointerMove,Ce=>{if(!B.current)return;const Me=Ce.clientX-B.current.x,Ae=Ce.clientY-B.current.y,be=!!V.current,me=["left","right"].includes(P.swipeDirection),Pe=["left","up"].includes(P.swipeDirection)?Math.min:Math.max,Ie=me?Pe(0,Me):0,Se=me?0:Pe(0,Ae),ve=Ce.pointerType==="touch"?10:2,We={x:Ie,y:Se},rt={originalEvent:Ce,delta:We};be?(V.current=We,kP(ALe,_,rt,{discrete:!1})):cee(We,P.swipeDirection,ve)?(V.current=We,kP(ELe,y,rt,{discrete:!1}),Ce.target.setPointerCapture(Ce.pointerId)):(Math.abs(Me)>ve||Math.abs(Ae)>ve)&&(B.current=null)}),onPointerUp:Or(t.onPointerUp,Ce=>{const Me=V.current,Ae=Ce.target;if(Ae.hasPointerCapture(Ce.pointerId)&&Ae.releasePointerCapture(Ce.pointerId),V.current=null,B.current=null,Me){const be=Ce.currentTarget,me={originalEvent:Ce,delta:Me};cee(Me,P.swipeDirection,P.swipeThreshold)?kP(kLe,E,me,{discrete:!0}):kP(jLe,T,me,{discrete:!0}),be.addEventListener("click",Pe=>Pe.preventDefault(),{once:!0})}})})})}),P.viewport)})]}):null}),PLe=t=>{const{__scopeToast:e,children:r,...n}=t,i=kO(Xk,e),[o,c]=I.useState(!1),[s,f]=I.useState(!1);return DLe(()=>c(!0)),I.useEffect(()=>{const p=window.setTimeout(()=>f(!0),1e3);return()=>window.clearTimeout(p)},[]),s?null:a.jsx(jS,{asChild:!0,children:a.jsx(jO,{...n,children:o&&a.jsxs(a.Fragment,{children:[i.label," ",r]})})})},RLe="ToastTitle",ffe=I.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return a.jsx(rn.div,{...n,ref:e})});ffe.displayName=RLe;var LLe="ToastDescription",mfe=I.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return a.jsx(rn.div,{...n,ref:e})});mfe.displayName=LLe;var pfe="ToastAction",gfe=I.forwardRef((t,e)=>{const{altText:r,...n}=t;return r.trim()?a.jsx(xfe,{altText:r,asChild:!0,children:a.jsx(e9,{...n,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${pfe}\`. Expected non-empty \`string\`.`),null)});gfe.displayName=pfe;var yfe="ToastClose",e9=I.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t,i=ILe(yfe,r);return a.jsx(xfe,{asChild:!0,children:a.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,i.onClose)})})});e9.displayName=yfe;var xfe=I.forwardRef((t,e)=>{const{__scopeToast:r,altText:n,...i}=t;return a.jsx(rn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...i,ref:e})});function _fe(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),MLe(n)){const i=n.ariaHidden||n.hidden||n.style.display==="none",o=n.dataset.radixToastAnnounceExclude==="";if(!i)if(o){const c=n.dataset.radixToastAnnounceAlt;c&&e.push(c)}else e.push(..._fe(n))}}),e}function kP(t,e,r,{discrete:n}){const i=r.originalEvent.currentTarget,o=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?XG(i,o):i.dispatchEvent(o)}var cee=(t,e,r=0)=>{const n=Math.abs(t.x),i=Math.abs(t.y),o=n>i;return e==="left"||e==="right"?o&&n>r:!o&&i>r};function DLe(t=()=>{}){const e=po(t);Po(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}function MLe(t){return t.nodeType===t.ELEMENT_NODE}function OLe(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 zB(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}var FLe=lfe,vfe=ufe,bfe=hfe,wfe=ffe,Sfe=mfe,Tfe=gfe,Efe=e9;function Afe(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,dee=Oi,kS=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return dee(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:o}=e,c=Object.keys(i).map(p=>{const y=r==null?void 0:r[p],_=o==null?void 0:o[p];if(y===null)return null;const T=uee(y)||uee(_);return i[p][T]}),s=r&&Object.entries(r).reduce((p,y)=>{let[_,T]=y;return T===void 0||(p[_]=T),p},{}),f=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((p,y)=>{let{class:_,className:T,...E}=y;return Object.entries(E).every(k=>{let[P,R]=k;return Array.isArray(R)?R.includes({...o,...s}[P]):{...o,...s}[P]===R})?[...p,_,T]:p},[]);return dee(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 BLe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),jfe=(...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 zLe={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 $Le=I.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:c,...s},f)=>I.createElement("svg",{ref:f,...zLe,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:jfe("lucide",i),...s},[...c.map(([p,y])=>I.createElement(p,y)),...Array.isArray(o)?o:[o]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lr=(t,e)=>{const r=I.forwardRef(({className:n,...i},o)=>I.createElement($Le,{ref:o,iconNode:e,className:jfe(`lucide-${BLe(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 hee=lr("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 Yy=lr("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 ra=lr("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 ULe=lr("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 kfe=lr("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ww=lr("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 nv=lr("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 VLe=lr("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 CS=lr("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 Qk=lr("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 N1=lr("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 aD=lr("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 qLe=lr("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 Cfe=lr("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 go=lr("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 GLe=lr("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 Ife=lr("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 t9=lr("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 r9=lr("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 im=lr("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 Nfe=lr("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 yo=lr("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 fee=lr("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 wj=lr("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 ko=lr("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 wc=lr("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 xm=lr("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 vd=lr("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 HLe=lr("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 dU=lr("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 Pfe=lr("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 ic=lr("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 WLe=lr("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 n9=lr("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 F_=lr("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 hU=lr("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 $B=lr("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 Rl=lr("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 mee=lr("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 fU=lr("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 jp=lr("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 rc=lr("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 KLe=lr("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 YLe=lr("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 iv=lr("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 CO=lr("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 Rfe=lr("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 ZLe=lr("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 XLe=lr("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 cm=lr("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 pee=lr("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 QLe=lr("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 Lfe=lr("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 rf=lr("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 P1=lr("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 Sj=lr("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 JLe=lr("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 eDe=lr("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 mU=lr("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 um=lr("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 La=lr("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 gee=lr("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 Dfe=lr("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 i9=lr("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 tDe=lr("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 Mfe=lr("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 IO=lr("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 rDe=lr("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 Ofe=lr("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 nDe=lr("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 iDe=lr("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 sDe=lr("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 yee=lr("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 Ffe=lr("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 aDe=lr("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 pU=lr("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 Ru=lr("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=lr("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 NO=lr("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 Ti=lr("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 qs=lr("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 oDe=lr("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 lDe=lr("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jk=lr("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 IS=lr("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 cDe=lr("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 R1=lr("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 of=lr("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 uDe=lr("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 Bfe=lr("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 dDe=lr("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.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:"pqwjuv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xee=lr("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 PO=lr("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 hDe=lr("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 fDe=lr("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 mDe=lr("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 pDe=lr("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 ai=lr("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 gDe=lr("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 oD=lr("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 sm=lr("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 yDe=lr("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 xDe=lr("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 _De=lr("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 zfe=lr("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 vDe=lr("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 _ee=lr("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 RO=lr("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 bDe=lr("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 hd=lr("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 lD=lr("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 s9=lr("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 eC=lr("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 wDe=lr("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 a9=lr("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 Tj=lr("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 $fe=lr("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 SDe=lr("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 UB=lr("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 TDe=lr("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 xs=lr("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 EDe=lr("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 gU=lr("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 o9=lr("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 ru=lr("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 Ufe=lr("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 ADe=lr("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 l9=lr("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 jDe=lr("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 Vfe=lr("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 cD=lr("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 qfe=lr("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 NS=lr("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 PS=lr("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 uD=lr("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 yU=lr("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 xU=lr("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 LO=lr("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 vc=lr("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 ul=lr("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=lr("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 kDe=lr("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 CDe=lr("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 c9=lr("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 IDe=lr("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 u9=lr("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 Ds=lr("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 NDe=lr("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 dD=lr("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 vee=lr("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"}]]),d9="-",PDe=t=>{const e=LDe(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const s=c.split(d9);return s[0]===""&&s.length!==1&&s.shift(),Gfe(s,e)||RDe(c)},getConflictingClassGroupIds:(c,s)=>{const f=r[c]||[];return s&&n[c]?[...f,...n[c]]:f}}},Gfe=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?Gfe(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const o=t.join(d9);return(c=e.validators.find(({validator:s})=>s(o)))==null?void 0:c.classGroupId},bee=/^\[(.+)\]$/,RDe=t=>{if(bee.test(t)){const e=bee.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},LDe=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return MDe(Object.entries(t.classGroups),r).forEach(([o,c])=>{_U(c,n,o,e)}),n},_U=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const o=i===""?e:wee(e,i);o.classGroupId=r;return}if(typeof i=="function"){if(DDe(i)){_U(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([o,c])=>{_U(c,wee(e,o),r,n)})})},wee=(t,e)=>{let r=t;return e.split(d9).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},DDe=t=>t.isThemeGetter,MDe=(t,e)=>e?t.map(([r,n])=>{const i=n.map(o=>typeof o=="string"?e+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([c,s])=>[e+c,s])):o);return[r,i]}):t,ODe=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=new Map,n=new Map;const i=(o,c)=>{r.set(o,c),e++,e>t&&(e=0,n=r,r=new Map)};return{get(o){let c=r.get(o);if(c!==void 0)return c;if((c=n.get(o))!==void 0)return i(o,c),c},set(o,c){r.has(o)?r.set(o,c):i(o,c)}}},Hfe="!",FDe=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],o=e.length,c=s=>{const f=[];let p=0,y=0,_;for(let R=0;Ry?_-y:void 0;return{modifiers:f,hasImportantModifier:E,baseClassName:k,maybePostfixModifierPosition:P}};return r?s=>r({className:s,parseClassName:c}):c},BDe=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},zDe=t=>({cache:ODe(t.cacheSize),parseClassName:FDe(t),...PDe(t)}),$De=/\s+/,UDe=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,o=[],c=t.trim().split($De);let s="";for(let f=c.length-1;f>=0;f-=1){const p=c[f],{modifiers:y,hasImportantModifier:_,baseClassName:T,maybePostfixModifierPosition:E}=r(p);let k=!!E,P=n(k?T.substring(0,E):T);if(!P){if(!k){s=p+(s.length>0?" "+s:s);continue}if(P=n(T),!P){s=p+(s.length>0?" "+s:s);continue}k=!1}const R=BDe(y).join(":"),D=_?R+Hfe:R,M=D+P;if(o.includes(M))continue;o.push(M);const B=i(P,k);for(let V=0;V0?" "+s:s)}return s};function VDe(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;n_(y),t());return r=zDe(p),n=r.cache.get,i=r.cache.set,o=s,s(f)}function s(f){const p=n(f);if(p)return p;const y=UDe(f,r);return i(f,y),y}return function(){return o(VDe.apply(null,arguments))}}const ka=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},Kfe=/^\[(?:([a-z-]+):)?(.+)\]$/i,GDe=/^\d+\/\d+$/,HDe=new Set(["px","full","screen"]),WDe=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KDe=/\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$/,YDe=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ZDe=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,XDe=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ip=t=>Kw(t)||HDe.has(t)||GDe.test(t),Ug=t=>RS(t,"length",sMe),Kw=t=>!!t&&!Number.isNaN(Number(t)),VB=t=>RS(t,"number",Kw),L2=t=>!!t&&Number.isInteger(Number(t)),QDe=t=>t.endsWith("%")&&Kw(t.slice(0,-1)),Di=t=>Kfe.test(t),Vg=t=>WDe.test(t),JDe=new Set(["length","size","percentage"]),eMe=t=>RS(t,JDe,Yfe),tMe=t=>RS(t,"position",Yfe),rMe=new Set(["image","url"]),nMe=t=>RS(t,rMe,oMe),iMe=t=>RS(t,"",aMe),D2=()=>!0,RS=(t,e,r)=>{const n=Kfe.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},sMe=t=>KDe.test(t)&&!YDe.test(t),Yfe=()=>!1,aMe=t=>ZDe.test(t),oMe=t=>XDe.test(t),lMe=()=>{const t=ka("colors"),e=ka("spacing"),r=ka("blur"),n=ka("brightness"),i=ka("borderColor"),o=ka("borderRadius"),c=ka("borderSpacing"),s=ka("borderWidth"),f=ka("contrast"),p=ka("grayscale"),y=ka("hueRotate"),_=ka("invert"),T=ka("gap"),E=ka("gradientColorStops"),k=ka("gradientColorStopPositions"),P=ka("inset"),R=ka("margin"),D=ka("opacity"),M=ka("padding"),B=ka("saturate"),V=ka("scale"),G=ka("sepia"),W=ka("skew"),Z=ka("space"),Q=ka("translate"),re=()=>["auto","contain","none"],se=()=>["auto","hidden","clip","visible","scroll"],ue=()=>["auto",Di,e],_e=()=>[Di,e],we=()=>["",ip,Ug],Ce=()=>["auto",Kw,Di],Me=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Ae=()=>["solid","dashed","dotted","double","none"],be=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],me=()=>["start","end","center","between","around","evenly","stretch"],Pe=()=>["","0",Di],Ie=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Se=()=>[Kw,Di];return{cacheSize:500,separator:":",theme:{colors:[D2],spacing:[ip,Ug],blur:["none","",Vg,Di],brightness:Se(),borderColor:[t],borderRadius:["none","","full",Vg,Di],borderSpacing:_e(),borderWidth:we(),contrast:Se(),grayscale:Pe(),hueRotate:Se(),invert:Pe(),gap:_e(),gradientColorStops:[t],gradientColorStopPositions:[QDe,Ug],inset:ue(),margin:ue(),opacity:Se(),padding:_e(),saturate:Se(),scale:Se(),sepia:Pe(),skew:Se(),space:_e(),translate:_e()},classGroups:{aspect:[{aspect:["auto","square","video",Di]}],container:["container"],columns:[{columns:[Vg]}],"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:[...Me(),Di]}],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:[P]}],"inset-x":[{"inset-x":[P]}],"inset-y":[{"inset-y":[P]}],start:[{start:[P]}],end:[{end:[P]}],top:[{top:[P]}],right:[{right:[P]}],bottom:[{bottom:[P]}],left:[{left:[P]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",L2,Di]}],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",Di]}],grow:[{grow:Pe()}],shrink:[{shrink:Pe()}],order:[{order:["first","last","none",L2,Di]}],"grid-cols":[{"grid-cols":[D2]}],"col-start-end":[{col:["auto",{span:["full",L2,Di]},Di]}],"col-start":[{"col-start":Ce()}],"col-end":[{"col-end":Ce()}],"grid-rows":[{"grid-rows":[D2]}],"row-start-end":[{row:["auto",{span:[L2,Di]},Di]}],"row-start":[{"row-start":Ce()}],"row-end":[{"row-end":Ce()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Di]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Di]}],gap:[{gap:[T]}],"gap-x":[{"gap-x":[T]}],"gap-y":[{"gap-y":[T]}],"justify-content":[{justify:["normal",...me()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...me(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...me(),"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":[Z]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[Z]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Di,e]}],"min-w":[{"min-w":[Di,e,"min","max","fit"]}],"max-w":[{"max-w":[Di,e,"none","full","min","max","fit","prose",{screen:[Vg]},Vg]}],h:[{h:[Di,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Di,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Di,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Di,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Vg,Ug]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",VB]}],"font-family":[{font:[D2]}],"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",Di]}],"line-clamp":[{"line-clamp":["none",Kw,VB]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ip,Di]}],"list-image":[{"list-image":["none",Di]}],"list-style-type":[{list:["none","disc","decimal",Di]}],"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",ip,Ug]}],"underline-offset":[{"underline-offset":["auto",ip,Di]}],"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",Di]}],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",Di]}],"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:[...Me(),tMe]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eMe]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},nMe]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[k]}],"gradient-via-pos":[{via:[k]}],"gradient-to-pos":[{to:[k]}],"gradient-from":[{from:[E]}],"gradient-via":[{via:[E]}],"gradient-to":[{to:[E]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"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":[ip,Di]}],"outline-w":[{outline:[ip,Ug]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:we()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[D]}],"ring-offset-w":[{"ring-offset":[ip,Ug]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Vg,iMe]}],"shadow-color":[{shadow:[D2]}],opacity:[{opacity:[D]}],"mix-blend":[{"mix-blend":[...be(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":be()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[f]}],"drop-shadow":[{"drop-shadow":["","none",Vg,Di]}],grayscale:[{grayscale:[p]}],"hue-rotate":[{"hue-rotate":[y]}],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":[p]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[y]}],"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",Di]}],duration:[{duration:Se()}],ease:[{ease:["linear","in","out","in-out",Di]}],delay:[{delay:Se()}],animate:[{animate:["none","spin","ping","pulse","bounce",Di]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[V]}],"scale-x":[{"scale-x":[V]}],"scale-y":[{"scale-y":[V]}],rotate:[{rotate:[L2,Di]}],"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",Di]}],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",Di]}],"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",Di]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[ip,Ug,VB]}],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"]}}},cMe=qDe(lMe);function sr(...t){return cMe(Oi(t))}function Ba(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 See(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}function pVt(t){return t?t.replace(/<[^>]*>/g,""):""}const uMe=FLe,Zfe=I.forwardRef(({className:t,...e},r)=>a.jsx(vfe,{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}));Zfe.displayName=vfe.displayName;const dMe=kS("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"}}),Xfe=I.forwardRef(({className:t,variant:e,...r},n)=>a.jsx(bfe,{ref:n,className:sr(dMe({variant:e}),t),...r}));Xfe.displayName=bfe.displayName;const hMe=I.forwardRef(({className:t,...e},r)=>a.jsx(Tfe,{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}));hMe.displayName=Tfe.displayName;const Qfe=I.forwardRef(({className:t,...e},r)=>a.jsx(Efe,{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:a.jsx(Ds,{className:"h-4 w-4"})}));Qfe.displayName=Efe.displayName;const Jfe=I.forwardRef(({className:t,...e},r)=>a.jsx(wfe,{ref:r,className:sr("text-sm font-semibold",t),...e}));Jfe.displayName=wfe.displayName;const eme=I.forwardRef(({className:t,...e},r)=>a.jsx(Sfe,{ref:r,className:sr("text-sm opacity-90",t),...e}));eme.displayName=Sfe.displayName;function fMe(){const{toasts:t}=Jhe();return a.jsxs(uMe,{children:[t.map(function({id:e,title:r,description:n,action:i,...o}){return a.jsxs(Xfe,{...o,children:[a.jsxs("div",{className:"grid gap-1",children:[r&&a.jsx(Jfe,{children:r}),n&&a.jsx(eme,{children:n})]}),i,a.jsx(Qfe,{})]},e)}),a.jsx(Zfe,{})]})}var Tee=["light","dark"],mMe="(prefers-color-scheme: dark)",pMe=I.createContext(void 0),gMe={setTheme:t=>{},themes:[]},yMe=()=>{var t;return(t=I.useContext(pMe))!=null?t:gMe};I.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:c,attrs:s,nonce:f})=>{let p=o==="system",y=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${s.map(k=>`'${k}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,_=i?Tee.includes(o)&&o?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${o}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",T=(k,P=!1,R=!0)=>{let D=c?c[k]:k,M=P?k+"|| ''":`'${D}'`,B="";return i&&R&&!P&&Tee.includes(k)&&(B+=`d.style.colorScheme = '${k}';`),r==="class"?P||D?B+=`c.add(${M})`:B+="null":D&&(B+=`d[s](n,${M})`),B},E=t?`!function(){${y}${T(t)}}()`:n?`!function(){try{${y}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${p})){var t='${mMe}',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)}}${p?"":"else{"+T(o,!1,!1)+"}"}${_}}catch(e){}}()`:`!function(){try{${y}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${T(c?"x[e]":"e",!0)}}else{${T(o,!1,!1)};}${_}}catch(t){}}();`;return I.createElement("script",{nonce:f,dangerouslySetInnerHTML:{__html:E}})});var xMe=t=>{switch(t){case"success":return bMe;case"info":return SMe;case"warning":return wMe;case"error":return TMe;default:return null}},_Me=Array(12).fill(0),vMe=({visible:t,className:e})=>Xe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Xe.createElement("div",{className:"sonner-spinner"},_Me.map((r,n)=>Xe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),bMe=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"})),wMe=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"})),SMe=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"})),TMe=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"})),EMe=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"})),AMe=()=>{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},vU=1,jMe=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:vU++,o=this.toasts.find(s=>s.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),o?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,o,c=n.then(async f=>{if(o=["resolve",f],Xe.isValidElement(f))i=!1,this.create({id:r,type:"default",message:f});else if(CMe(f)&&!f.ok){i=!1;let p=typeof e.error=="function"?await e.error(`HTTP error! status: ${f.status}`):e.error,y=typeof e.description=="function"?await e.description(`HTTP error! status: ${f.status}`):e.description;this.create({id:r,type:"error",message:p,description:y})}else if(e.success!==void 0){i=!1;let p=typeof e.success=="function"?await e.success(f):e.success,y=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"success",message:p,description:y})}}).catch(async f=>{if(o=["reject",f],e.error!==void 0){i=!1;let p=typeof e.error=="function"?await e.error(f):e.error,y=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"error",message:p,description:y})}}).finally(()=>{var f;i&&(this.dismiss(r),r=void 0),(f=e.finally)==null||f.call(e)}),s=()=>new Promise((f,p)=>c.then(()=>o[0]==="reject"?p(o[1]):f(o[1])).catch(p));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)||vU++;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}},wu=new jMe,kMe=(t,e)=>{let r=(e==null?void 0:e.id)||vU++;return wu.addToast({title:t,...e,id:r}),r},CMe=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",IMe=kMe,NMe=()=>wu.toasts,PMe=()=>wu.getActiveToasts(),Gt=Object.assign(IMe,{success:wu.success,info:wu.info,warning:wu.warning,error:wu.error,custom:wu.custom,message:wu.message,promise:wu.promise,dismiss:wu.dismiss,loading:wu.loading},{getHistory:NMe,getToasts:PMe});function RMe(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))}RMe(`: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 CP(t){return t.label!==void 0}var LMe=3,DMe="32px",MMe="16px",Eee=4e3,OMe=356,FMe=14,BMe=20,zMe=200;function Nh(...t){return t.filter(Boolean).join(" ")}function $Me(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var UMe=t=>{var e,r,n,i,o,c,s,f,p,y,_;let{invert:T,toast:E,unstyled:k,interacting:P,setHeights:R,visibleToasts:D,heights:M,index:B,toasts:V,expanded:G,removeToast:W,defaultRichColors:Z,closeButton:Q,style:re,cancelButtonStyle:se,actionButtonStyle:ue,className:_e="",descriptionClassName:we="",duration:Ce,position:Me,gap:Ae,loadingIcon:be,expandByDefault:me,classNames:Pe,icons:Ie,closeButtonAriaLabel:Se="Close toast",pauseWhenPageIsHidden:ve}=t,[We,rt]=Xe.useState(null),[at,Et]=Xe.useState(null),[_t,Vt]=Xe.useState(!1),[pt,Nt]=Xe.useState(!1),[er,vt]=Xe.useState(!1),[or,Sr]=Xe.useState(!1),[nn,cr]=Xe.useState(!1),[xr,tr]=Xe.useState(0),[_n,lt]=Xe.useState(0),At=Xe.useRef(E.duration||Ce||Eee),Mt=Xe.useRef(null),dr=Xe.useRef(null),ur=B===0,hr=B+1<=D,Xt=E.type,Pr=E.dismissible!==!1,Rn=E.className||"",ci=E.descriptionClassName||"",ti=Xe.useMemo(()=>M.findIndex(Jr=>Jr.toastId===E.id)||0,[M,E.id]),zi=Xe.useMemo(()=>{var Jr;return(Jr=E.closeButton)!=null?Jr:Q},[E.closeButton,Q]),wa=Xe.useMemo(()=>E.duration||Ce||Eee,[E.duration,Ce]),xi=Xe.useRef(0),la=Xe.useRef(0),Cr=Xe.useRef(0),Fn=Xe.useRef(null),[As,Sa]=Me.split("-"),_o=Xe.useMemo(()=>M.reduce((Jr,Bn,ts)=>ts>=ti?Jr:Jr+Bn.height,0),[M,ti]),Yr=AMe(),hn=E.invert||T,xn=Xt==="loading";la.current=Xe.useMemo(()=>ti*Ae+_o,[ti,_o]),Xe.useEffect(()=>{At.current=wa},[wa]),Xe.useEffect(()=>{Vt(!0)},[]),Xe.useEffect(()=>{let Jr=dr.current;if(Jr){let Bn=Jr.getBoundingClientRect().height;return lt(Bn),R(ts=>[{toastId:E.id,height:Bn,position:E.position},...ts]),()=>R(ts=>ts.filter(yl=>yl.toastId!==E.id))}},[R,E.id]),Xe.useLayoutEffect(()=>{if(!_t)return;let Jr=dr.current,Bn=Jr.style.height;Jr.style.height="auto";let ts=Jr.getBoundingClientRect().height;Jr.style.height=Bn,lt(ts),R(yl=>yl.find(Zo=>Zo.toastId===E.id)?yl.map(Zo=>Zo.toastId===E.id?{...Zo,height:ts}:Zo):[{toastId:E.id,height:ts,position:E.position},...yl])},[_t,E.title,E.description,R,E.id]);let Zr=Xe.useCallback(()=>{Nt(!0),tr(la.current),R(Jr=>Jr.filter(Bn=>Bn.toastId!==E.id)),setTimeout(()=>{W(E)},zMe)},[E,W,R,la]);Xe.useEffect(()=>{if(E.promise&&Xt==="loading"||E.duration===1/0||E.type==="loading")return;let Jr;return G||P||ve&&Yr?(()=>{if(Cr.current{var Bn;(Bn=E.onAutoClose)==null||Bn.call(E,E),Zr()},At.current)),()=>clearTimeout(Jr)},[G,P,E,Xt,ve,Yr,Zr]),Xe.useEffect(()=>{E.delete&&Zr()},[Zr,E.delete]);function ui(){var Jr,Bn,ts;return Ie!=null&&Ie.loading?Xe.createElement("div",{className:Nh(Pe==null?void 0:Pe.loader,(Jr=E==null?void 0:E.classNames)==null?void 0:Jr.loader,"sonner-loader"),"data-visible":Xt==="loading"},Ie.loading):be?Xe.createElement("div",{className:Nh(Pe==null?void 0:Pe.loader,(Bn=E==null?void 0:E.classNames)==null?void 0:Bn.loader,"sonner-loader"),"data-visible":Xt==="loading"},be):Xe.createElement(vMe,{className:Nh(Pe==null?void 0:Pe.loader,(ts=E==null?void 0:E.classNames)==null?void 0:ts.loader),visible:Xt==="loading"})}return Xe.createElement("li",{tabIndex:0,ref:dr,className:Nh(_e,Rn,Pe==null?void 0:Pe.toast,(e=E==null?void 0:E.classNames)==null?void 0:e.toast,Pe==null?void 0:Pe.default,Pe==null?void 0:Pe[Xt],(r=E==null?void 0:E.classNames)==null?void 0:r[Xt]),"data-sonner-toast":"","data-rich-colors":(n=E.richColors)!=null?n:Z,"data-styled":!(E.jsx||E.unstyled||k),"data-mounted":_t,"data-promise":!!E.promise,"data-swiped":nn,"data-removed":pt,"data-visible":hr,"data-y-position":As,"data-x-position":Sa,"data-index":B,"data-front":ur,"data-swiping":er,"data-dismissible":Pr,"data-type":Xt,"data-invert":hn,"data-swipe-out":or,"data-swipe-direction":at,"data-expanded":!!(G||me&&_t),style:{"--index":B,"--toasts-before":B,"--z-index":V.length-B,"--offset":`${pt?xr:la.current}px`,"--initial-height":me?"auto":`${_n}px`,...re,...E.style},onDragEnd:()=>{vt(!1),rt(null),Fn.current=null},onPointerDown:Jr=>{xn||!Pr||(Mt.current=new Date,tr(la.current),Jr.target.setPointerCapture(Jr.pointerId),Jr.target.tagName!=="BUTTON"&&(vt(!0),Fn.current={x:Jr.clientX,y:Jr.clientY}))},onPointerUp:()=>{var Jr,Bn,ts,yl;if(or||!Pr)return;Fn.current=null;let Zo=Number(((Jr=dr.current)==null?void 0:Jr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ot=Number(((Bn=dr.current)==null?void 0:Bn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ro=new Date().getTime()-((ts=Mt.current)==null?void 0:ts.getTime()),Ei=We==="x"?Zo:Ot,js=Math.abs(Ei)/Ro;if(Math.abs(Ei)>=BMe||js>.11){tr(la.current),(yl=E.onDismiss)==null||yl.call(E,E),Et(We==="x"?Zo>0?"right":"left":Ot>0?"down":"up"),Zr(),Sr(!0),cr(!1);return}vt(!1),rt(null)},onPointerMove:Jr=>{var Bn,ts,yl,Zo;if(!Fn.current||!Pr||((Bn=window.getSelection())==null?void 0:Bn.toString().length)>0)return;let Ot=Jr.clientY-Fn.current.y,Ro=Jr.clientX-Fn.current.x,Ei=(ts=t.swipeDirections)!=null?ts:$Me(Me);!We&&(Math.abs(Ro)>1||Math.abs(Ot)>1)&&rt(Math.abs(Ro)>Math.abs(Ot)?"x":"y");let js={x:0,y:0};We==="y"?(Ei.includes("top")||Ei.includes("bottom"))&&(Ei.includes("top")&&Ot<0||Ei.includes("bottom")&&Ot>0)&&(js.y=Ot):We==="x"&&(Ei.includes("left")||Ei.includes("right"))&&(Ei.includes("left")&&Ro<0||Ei.includes("right")&&Ro>0)&&(js.x=Ro),(Math.abs(js.x)>0||Math.abs(js.y)>0)&&cr(!0),(yl=dr.current)==null||yl.style.setProperty("--swipe-amount-x",`${js.x}px`),(Zo=dr.current)==null||Zo.style.setProperty("--swipe-amount-y",`${js.y}px`)}},zi&&!E.jsx?Xe.createElement("button",{"aria-label":Se,"data-disabled":xn,"data-close-button":!0,onClick:xn||!Pr?()=>{}:()=>{var Jr;Zr(),(Jr=E.onDismiss)==null||Jr.call(E,E)},className:Nh(Pe==null?void 0:Pe.closeButton,(i=E==null?void 0:E.classNames)==null?void 0:i.closeButton)},(o=Ie==null?void 0:Ie.close)!=null?o:EMe):null,E.jsx||I.isValidElement(E.title)?E.jsx?E.jsx:typeof E.title=="function"?E.title():E.title:Xe.createElement(Xe.Fragment,null,Xt||E.icon||E.promise?Xe.createElement("div",{"data-icon":"",className:Nh(Pe==null?void 0:Pe.icon,(c=E==null?void 0:E.classNames)==null?void 0:c.icon)},E.promise||E.type==="loading"&&!E.icon?E.icon||ui():null,E.type!=="loading"?E.icon||(Ie==null?void 0:Ie[Xt])||xMe(Xt):null):null,Xe.createElement("div",{"data-content":"",className:Nh(Pe==null?void 0:Pe.content,(s=E==null?void 0:E.classNames)==null?void 0:s.content)},Xe.createElement("div",{"data-title":"",className:Nh(Pe==null?void 0:Pe.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:Nh(we,ci,Pe==null?void 0:Pe.description,(p=E==null?void 0:E.classNames)==null?void 0:p.description)},typeof E.description=="function"?E.description():E.description):null),I.isValidElement(E.cancel)?E.cancel:E.cancel&&CP(E.cancel)?Xe.createElement("button",{"data-button":!0,"data-cancel":!0,style:E.cancelButtonStyle||se,onClick:Jr=>{var Bn,ts;CP(E.cancel)&&Pr&&((ts=(Bn=E.cancel).onClick)==null||ts.call(Bn,Jr),Zr())},className:Nh(Pe==null?void 0:Pe.cancelButton,(y=E==null?void 0:E.classNames)==null?void 0:y.cancelButton)},E.cancel.label):null,I.isValidElement(E.action)?E.action:E.action&&CP(E.action)?Xe.createElement("button",{"data-button":!0,"data-action":!0,style:E.actionButtonStyle||ue,onClick:Jr=>{var Bn,ts;CP(E.action)&&((ts=(Bn=E.action).onClick)==null||ts.call(Bn,Jr),!Jr.defaultPrevented&&Zr())},className:Nh(Pe==null?void 0:Pe.actionButton,(_=E==null?void 0:E.classNames)==null?void 0:_.actionButton)},E.action.label):null))};function Aee(){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 VMe(t,e){let r={};return[t,e].forEach((n,i)=>{let o=i===1,c=o?"--mobile-offset":"--offset",s=o?MMe:DMe;function f(p){["top","right","bottom","left"].forEach(y=>{r[`${c}-${y}`]=typeof p=="number"?`${p}px`:p})}typeof n=="number"||typeof n=="string"?f(n):typeof n=="object"?["top","right","bottom","left"].forEach(p=>{n[p]===void 0?r[`${c}-${p}`]=s:r[`${c}-${p}`]=typeof n[p]=="number"?`${n[p]}px`:n[p]}):f(s)}),r}var qMe=I.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:o,closeButton:c,className:s,offset:f,mobileOffset:p,theme:y="light",richColors:_,duration:T,style:E,visibleToasts:k=LMe,toastOptions:P,dir:R=Aee(),gap:D=FMe,loadingIcon:M,icons:B,containerAriaLabel:V="Notifications",pauseWhenPageIsHidden:G}=t,[W,Z]=Xe.useState([]),Q=Xe.useMemo(()=>Array.from(new Set([n].concat(W.filter(ve=>ve.position).map(ve=>ve.position)))),[W,n]),[re,se]=Xe.useState([]),[ue,_e]=Xe.useState(!1),[we,Ce]=Xe.useState(!1),[Me,Ae]=Xe.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),be=Xe.useRef(null),me=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Pe=Xe.useRef(null),Ie=Xe.useRef(!1),Se=Xe.useCallback(ve=>{Z(We=>{var rt;return(rt=We.find(at=>at.id===ve.id))!=null&&rt.delete||wu.dismiss(ve.id),We.filter(({id:at})=>at!==ve.id)})},[]);return Xe.useEffect(()=>wu.subscribe(ve=>{if(ve.dismiss){Z(We=>We.map(rt=>rt.id===ve.id?{...rt,delete:!0}:rt));return}setTimeout(()=>{Yhe.flushSync(()=>{Z(We=>{let rt=We.findIndex(at=>at.id===ve.id);return rt!==-1?[...We.slice(0,rt),{...We[rt],...ve},...We.slice(rt+1)]:[ve,...We]})})})}),[]),Xe.useEffect(()=>{if(y!=="system"){Ae(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Ae("dark"):Ae("light")),typeof window>"u")return;let ve=window.matchMedia("(prefers-color-scheme: dark)");try{ve.addEventListener("change",({matches:We})=>{Ae(We?"dark":"light")})}catch{ve.addListener(({matches:rt})=>{try{Ae(rt?"dark":"light")}catch(at){console.error(at)}})}},[y]),Xe.useEffect(()=>{W.length<=1&&_e(!1)},[W]),Xe.useEffect(()=>{let ve=We=>{var rt,at;i.every(Et=>We[Et]||We.code===Et)&&(_e(!0),(rt=be.current)==null||rt.focus()),We.code==="Escape"&&(document.activeElement===be.current||(at=be.current)!=null&&at.contains(document.activeElement))&&_e(!1)};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[i]),Xe.useEffect(()=>{if(be.current)return()=>{Pe.current&&(Pe.current.focus({preventScroll:!0}),Pe.current=null,Ie.current=!1)}},[be.current]),Xe.createElement("section",{ref:e,"aria-label":`${V} ${me}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},Q.map((ve,We)=>{var rt;let[at,Et]=ve.split("-");return W.length?Xe.createElement("ol",{key:ve,dir:R==="auto"?Aee():R,tabIndex:-1,ref:be,className:s,"data-sonner-toaster":!0,"data-theme":Me,"data-y-position":at,"data-lifted":ue&&W.length>1&&!o,"data-x-position":Et,style:{"--front-toast-height":`${((rt=re[0])==null?void 0:rt.height)||0}px`,"--width":`${OMe}px`,"--gap":`${D}px`,...E,...VMe(f,p)},onBlur:_t=>{Ie.current&&!_t.currentTarget.contains(_t.relatedTarget)&&(Ie.current=!1,Pe.current&&(Pe.current.focus({preventScroll:!0}),Pe.current=null))},onFocus:_t=>{_t.target instanceof HTMLElement&&_t.target.dataset.dismissible==="false"||Ie.current||(Ie.current=!0,Pe.current=_t.relatedTarget)},onMouseEnter:()=>_e(!0),onMouseMove:()=>_e(!0),onMouseLeave:()=>{we||_e(!1)},onDragEnd:()=>_e(!1),onPointerDown:_t=>{_t.target instanceof HTMLElement&&_t.target.dataset.dismissible==="false"||Ce(!0)},onPointerUp:()=>Ce(!1)},W.filter(_t=>!_t.position&&We===0||_t.position===ve).map((_t,Vt)=>{var pt,Nt;return Xe.createElement(UMe,{key:_t.id,icons:B,index:Vt,toast:_t,defaultRichColors:_,duration:(pt=P==null?void 0:P.duration)!=null?pt:T,className:P==null?void 0:P.className,descriptionClassName:P==null?void 0:P.descriptionClassName,invert:r,visibleToasts:k,closeButton:(Nt=P==null?void 0:P.closeButton)!=null?Nt:c,interacting:we,position:ve,style:P==null?void 0:P.style,unstyled:P==null?void 0:P.unstyled,classNames:P==null?void 0:P.classNames,cancelButtonStyle:P==null?void 0:P.cancelButtonStyle,actionButtonStyle:P==null?void 0:P.actionButtonStyle,removeToast:Se,toasts:W.filter(er=>er.position==_t.position),heights:re.filter(er=>er.position==_t.position),setHeights:se,expandByDefault:o,gap:D,loadingIcon:M,expanded:ue,pauseWhenPageIsHidden:G,swipeDirections:t.swipeDirections})})):null}))});const GMe=({...t})=>{const{theme:e="system"}=yMe();return a.jsx(qMe,{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 HMe=aG[" useId ".trim().toString()]||(()=>{}),WMe=0;function Dl(t){const[e,r]=I.useState(HMe());return Po(()=>{r(n=>n??String(WMe++))},[t]),e?`radix-${e}`:""}var qB="focusScope.autoFocusOnMount",GB="focusScope.autoFocusOnUnmount",jee={bubbles:!1,cancelable:!0},KMe="FocusScope",tC=I.forwardRef((t,e)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...c}=t,[s,f]=I.useState(null),p=po(i),y=po(o),_=I.useRef(null),T=Kn(e,P=>f(P)),E=I.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;I.useEffect(()=>{if(n){let P=function(B){if(E.paused||!s)return;const V=B.target;s.contains(V)?_.current=V:Qg(_.current,{select:!0})},R=function(B){if(E.paused||!s)return;const V=B.relatedTarget;V!==null&&(s.contains(V)||Qg(_.current,{select:!0}))},D=function(B){if(document.activeElement===document.body)for(const G of B)G.removedNodes.length>0&&Qg(s)};document.addEventListener("focusin",P),document.addEventListener("focusout",R);const M=new MutationObserver(D);return s&&M.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",P),document.removeEventListener("focusout",R),M.disconnect()}}},[n,s,E.paused]),I.useEffect(()=>{if(s){Cee.add(E);const P=document.activeElement;if(!s.contains(P)){const D=new CustomEvent(qB,jee);s.addEventListener(qB,p),s.dispatchEvent(D),D.defaultPrevented||(YMe(eOe(tme(s)),{select:!0}),document.activeElement===P&&Qg(s))}return()=>{s.removeEventListener(qB,p),setTimeout(()=>{const D=new CustomEvent(GB,jee);s.addEventListener(GB,y),s.dispatchEvent(D),D.defaultPrevented||Qg(P??document.body,{select:!0}),s.removeEventListener(GB,y),Cee.remove(E)},0)}}},[s,p,y,E]);const k=I.useCallback(P=>{if(!r&&!n||E.paused)return;const R=P.key==="Tab"&&!P.altKey&&!P.ctrlKey&&!P.metaKey,D=document.activeElement;if(R&&D){const M=P.currentTarget,[B,V]=ZMe(M);B&&V?!P.shiftKey&&D===V?(P.preventDefault(),r&&Qg(B,{select:!0})):P.shiftKey&&D===B&&(P.preventDefault(),r&&Qg(V,{select:!0})):D===M&&P.preventDefault()}},[r,n,E.paused]);return a.jsx(rn.div,{tabIndex:-1,...c,ref:T,onKeyDown:k})});tC.displayName=KMe;function YMe(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(Qg(n,{select:e}),document.activeElement!==r)return}function ZMe(t){const e=tme(t),r=kee(e,t),n=kee(e.reverse(),t);return[r,n]}function tme(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 kee(t,e){for(const r of t)if(!XMe(r,{upTo:e}))return r}function XMe(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 QMe(t){return t instanceof HTMLInputElement&&"select"in t}function Qg(t,{select:e=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&QMe(t)&&e&&t.select()}}var Cee=JMe();function JMe(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=Iee(t,e),t.unshift(e)},remove(e){var r;t=Iee(t,e),(r=t[0])==null||r.resume()}}}function Iee(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}function eOe(t){return t.filter(e=>e.tagName!=="A")}var HB=0;function DO(){I.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??Nee()),document.body.insertAdjacentElement("beforeend",t[1]??Nee()),HB++,()=>{HB===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),HB--}},[])}function Nee(){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 Kf=function(){return Kf=Object.assign||function(e){for(var r,n=1,i=arguments.length;n"u")return yOe;var e=xOe(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])}},vOe=sme(),Yw="data-scroll-locked",bOe=function(t,e,r,n){var i=t.left,o=t.top,c=t.right,s=t.gap;return r===void 0&&(r="margin"),` .`.concat(rOe,` { overflow: hidden `).concat(n,`; padding-right: `).concat(s,"px ").concat(n,`; } body[`).concat(Yw,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&` padding-left: `.concat(i,`px; padding-top: `).concat(o,`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(rL,` { right: `).concat(s,"px ").concat(n,`; } .`).concat(nL,` { margin-right: `).concat(s,"px ").concat(n,`; } .`).concat(rL," .").concat(rL,` { right: 0 `).concat(n,`; } .`).concat(nL," .").concat(nL,` { margin-right: 0 `).concat(n,`; } body[`).concat(Yw,`] { `).concat(nOe,": ").concat(s,`px; } `)},Ree=function(){var t=parseInt(document.body.getAttribute(Yw)||"0",10);return isFinite(t)?t:0},wOe=function(){I.useEffect(function(){return document.body.setAttribute(Yw,(Ree()+1).toString()),function(){var t=Ree()-1;t<=0?document.body.removeAttribute(Yw):document.body.setAttribute(Yw,t.toString())}},[])},SOe=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;wOe();var o=I.useMemo(function(){return _Oe(i)},[i]);return I.createElement(vOe,{styles:bOe(o,!e,i,r?"":"!important")})},bU=!1;if(typeof window<"u")try{var IP=Object.defineProperty({},"passive",{get:function(){return bU=!0,!0}});window.addEventListener("test",IP,IP),window.removeEventListener("test",IP,IP)}catch{bU=!1}var Gb=bU?{passive:!1}:!1,TOe=function(t){return t.tagName==="TEXTAREA"},ame=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!TOe(t)&&r[e]==="visible")},EOe=function(t){return ame(t,"overflowY")},AOe=function(t){return ame(t,"overflowX")},Lee=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=ome(t,n);if(i){var o=lme(t,n),c=o[1],s=o[2];if(c>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},jOe=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},kOe=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},ome=function(t,e){return t==="v"?EOe(e):AOe(e)},lme=function(t,e){return t==="v"?jOe(e):kOe(e)},COe=function(t,e){return t==="h"&&e==="rtl"?-1:1},IOe=function(t,e,r,n,i){var o=COe(t,window.getComputedStyle(e).direction),c=o*n,s=r.target,f=e.contains(s),p=!1,y=c>0,_=0,T=0;do{if(!s)break;var E=lme(t,s),k=E[0],P=E[1],R=E[2],D=P-R-o*k;(k||D)&&ome(t,s)&&(_+=D,T+=k);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(y&&(Math.abs(_)<1||!i)||!y&&(Math.abs(T)<1||!i))&&(p=!0),p},NP=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Dee=function(t){return[t.deltaX,t.deltaY]},Mee=function(t){return t&&"current"in t?t.current:t},NOe=function(t,e){return t[0]===e[0]&&t[1]===e[1]},POe=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},ROe=0,Hb=[];function LOe(t){var e=I.useRef([]),r=I.useRef([0,0]),n=I.useRef(),i=I.useState(ROe++)[0],o=I.useState(sme)[0],c=I.useRef(t);I.useEffect(function(){c.current=t},[t]),I.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var P=tOe([t.lockRef.current],(t.shards||[]).map(Mee),!0).filter(Boolean);return P.forEach(function(R){return R.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),P.forEach(function(R){return R.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var s=I.useCallback(function(P,R){if("touches"in P&&P.touches.length===2||P.type==="wheel"&&P.ctrlKey)return!c.current.allowPinchZoom;var D=NP(P),M=r.current,B="deltaX"in P?P.deltaX:M[0]-D[0],V="deltaY"in P?P.deltaY:M[1]-D[1],G,W=P.target,Z=Math.abs(B)>Math.abs(V)?"h":"v";if("touches"in P&&Z==="h"&&W.type==="range")return!1;var Q=Lee(Z,W);if(!Q)return!0;if(Q?G=Z:(G=Z==="v"?"h":"v",Q=Lee(Z,W)),!Q)return!1;if(!n.current&&"changedTouches"in P&&(B||V)&&(n.current=G),!G)return!0;var re=n.current||G;return IOe(re,R,P,re==="h"?B:V,!0)},[]),f=I.useCallback(function(P){var R=P;if(!(!Hb.length||Hb[Hb.length-1]!==o)){var D="deltaY"in R?Dee(R):NP(R),M=e.current.filter(function(G){return G.name===R.type&&(G.target===R.target||R.target===G.shadowParent)&&NOe(G.delta,D)})[0];if(M&&M.should){R.cancelable&&R.preventDefault();return}if(!M){var B=(c.current.shards||[]).map(Mee).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()}}},[]),p=I.useCallback(function(P,R,D,M){var B={name:P,delta:R,target:D,should:M,shadowParent:DOe(D)};e.current.push(B),setTimeout(function(){e.current=e.current.filter(function(V){return V!==B})},1)},[]),y=I.useCallback(function(P){r.current=NP(P),n.current=void 0},[]),_=I.useCallback(function(P){p(P.type,Dee(P),P.target,s(P,t.lockRef.current))},[]),T=I.useCallback(function(P){p(P.type,NP(P),P.target,s(P,t.lockRef.current))},[]);I.useEffect(function(){return Hb.push(o),t.setCallbacks({onScrollCapture:_,onWheelCapture:_,onTouchMoveCapture:T}),document.addEventListener("wheel",f,Gb),document.addEventListener("touchmove",f,Gb),document.addEventListener("touchstart",y,Gb),function(){Hb=Hb.filter(function(P){return P!==o}),document.removeEventListener("wheel",f,Gb),document.removeEventListener("touchmove",f,Gb),document.removeEventListener("touchstart",y,Gb)}},[]);var E=t.removeScrollBar,k=t.inert;return I.createElement(I.Fragment,null,k?I.createElement(o,{styles:POe(i)}):null,E?I.createElement(SOe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function DOe(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const MOe=uOe(ime,LOe);var rC=I.forwardRef(function(t,e){return I.createElement(MO,Kf({},t,{ref:e,sideCar:MOe}))});rC.classNames=MO.classNames;var OOe=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},Wb=new WeakMap,PP=new WeakMap,RP={},ZB=0,cme=function(t){return t&&(t.host||cme(t.parentNode))},FOe=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=cme(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})},BOe=function(t,e,r,n){var i=FOe(e,Array.isArray(t)?t:[t]);RP[r]||(RP[r]=new WeakMap);var o=RP[r],c=[],s=new Set,f=new Set(i),p=function(_){!_||s.has(_)||(s.add(_),p(_.parentNode))};i.forEach(p);var y=function(_){!_||f.has(_)||Array.prototype.forEach.call(_.children,function(T){if(s.has(T))y(T);else try{var E=T.getAttribute(n),k=E!==null&&E!=="false",P=(Wb.get(T)||0)+1,R=(o.get(T)||0)+1;Wb.set(T,P),o.set(T,R),c.push(T),P===1&&k&&PP.set(T,!0),R===1&&T.setAttribute(r,"true"),k||T.setAttribute(n,"true")}catch(D){console.error("aria-hidden: cannot operate on ",T,D)}})};return y(e),s.clear(),ZB++,function(){c.forEach(function(_){var T=Wb.get(_)-1,E=o.get(_)-1;Wb.set(_,T),o.set(_,E),T||(PP.has(_)||_.removeAttribute(n),PP.delete(_)),E||_.removeAttribute(r)}),ZB--,ZB||(Wb=new WeakMap,Wb=new WeakMap,PP=new WeakMap,RP={})}},OO=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=OOe(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),BOe(n,i,r,"aria-hidden")):function(){return null}},FO="Dialog",[ume,dme]=Yo(FO),[zOe,df]=ume(FO),hme=t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!0}=t,s=I.useRef(null),f=I.useRef(null),[p,y]=dd({prop:n,defaultProp:i??!1,onChange:o,caller:FO});return a.jsx(zOe,{scope:e,triggerRef:s,contentRef:f,contentId:Dl(),titleId:Dl(),descriptionId:Dl(),open:p,onOpenChange:y,onOpenToggle:I.useCallback(()=>y(_=>!_),[y]),modal:c,children:r})};hme.displayName=FO;var fme="DialogTrigger",mme=I.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=df(fme,r),o=Kn(e,i.triggerRef);return a.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":m9(i.open),...n,ref:o,onClick:Or(t.onClick,i.onOpenToggle)})});mme.displayName=fme;var h9="DialogPortal",[$Oe,pme]=ume(h9,{forceMount:void 0}),gme=t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,o=df(h9,e);return a.jsx($Oe,{scope:e,forceMount:r,children:I.Children.map(n,c=>a.jsx(pl,{present:r||o.open,children:a.jsx(jS,{asChild:!0,container:i,children:c})}))})};gme.displayName=h9;var hD="DialogOverlay",yme=I.forwardRef((t,e)=>{const r=pme(hD,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=df(hD,t.__scopeDialog);return o.modal?a.jsx(pl,{present:n||o.open,children:a.jsx(VOe,{...i,ref:e})}):null});yme.displayName=hD;var UOe=Ky("DialogOverlay.RemoveScroll"),VOe=I.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=df(hD,r);return a.jsx(rC,{as:UOe,allowPinchZoom:!0,shards:[i.contentRef],children:a.jsx(rn.div,{"data-state":m9(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),B_="DialogContent",xme=I.forwardRef((t,e)=>{const r=pme(B_,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=df(B_,t.__scopeDialog);return a.jsx(pl,{present:n||o.open,children:o.modal?a.jsx(qOe,{...i,ref:e}):a.jsx(GOe,{...i,ref:e})})});xme.displayName=B_;var qOe=I.forwardRef((t,e)=>{const r=df(B_,t.__scopeDialog),n=I.useRef(null),i=Kn(e,r.contentRef,n);return I.useEffect(()=>{const o=n.current;if(o)return OO(o)},[]),a.jsx(_me,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Or(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,s=c.button===0&&c.ctrlKey===!0;(c.button===2||s)&&o.preventDefault()}),onFocusOutside:Or(t.onFocusOutside,o=>o.preventDefault())})}),GOe=I.forwardRef((t,e)=>{const r=df(B_,t.__scopeDialog),n=I.useRef(!1),i=I.useRef(!1);return a.jsx(_me,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var c,s;(c=t.onCloseAutoFocus)==null||c.call(t,o),o.defaultPrevented||(n.current||(s=r.triggerRef.current)==null||s.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var f,p;(f=t.onInteractOutside)==null||f.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((p=r.triggerRef.current)==null?void 0:p.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),_me=I.forwardRef((t,e)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...c}=t,s=df(B_,r),f=I.useRef(null),p=Kn(e,f);return DO(),a.jsxs(a.Fragment,{children:[a.jsx(tC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a.jsx(rv,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":m9(s.open),...c,ref:p,onDismiss:()=>s.onOpenChange(!1)})}),a.jsxs(a.Fragment,{children:[a.jsx(WOe,{titleId:s.titleId}),a.jsx(YOe,{contentRef:f,descriptionId:s.descriptionId})]})]})}),f9="DialogTitle",vme=I.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=df(f9,r);return a.jsx(rn.h2,{id:i.titleId,...n,ref:e})});vme.displayName=f9;var bme="DialogDescription",wme=I.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=df(bme,r);return a.jsx(rn.p,{id:i.descriptionId,...n,ref:e})});wme.displayName=bme;var Sme="DialogClose",Tme=I.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=df(Sme,r);return a.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});Tme.displayName=Sme;function m9(t){return t?"open":"closed"}var Eme="DialogTitleWarning",[HOe,Ame]=ZRe(Eme,{contentName:B_,titleName:f9,docsSlug:"dialog"}),WOe=({titleId:t})=>{const e=Ame(Eme),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 I.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},KOe="DialogDescriptionWarning",YOe=({contentRef:t,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Ame(KOe).contentName}}.`;return I.useEffect(()=>{var o;const i=(o=t.current)==null?void 0:o.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},BO=hme,p9=mme,zO=gme,LS=yme,DS=xme,nC=vme,iC=wme,sC=Tme,jme="AlertDialog",[ZOe,gVt]=Yo(jme,[dme]),Zp=dme(),kme=t=>{const{__scopeAlertDialog:e,...r}=t,n=Zp(e);return a.jsx(BO,{...n,...r,modal:!0})};kme.displayName=jme;var XOe="AlertDialogTrigger",Cme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Zp(r);return a.jsx(p9,{...i,...n,ref:e})});Cme.displayName=XOe;var QOe="AlertDialogPortal",Ime=t=>{const{__scopeAlertDialog:e,...r}=t,n=Zp(e);return a.jsx(zO,{...n,...r})};Ime.displayName=QOe;var JOe="AlertDialogOverlay",Nme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Zp(r);return a.jsx(LS,{...i,...n,ref:e})});Nme.displayName=JOe;var Zw="AlertDialogContent",[e3e,t3e]=ZOe(Zw),r3e=rfe("AlertDialogContent"),Pme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,children:n,...i}=t,o=Zp(r),c=I.useRef(null),s=Kn(e,c),f=I.useRef(null);return a.jsx(HOe,{contentName:Zw,titleName:Rme,docsSlug:"alert-dialog",children:a.jsx(e3e,{scope:r,cancelRef:f,children:a.jsxs(DS,{role:"alertdialog",...o,...i,ref:s,onOpenAutoFocus:Or(i.onOpenAutoFocus,p=>{var y;p.preventDefault(),(y=f.current)==null||y.focus({preventScroll:!0})}),onPointerDownOutside:p=>p.preventDefault(),onInteractOutside:p=>p.preventDefault(),children:[a.jsx(r3e,{children:n}),a.jsx(i3e,{contentRef:c})]})})})});Pme.displayName=Zw;var Rme="AlertDialogTitle",Lme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Zp(r);return a.jsx(nC,{...i,...n,ref:e})});Lme.displayName=Rme;var Dme="AlertDialogDescription",Mme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Zp(r);return a.jsx(iC,{...i,...n,ref:e})});Mme.displayName=Dme;var n3e="AlertDialogAction",Ome=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Zp(r);return a.jsx(sC,{...i,...n,ref:e})});Ome.displayName=n3e;var Fme="AlertDialogCancel",Bme=I.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,{cancelRef:i}=t3e(Fme,r),o=Zp(r),c=Kn(e,i);return a.jsx(sC,{...o,...n,ref:c})});Bme.displayName=Fme;var i3e=({contentRef:t})=>{const e=`\`${Zw}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${Zw}\` by passing a \`${Dme}\` 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 \`${Zw}\`. 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 I.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},s3e=kme,a3e=Cme,o3e=Ime,zme=Nme,$me=Pme,Ume=Ome,Vme=Bme,qme=Lme,Gme=Mme;const Ej=kS("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"}}),zt=I.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},o)=>{const c=n?efe:"button";return a.jsx(c,{className:sr(Ej({variant:e,size:r,className:t})),ref:o,...i})});zt.displayName="Button";const Hme=s3e,yVt=a3e,l3e=o3e,Wme=I.forwardRef(({className:t,...e},r)=>a.jsx(zme,{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}));Wme.displayName=zme.displayName;const g9=I.forwardRef(({className:t,...e},r)=>a.jsxs(l3e,{children:[a.jsx(Wme,{}),a.jsx($me,{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})]}));g9.displayName=$me.displayName;const y9=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col space-y-2 text-center sm:text-left",t),...e});y9.displayName="AlertDialogHeader";const x9=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});x9.displayName="AlertDialogFooter";const _9=I.forwardRef(({className:t,...e},r)=>a.jsx(qme,{ref:r,className:sr("text-lg font-semibold",t),...e}));_9.displayName=qme.displayName;const v9=I.forwardRef(({className:t,...e},r)=>a.jsx(Gme,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));v9.displayName=Gme.displayName;const b9=I.forwardRef(({className:t,...e},r)=>a.jsx(Ume,{ref:r,className:sr(Ej(),t),...e}));b9.displayName=Ume.displayName;const w9=I.forwardRef(({className:t,...e},r)=>a.jsx(Vme,{ref:r,className:sr(Ej({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));w9.displayName=Vme.displayName;let fD=null;const c3e=["delete","remove","revoke","cannot be undone","permanently"];function xVt(t,e={}){const r=typeof t=="string"?{description:t,...e}:t,n=`${r.title??""} ${r.description??""}`.toLowerCase(),i=r.destructive??c3e.some(o=>n.includes(o));return new Promise(o=>{if(!fD){o(window.confirm(r.description??r.title??"Are you sure?"));return}fD({...r,destructive:i,resolve:o})})}function u3e(){const[t,e]=I.useState(null);I.useEffect(()=>(fD=i=>e(i),()=>{fD=null}),[]);const r=i=>{t==null||t.resolve(i),e(null)},n=!!(t!=null&&t.destructive);return a.jsx(Hme,{open:!!t,onOpenChange:i=>!i&&r(!1),children:a.jsxs(g9,{className:"sm:max-w-md",children:[a.jsx(y9,{children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.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:a.jsx(PS,{className:"h-5 w-5"})}),a.jsxs("div",{className:"space-y-1.5 text-left",children:[a.jsx(_9,{children:(t==null?void 0:t.title)??(n?"Are you sure?":"Please confirm")}),(t==null?void 0:t.description)&&a.jsx(v9,{className:"leading-relaxed",children:t.description})]})]})}),a.jsxs(x9,{className:"gap-2 sm:gap-2",children:[a.jsx(w9,{onClick:()=>r(!1),children:(t==null?void 0:t.cancelText)??"Cancel"}),a.jsx(b9,{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 d3e=["top","right","bottom","left"],Xy=Math.min,ed=Math.max,mD=Math.round,LP=Math.floor,Qy=t=>({x:t,y:t}),h3e={left:"right",right:"left",bottom:"top",top:"bottom"},f3e={start:"end",end:"start"};function wU(t,e,r){return ed(t,Xy(e,r))}function Bp(t,e){return typeof t=="function"?t(e):t}function zp(t){return t.split("-")[0]}function MS(t){return t.split("-")[1]}function S9(t){return t==="x"?"y":"x"}function T9(t){return t==="y"?"height":"width"}function Jy(t){return["top","bottom"].includes(zp(t))?"y":"x"}function E9(t){return S9(Jy(t))}function m3e(t,e,r){r===void 0&&(r=!1);const n=MS(t),i=E9(t),o=T9(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(c=pD(c)),[c,pD(c)]}function p3e(t){const e=pD(t);return[SU(t),e,SU(e)]}function SU(t){return t.replace(/start|end/g,e=>f3e[e])}function g3e(t,e,r){const n=["left","right"],i=["right","left"],o=["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?o:c;default:return[]}}function y3e(t,e,r,n){const i=MS(t);let o=g3e(zp(t),r==="start",n);return i&&(o=o.map(c=>c+"-"+i),e&&(o=o.concat(o.map(SU)))),o}function pD(t){return t.replace(/left|right|bottom|top/g,e=>h3e[e])}function x3e(t){return{top:0,right:0,bottom:0,left:0,...t}}function Kme(t){return typeof t!="number"?x3e(t):{top:t,right:t,bottom:t,left:t}}function gD(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 Oee(t,e,r){let{reference:n,floating:i}=t;const o=Jy(e),c=E9(e),s=T9(c),f=zp(e),p=o==="y",y=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,y:n.y-i.height};break;case"bottom":E={x:y,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(MS(e)){case"start":E[c]-=T*(r&&p?-1:1);break;case"end":E[c]+=T*(r&&p?-1:1);break}return E}const _3e=async(t,e,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:c}=r,s=o.filter(Boolean),f=await(c.isRTL==null?void 0:c.isRTL(e));let p=await c.getElementRects({reference:t,floating:e,strategy:i}),{x:y,y:_}=Oee(p,n,f),T=n,E={},k=0;for(let P=0;P({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:o,platform:c,elements:s,middlewareData:f}=e,{element:p,padding:y=0}=Bp(t,e)||{};if(p==null)return{};const _=Kme(y),T={x:r,y:n},E=E9(i),k=T9(E),P=await c.getDimensions(p),R=E==="y",D=R?"top":"left",M=R?"bottom":"right",B=R?"clientHeight":"clientWidth",V=o.reference[k]+o.reference[E]-T[E]-o.floating[k],G=T[E]-o.reference[E],W=await(c.getOffsetParent==null?void 0:c.getOffsetParent(p));let Z=W?W[B]:0;(!Z||!await(c.isElement==null?void 0:c.isElement(W)))&&(Z=s.floating[B]||o.floating[k]);const Q=V/2-G/2,re=Z/2-P[k]/2-1,se=Xy(_[D],re),ue=Xy(_[M],re),_e=se,we=Z-P[k]-ue,Ce=Z/2-P[k]/2+Q,Me=wU(_e,Ce,we),Ae=!f.arrow&&MS(i)!=null&&Ce!==Me&&o.reference[k]/2-(Ce<_e?se:ue)-P[k]/2<0,be=Ae?Ce<_e?Ce-_e:Ce-we:0;return{[E]:T[E]+be,data:{[E]:Me,centerOffset:Ce-Me-be,...Ae&&{alignmentOffset:be}},reset:Ae}}}),b3e=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var r,n;const{placement:i,middlewareData:o,rects:c,initialPlacement:s,platform:f,elements:p}=e,{mainAxis:y=!0,crossAxis:_=!0,fallbackPlacements:T,fallbackStrategy:E="bestFit",fallbackAxisSideDirection:k="none",flipAlignment:P=!0,...R}=Bp(t,e);if((r=o.arrow)!=null&&r.alignmentOffset)return{};const D=zp(i),M=Jy(s),B=zp(s)===s,V=await(f.isRTL==null?void 0:f.isRTL(p.floating)),G=T||(B||!P?[pD(s)]:p3e(s)),W=k!=="none";!T&&W&&G.push(...y3e(s,P,k,V));const Z=[s,...G],Q=await Aj(e,R),re=[];let se=((n=o.flip)==null?void 0:n.overflows)||[];if(y&&re.push(Q[D]),_){const Ce=m3e(i,c,V);re.push(Q[Ce[0]],Q[Ce[1]])}if(se=[...se,{placement:i,overflows:re}],!re.every(Ce=>Ce<=0)){var ue,_e;const Ce=(((ue=o.flip)==null?void 0:ue.index)||0)+1,Me=Z[Ce];if(Me)return{data:{index:Ce,overflows:se},reset:{placement:Me}};let Ae=(_e=se.filter(be=>be.overflows[0]<=0).sort((be,me)=>be.overflows[1]-me.overflows[1])[0])==null?void 0:_e.placement;if(!Ae)switch(E){case"bestFit":{var we;const be=(we=se.filter(me=>{if(W){const Pe=Jy(me.placement);return Pe===M||Pe==="y"}return!0}).map(me=>[me.placement,me.overflows.filter(Pe=>Pe>0).reduce((Pe,Ie)=>Pe+Ie,0)]).sort((me,Pe)=>me[1]-Pe[1])[0])==null?void 0:we[0];be&&(Ae=be);break}case"initialPlacement":Ae=s;break}if(i!==Ae)return{reset:{placement:Ae}}}return{}}}};function Fee(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function Bee(t){return d3e.some(e=>t[e]>=0)}const w3e=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r}=e,{strategy:n="referenceHidden",...i}=Bp(t,e);switch(n){case"referenceHidden":{const o=await Aj(e,{...i,elementContext:"reference"}),c=Fee(o,r.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:Bee(c)}}}case"escaped":{const o=await Aj(e,{...i,altBoundary:!0}),c=Fee(o,r.floating);return{data:{escapedOffsets:c,escaped:Bee(c)}}}default:return{}}}}};async function S3e(t,e){const{placement:r,platform:n,elements:i}=t,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=zp(r),s=MS(r),f=Jy(r)==="y",p=["left","top"].includes(c)?-1:1,y=o&&f?-1:1,_=Bp(e,t);let{mainAxis:T,crossAxis:E,alignmentAxis:k}=typeof _=="number"?{mainAxis:_,crossAxis:0,alignmentAxis:null}:{mainAxis:_.mainAxis||0,crossAxis:_.crossAxis||0,alignmentAxis:_.alignmentAxis};return s&&typeof k=="number"&&(E=s==="end"?k*-1:k),f?{x:E*y,y:T*p}:{x:T*p,y:E*y}}const T3e=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var r,n;const{x:i,y:o,placement:c,middlewareData:s}=e,f=await S3e(e,t);return c===((r=s.offset)==null?void 0:r.placement)&&(n=s.arrow)!=null&&n.alignmentOffset?{}:{x:i+f.x,y:o+f.y,data:{...f,placement:c}}}}},E3e=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:r,y:n,placement:i}=e,{mainAxis:o=!0,crossAxis:c=!1,limiter:s={fn:R=>{let{x:D,y:M}=R;return{x:D,y:M}}},...f}=Bp(t,e),p={x:r,y:n},y=await Aj(e,f),_=Jy(zp(i)),T=S9(_);let E=p[T],k=p[_];if(o){const R=T==="y"?"top":"left",D=T==="y"?"bottom":"right",M=E+y[R],B=E-y[D];E=wU(M,E,B)}if(c){const R=_==="y"?"top":"left",D=_==="y"?"bottom":"right",M=k+y[R],B=k-y[D];k=wU(M,k,B)}const P=s.fn({...e,[T]:E,[_]:k});return{...P,data:{x:P.x-r,y:P.y-n,enabled:{[T]:o,[_]:c}}}}}},A3e=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:r,y:n,placement:i,rects:o,middlewareData:c}=e,{offset:s=0,mainAxis:f=!0,crossAxis:p=!0}=Bp(t,e),y={x:r,y:n},_=Jy(i),T=S9(_);let E=y[T],k=y[_];const P=Bp(s,e),R=typeof P=="number"?{mainAxis:P,crossAxis:0}:{mainAxis:0,crossAxis:0,...P};if(f){const B=T==="y"?"height":"width",V=o.reference[T]-o.floating[B]+R.mainAxis,G=o.reference[T]+o.reference[B]-R.mainAxis;EG&&(E=G)}if(p){var D,M;const B=T==="y"?"width":"height",V=["top","left"].includes(zp(i)),G=o.reference[_]-o.floating[B]+(V&&((D=c.offset)==null?void 0:D[_])||0)+(V?0:R.crossAxis),W=o.reference[_]+o.reference[B]+(V?0:((M=c.offset)==null?void 0:M[_])||0)-(V?R.crossAxis:0);kW&&(k=W)}return{[T]:E,[_]:k}}}},j3e=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var r,n;const{placement:i,rects:o,platform:c,elements:s}=e,{apply:f=()=>{},...p}=Bp(t,e),y=await Aj(e,p),_=zp(i),T=MS(i),E=Jy(i)==="y",{width:k,height:P}=o.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=P-y.top-y.bottom,B=k-y.left-y.right,V=Xy(P-y[R],M),G=Xy(k-y[D],B),W=!e.middlewareData.shift;let Z=V,Q=G;if((r=e.middlewareData.shift)!=null&&r.enabled.x&&(Q=B),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(Z=M),W&&!T){const se=ed(y.left,0),ue=ed(y.right,0),_e=ed(y.top,0),we=ed(y.bottom,0);E?Q=k-2*(se!==0||ue!==0?se+ue:ed(y.left,y.right)):Z=P-2*(_e!==0||we!==0?_e+we:ed(y.top,y.bottom))}await f({...e,availableWidth:Q,availableHeight:Z});const re=await c.getDimensions(s.floating);return k!==re.width||P!==re.height?{reset:{rects:!0}}:{}}}};function $O(){return typeof window<"u"}function OS(t){return Yme(t)?(t.nodeName||"").toLowerCase():"#document"}function od(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function _m(t){var e;return(e=(Yme(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Yme(t){return $O()?t instanceof Node||t instanceof od(t).Node:!1}function lf(t){return $O()?t instanceof Element||t instanceof od(t).Element:!1}function dm(t){return $O()?t instanceof HTMLElement||t instanceof od(t).HTMLElement:!1}function zee(t){return!$O()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof od(t).ShadowRoot}function aC(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=cf(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&!["inline","contents"].includes(i)}function k3e(t){return["table","td","th"].includes(OS(t))}function UO(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function A9(t){const e=j9(),r=lf(t)?cf(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 C3e(t){let e=ex(t);for(;dm(e)&&!L1(e);){if(A9(e))return e;if(UO(e))return null;e=ex(e)}return null}function j9(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function L1(t){return["html","body","#document"].includes(OS(t))}function cf(t){return od(t).getComputedStyle(t)}function VO(t){return lf(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function ex(t){if(OS(t)==="html")return t;const e=t.assignedSlot||t.parentNode||zee(t)&&t.host||_m(t);return zee(e)?e.host:e}function Zme(t){const e=ex(t);return L1(e)?t.ownerDocument?t.ownerDocument.body:t.body:dm(e)&&aC(e)?e:Zme(e)}function jj(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=Zme(t),o=i===((n=t.ownerDocument)==null?void 0:n.body),c=od(i);if(o){const s=TU(c);return e.concat(c,c.visualViewport||[],aC(i)?i:[],s&&r?jj(s):[])}return e.concat(i,jj(i,[],r))}function TU(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Xme(t){const e=cf(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=dm(t),o=i?t.offsetWidth:r,c=i?t.offsetHeight:n,s=mD(r)!==o||mD(n)!==c;return s&&(r=o,n=c),{width:r,height:n,$:s}}function k9(t){return lf(t)?t:t.contextElement}function Xw(t){const e=k9(t);if(!dm(e))return Qy(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:o}=Xme(e);let c=(o?mD(r.width):r.width)/n,s=(o?mD(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!s||!Number.isFinite(s))&&(s=1),{x:c,y:s}}const I3e=Qy(0);function Qme(t){const e=od(t);return!j9()||!e.visualViewport?I3e:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function N3e(t,e,r){return e===void 0&&(e=!1),!r||e&&r!==od(t)?!1:e}function z_(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),o=k9(t);let c=Qy(1);e&&(n?lf(n)&&(c=Xw(n)):c=Xw(t));const s=N3e(o,r,n)?Qme(o):Qy(0);let f=(i.left+s.x)/c.x,p=(i.top+s.y)/c.y,y=i.width/c.x,_=i.height/c.y;if(o){const T=od(o),E=n&&lf(n)?od(n):n;let k=T,P=TU(k);for(;P&&n&&E!==k;){const R=Xw(P),D=P.getBoundingClientRect(),M=cf(P),B=D.left+(P.clientLeft+parseFloat(M.paddingLeft))*R.x,V=D.top+(P.clientTop+parseFloat(M.paddingTop))*R.y;f*=R.x,p*=R.y,y*=R.x,_*=R.y,f+=B,p+=V,k=od(P),P=TU(k)}}return gD({width:y,height:_,x:f,y:p})}function P3e(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const o=i==="fixed",c=_m(n),s=e?UO(e.floating):!1;if(n===c||s&&o)return r;let f={scrollLeft:0,scrollTop:0},p=Qy(1);const y=Qy(0),_=dm(n);if((_||!_&&!o)&&((OS(n)!=="body"||aC(c))&&(f=VO(n)),dm(n))){const T=z_(n);p=Xw(n),y.x=T.x+n.clientLeft,y.y=T.y+n.clientTop}return{width:r.width*p.x,height:r.height*p.y,x:r.x*p.x-f.scrollLeft*p.x+y.x,y:r.y*p.y-f.scrollTop*p.y+y.y}}function R3e(t){return Array.from(t.getClientRects())}function EU(t,e){const r=VO(t).scrollLeft;return e?e.left+r:z_(_m(t)).left+r}function L3e(t){const e=_m(t),r=VO(t),n=t.ownerDocument.body,i=ed(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=ed(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let c=-r.scrollLeft+EU(t);const s=-r.scrollTop;return cf(n).direction==="rtl"&&(c+=ed(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:c,y:s}}function D3e(t,e){const r=od(t),n=_m(t),i=r.visualViewport;let o=n.clientWidth,c=n.clientHeight,s=0,f=0;if(i){o=i.width,c=i.height;const p=j9();(!p||p&&e==="fixed")&&(s=i.offsetLeft,f=i.offsetTop)}return{width:o,height:c,x:s,y:f}}function M3e(t,e){const r=z_(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,o=dm(t)?Xw(t):Qy(1),c=t.clientWidth*o.x,s=t.clientHeight*o.y,f=i*o.x,p=n*o.y;return{width:c,height:s,x:f,y:p}}function $ee(t,e,r){let n;if(e==="viewport")n=D3e(t,r);else if(e==="document")n=L3e(_m(t));else if(lf(e))n=M3e(e,r);else{const i=Qme(t);n={...e,x:e.x-i.x,y:e.y-i.y}}return gD(n)}function Jme(t,e){const r=ex(t);return r===e||!lf(r)||L1(r)?!1:cf(r).position==="fixed"||Jme(r,e)}function O3e(t,e){const r=e.get(t);if(r)return r;let n=jj(t,[],!1).filter(s=>lf(s)&&OS(s)!=="body"),i=null;const o=cf(t).position==="fixed";let c=o?ex(t):t;for(;lf(c)&&!L1(c);){const s=cf(c),f=A9(c);!f&&s.position==="fixed"&&(i=null),(o?!f&&!i:!f&&s.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||aC(c)&&!f&&Jme(t,c))?n=n.filter(y=>y!==c):i=s,c=ex(c)}return e.set(t,n),n}function F3e(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?UO(e)?[]:O3e(e,this._c):[].concat(r),n],s=c[0],f=c.reduce((p,y)=>{const _=$ee(e,y,i);return p.top=ed(_.top,p.top),p.right=Xy(_.right,p.right),p.bottom=Xy(_.bottom,p.bottom),p.left=ed(_.left,p.left),p},$ee(e,s,i));return{width:f.right-f.left,height:f.bottom-f.top,x:f.left,y:f.top}}function B3e(t){const{width:e,height:r}=Xme(t);return{width:e,height:r}}function z3e(t,e,r){const n=dm(e),i=_m(e),o=r==="fixed",c=z_(t,!0,o,e);let s={scrollLeft:0,scrollTop:0};const f=Qy(0);if(n||!n&&!o)if((OS(e)!=="body"||aC(i))&&(s=VO(e)),n){const E=z_(e,!0,o,e);f.x=E.x+e.clientLeft,f.y=E.y+e.clientTop}else i&&(f.x=EU(i));let p=0,y=0;if(i&&!n&&!o){const E=i.getBoundingClientRect();y=E.top+s.scrollTop,p=E.left+s.scrollLeft-EU(i,E)}const _=c.left+s.scrollLeft-f.x-p,T=c.top+s.scrollTop-f.y-y;return{x:_,y:T,width:c.width,height:c.height}}function XB(t){return cf(t).position==="static"}function Uee(t,e){if(!dm(t)||cf(t).position==="fixed")return null;if(e)return e(t);let r=t.offsetParent;return _m(t)===r&&(r=r.ownerDocument.body),r}function epe(t,e){const r=od(t);if(UO(t))return r;if(!dm(t)){let i=ex(t);for(;i&&!L1(i);){if(lf(i)&&!XB(i))return i;i=ex(i)}return r}let n=Uee(t,e);for(;n&&k3e(n)&&XB(n);)n=Uee(n,e);return n&&L1(n)&&XB(n)&&!A9(n)?r:n||C3e(t)||r}const $3e=async function(t){const e=this.getOffsetParent||epe,r=this.getDimensions,n=await r(t.floating);return{reference:z3e(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function U3e(t){return cf(t).direction==="rtl"}const V3e={convertOffsetParentRelativeRectToViewportRelativeRect:P3e,getDocumentElement:_m,getClippingRect:F3e,getOffsetParent:epe,getElementRects:$3e,getClientRects:R3e,getDimensions:B3e,getScale:Xw,isElement:lf,isRTL:U3e};function q3e(t,e){let r=null,n;const i=_m(t);function o(){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),o();const{left:p,top:y,width:_,height:T}=t.getBoundingClientRect();if(s||e(),!_||!T)return;const E=LP(y),k=LP(i.clientWidth-(p+_)),P=LP(i.clientHeight-(y+T)),R=LP(p),M={rootMargin:-E+"px "+-k+"px "+-P+"px "+-R+"px",threshold:ed(0,Xy(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),o}function G3e(t,e,r,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:f=!1}=n,p=k9(t),y=i||o?[...p?jj(p):[],...jj(e)]:[];y.forEach(D=>{i&&D.addEventListener("scroll",r,{passive:!0}),o&&D.addEventListener("resize",r)});const _=p&&s?q3e(p,r):null;let T=-1,E=null;c&&(E=new ResizeObserver(D=>{let[M]=D;M&&M.target===p&&E&&(E.unobserve(e),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var B;(B=E)==null||B.observe(e)})),r()}),p&&!f&&E.observe(p),E.observe(e));let k,P=f?z_(t):null;f&&R();function R(){const D=z_(t);P&&(D.x!==P.x||D.y!==P.y||D.width!==P.width||D.height!==P.height)&&r(),P=D,k=requestAnimationFrame(R)}return r(),()=>{var D;y.forEach(M=>{i&&M.removeEventListener("scroll",r),o&&M.removeEventListener("resize",r)}),_==null||_(),(D=E)==null||D.disconnect(),E=null,f&&cancelAnimationFrame(k)}}const H3e=T3e,W3e=E3e,K3e=b3e,Y3e=j3e,Z3e=w3e,Vee=v3e,X3e=A3e,Q3e=(t,e,r)=>{const n=new Map,i={platform:V3e,...r},o={...i.platform,_c:n};return _3e(t,e,{...i,platform:o})};var iL=typeof document<"u"?I.useLayoutEffect:I.useEffect;function yD(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(!yD(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 o=i[n];if(!(o==="_owner"&&t.$$typeof)&&!yD(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function tpe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function qee(t,e){const r=tpe(t);return Math.round(e*r)/r}function QB(t){const e=I.useRef(t);return iL(()=>{e.current=t}),e}function J3e(t){t===void 0&&(t={});const{placement:e="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:o,floating:c}={},transform:s=!0,whileElementsMounted:f,open:p}=t,[y,_]=I.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[T,E]=I.useState(n);yD(T,n)||E(n);const[k,P]=I.useState(null),[R,D]=I.useState(null),M=I.useCallback(me=>{me!==W.current&&(W.current=me,P(me))},[]),B=I.useCallback(me=>{me!==Z.current&&(Z.current=me,D(me))},[]),V=o||k,G=c||R,W=I.useRef(null),Z=I.useRef(null),Q=I.useRef(y),re=f!=null,se=QB(f),ue=QB(i),_e=QB(p),we=I.useCallback(()=>{if(!W.current||!Z.current)return;const me={placement:e,strategy:r,middleware:T};ue.current&&(me.platform=ue.current),Q3e(W.current,Z.current,me).then(Pe=>{const Ie={...Pe,isPositioned:_e.current!==!1};Ce.current&&!yD(Q.current,Ie)&&(Q.current=Ie,Yp.flushSync(()=>{_(Ie)}))})},[T,e,r,ue,_e]);iL(()=>{p===!1&&Q.current.isPositioned&&(Q.current.isPositioned=!1,_(me=>({...me,isPositioned:!1})))},[p]);const Ce=I.useRef(!1);iL(()=>(Ce.current=!0,()=>{Ce.current=!1}),[]),iL(()=>{if(V&&(W.current=V),G&&(Z.current=G),V&&G){if(se.current)return se.current(V,G,we);we()}},[V,G,we,se,re]);const Me=I.useMemo(()=>({reference:W,floating:Z,setReference:M,setFloating:B}),[M,B]),Ae=I.useMemo(()=>({reference:V,floating:G}),[V,G]),be=I.useMemo(()=>{const me={position:r,left:0,top:0};if(!Ae.floating)return me;const Pe=qee(Ae.floating,y.x),Ie=qee(Ae.floating,y.y);return s?{...me,transform:"translate("+Pe+"px, "+Ie+"px)",...tpe(Ae.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:Pe,top:Ie}},[r,s,Ae.floating,y.x,y.y]);return I.useMemo(()=>({...y,update:we,refs:Me,elements:Ae,floatingStyles:be}),[y,we,Me,Ae,be])}const eFe=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?Vee({element:n.current,padding:i}).fn(r):{}:n?Vee({element:n,padding:i}).fn(r):{}}}},tFe=(t,e)=>({...H3e(t),options:[t,e]}),rFe=(t,e)=>({...W3e(t),options:[t,e]}),nFe=(t,e)=>({...X3e(t),options:[t,e]}),iFe=(t,e)=>({...K3e(t),options:[t,e]}),sFe=(t,e)=>({...Y3e(t),options:[t,e]}),aFe=(t,e)=>({...Z3e(t),options:[t,e]}),oFe=(t,e)=>({...eFe(t),options:[t,e]});var lFe="Arrow",rpe=I.forwardRef((t,e)=>{const{children:r,width:n=10,height:i=5,...o}=t;return a.jsx(rn.svg,{...o,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:a.jsx("polygon",{points:"0,0 30,0 15,10"})})});rpe.displayName=lFe;var cFe=rpe;function oC(t){const[e,r]=I.useState(void 0);return Po(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let c,s;if("borderBoxSize"in o){const f=o.borderBoxSize,p=Array.isArray(f)?f[0]:f;c=p.inlineSize,s=p.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 C9="Popper",[npe,mx]=Yo(C9),[uFe,ipe]=npe(C9),spe=t=>{const{__scopePopper:e,children:r}=t,[n,i]=I.useState(null);return a.jsx(uFe,{scope:e,anchor:n,onAnchorChange:i,children:r})};spe.displayName=C9;var ape="PopperAnchor",ope=I.forwardRef((t,e)=>{const{__scopePopper:r,virtualRef:n,...i}=t,o=ipe(ape,r),c=I.useRef(null),s=Kn(e,c);return I.useEffect(()=>{o.onAnchorChange((n==null?void 0:n.current)||c.current)}),n?null:a.jsx(rn.div,{...i,ref:s})});ope.displayName=ape;var I9="PopperContent",[dFe,hFe]=npe(I9),lpe=I.forwardRef((t,e)=>{var _t,Vt,pt,Nt,er,vt;const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:c=0,arrowPadding:s=0,avoidCollisions:f=!0,collisionBoundary:p=[],collisionPadding:y=0,sticky:_="partial",hideWhenDetached:T=!1,updatePositionStrategy:E="optimized",onPlaced:k,...P}=t,R=ipe(I9,r),[D,M]=I.useState(null),B=Kn(e,or=>M(or)),[V,G]=I.useState(null),W=oC(V),Z=(W==null?void 0:W.width)??0,Q=(W==null?void 0:W.height)??0,re=n+(o!=="center"?"-"+o:""),se=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},ue=Array.isArray(p)?p:[p],_e=ue.length>0,we={padding:se,boundary:ue.filter(mFe),altBoundary:_e},{refs:Ce,floatingStyles:Me,placement:Ae,isPositioned:be,middlewareData:me}=J3e({strategy:"fixed",placement:re,whileElementsMounted:(...or)=>G3e(...or,{animationFrame:E==="always"}),elements:{reference:R.anchor},middleware:[tFe({mainAxis:i+Q,alignmentAxis:c}),f&&rFe({mainAxis:!0,crossAxis:!1,limiter:_==="partial"?nFe():void 0,...we}),f&&iFe({...we}),sFe({...we,apply:({elements:or,rects:Sr,availableWidth:nn,availableHeight:cr})=>{const{width:xr,height:tr}=Sr.reference,_n=or.floating.style;_n.setProperty("--radix-popper-available-width",`${nn}px`),_n.setProperty("--radix-popper-available-height",`${cr}px`),_n.setProperty("--radix-popper-anchor-width",`${xr}px`),_n.setProperty("--radix-popper-anchor-height",`${tr}px`)}}),V&&oFe({element:V,padding:s}),pFe({arrowWidth:Z,arrowHeight:Q}),T&&aFe({strategy:"referenceHidden",...we})]}),[Pe,Ie]=dpe(Ae),Se=po(k);Po(()=>{be&&(Se==null||Se())},[be,Se]);const ve=(_t=me.arrow)==null?void 0:_t.x,We=(Vt=me.arrow)==null?void 0:Vt.y,rt=((pt=me.arrow)==null?void 0:pt.centerOffset)!==0,[at,Et]=I.useState();return Po(()=>{D&&Et(window.getComputedStyle(D).zIndex)},[D]),a.jsx("div",{ref:Ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Me,transform:be?Me.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:at,"--radix-popper-transform-origin":[(Nt=me.transformOrigin)==null?void 0:Nt.x,(er=me.transformOrigin)==null?void 0:er.y].join(" "),...((vt=me.hide)==null?void 0:vt.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:a.jsx(dFe,{scope:r,placedSide:Pe,onArrowChange:G,arrowX:ve,arrowY:We,shouldHideArrow:rt,children:a.jsx(rn.div,{"data-side":Pe,"data-align":Ie,...P,ref:B,style:{...P.style,animation:be?void 0:"none"}})})})});lpe.displayName=I9;var cpe="PopperArrow",fFe={top:"bottom",right:"left",bottom:"top",left:"right"},upe=I.forwardRef(function(e,r){const{__scopePopper:n,...i}=e,o=hFe(cpe,n),c=fFe[o.placedSide];return a.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[c]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:a.jsx(cFe,{...i,ref:r,style:{...i.style,display:"block"}})})});upe.displayName=cpe;function mFe(t){return t!==null}var pFe=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,[p,y]=dpe(r),_={start:"0%",center:"50%",end:"100%"}[y],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 k="",P="";return p==="bottom"?(k=c?_:`${T}px`,P=`${-f}px`):p==="top"?(k=c?_:`${T}px`,P=`${n.floating.height+f}px`):p==="right"?(k=`${-f}px`,P=c?_:`${E}px`):p==="left"&&(k=`${n.floating.width+f}px`,P=c?_:`${E}px`),{data:{x:k,y:P}}}});function dpe(t){const[e,r="center"]=t.split("-");return[e,r]}var qO=spe,lC=ope,GO=lpe,HO=upe,[WO,_Vt]=Yo("Tooltip",[mx]),KO=mx(),hpe="TooltipProvider",gFe=700,AU="tooltip.open",[yFe,N9]=WO(hpe),fpe=t=>{const{__scopeTooltip:e,delayDuration:r=gFe,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=t,c=I.useRef(!0),s=I.useRef(!1),f=I.useRef(0);return I.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),a.jsx(yFe,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:I.useCallback(()=>{window.clearTimeout(f.current),c.current=!1},[]),onClose:I.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.current=!0,n)},[n]),isPointerInTransitRef:s,onPointerInTransitChange:I.useCallback(p=>{s.current=p},[]),disableHoverableContent:i,children:o})};fpe.displayName=hpe;var kj="Tooltip",[xFe,YO]=WO(kj),mpe=t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:o,disableHoverableContent:c,delayDuration:s}=t,f=N9(kj,t.__scopeTooltip),p=KO(e),[y,_]=I.useState(null),T=Dl(),E=I.useRef(0),k=c??f.disableHoverableContent,P=s??f.delayDuration,R=I.useRef(!1),[D,M]=dd({prop:n,defaultProp:i??!1,onChange:Z=>{Z?(f.onOpen(),document.dispatchEvent(new CustomEvent(AU))):f.onClose(),o==null||o(Z)},caller:kj}),B=I.useMemo(()=>D?R.current?"delayed-open":"instant-open":"closed",[D]),V=I.useCallback(()=>{window.clearTimeout(E.current),E.current=0,R.current=!1,M(!0)},[M]),G=I.useCallback(()=>{window.clearTimeout(E.current),E.current=0,M(!1)},[M]),W=I.useCallback(()=>{window.clearTimeout(E.current),E.current=window.setTimeout(()=>{R.current=!0,M(!0),E.current=0},P)},[P,M]);return I.useEffect(()=>()=>{E.current&&(window.clearTimeout(E.current),E.current=0)},[]),a.jsx(qO,{...p,children:a.jsx(xFe,{scope:e,contentId:T,open:D,stateAttribute:B,trigger:y,onTriggerChange:_,onTriggerEnter:I.useCallback(()=>{f.isOpenDelayedRef.current?W():V()},[f.isOpenDelayedRef,W,V]),onTriggerLeave:I.useCallback(()=>{k?G():(window.clearTimeout(E.current),E.current=0)},[G,k]),onOpen:V,onClose:G,disableHoverableContent:k,children:r})})};mpe.displayName=kj;var jU="TooltipTrigger",ppe=I.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=YO(jU,r),o=N9(jU,r),c=KO(r),s=I.useRef(null),f=Kn(e,s,i.onTriggerChange),p=I.useRef(!1),y=I.useRef(!1),_=I.useCallback(()=>p.current=!1,[]);return I.useEffect(()=>()=>document.removeEventListener("pointerup",_),[_]),a.jsx(lC,{asChild:!0,...c,children:a.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"&&!y.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Or(t.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Or(t.onPointerDown,()=>{i.open&&i.onClose(),p.current=!0,document.addEventListener("pointerup",_,{once:!0})}),onFocus:Or(t.onFocus,()=>{p.current||i.onOpen()}),onBlur:Or(t.onBlur,i.onClose),onClick:Or(t.onClick,i.onClose)})})});ppe.displayName=jU;var _Fe="TooltipPortal",[vVt,vFe]=WO(_Fe,{forceMount:void 0}),D1="TooltipContent",gpe=I.forwardRef((t,e)=>{const r=vFe(D1,t.__scopeTooltip),{forceMount:n=r.forceMount,side:i="top",...o}=t,c=YO(D1,t.__scopeTooltip);return a.jsx(pl,{present:n||c.open,children:c.disableHoverableContent?a.jsx(ype,{side:i,...o,ref:e}):a.jsx(bFe,{side:i,...o,ref:e})})}),bFe=I.forwardRef((t,e)=>{const r=YO(D1,t.__scopeTooltip),n=N9(D1,t.__scopeTooltip),i=I.useRef(null),o=Kn(e,i),[c,s]=I.useState(null),{trigger:f,onClose:p}=r,y=i.current,{onPointerInTransitChange:_}=n,T=I.useCallback(()=>{s(null),_(!1)},[_]),E=I.useCallback((k,P)=>{const R=k.currentTarget,D={x:k.clientX,y:k.clientY},M=AFe(D,R.getBoundingClientRect()),B=jFe(D,M),V=kFe(P.getBoundingClientRect()),G=IFe([...B,...V]);s(G),_(!0)},[_]);return I.useEffect(()=>()=>T(),[T]),I.useEffect(()=>{if(f&&y){const k=R=>E(R,y),P=R=>E(R,f);return f.addEventListener("pointerleave",k),y.addEventListener("pointerleave",P),()=>{f.removeEventListener("pointerleave",k),y.removeEventListener("pointerleave",P)}}},[f,y,E,T]),I.useEffect(()=>{if(c){const k=P=>{const R=P.target,D={x:P.clientX,y:P.clientY},M=(f==null?void 0:f.contains(R))||(y==null?void 0:y.contains(R)),B=!CFe(D,c);M?T():B&&(T(),p())};return document.addEventListener("pointermove",k),()=>document.removeEventListener("pointermove",k)}},[f,y,c,p,T]),a.jsx(ype,{...t,ref:o})}),[wFe,SFe]=WO(kj,{isInside:!1}),TFe=rfe("TooltipContent"),ype=I.forwardRef((t,e)=>{const{__scopeTooltip:r,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:c,...s}=t,f=YO(D1,r),p=KO(r),{onClose:y}=f;return I.useEffect(()=>(document.addEventListener(AU,y),()=>document.removeEventListener(AU,y)),[y]),I.useEffect(()=>{if(f.trigger){const _=T=>{const E=T.target;E!=null&&E.contains(f.trigger)&&y()};return window.addEventListener("scroll",_,{capture:!0}),()=>window.removeEventListener("scroll",_,{capture:!0})}},[f.trigger,y]),a.jsx(rv,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:_=>_.preventDefault(),onDismiss:y,children:a.jsxs(GO,{"data-state":f.stateAttribute,...p,...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:[a.jsx(TFe,{children:n}),a.jsx(wFe,{scope:r,isInside:!0,children:a.jsx(vLe,{id:f.contentId,role:"tooltip",children:i||n})})]})})});gpe.displayName=D1;var xpe="TooltipArrow",EFe=I.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=KO(r);return SFe(xpe,r).isInside?null:a.jsx(HO,{...i,...n,ref:e})});EFe.displayName=xpe;function AFe(t,e){const r=Math.abs(e.top-t.y),n=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),o=Math.abs(e.left-t.x);switch(Math.min(r,n,i,o)){case o:return"left";case i:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function jFe(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 kFe(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 CFe(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=T>n&&r<(_-p)*(n-y)/(T-y)+p&&(i=!i)}return i}function IFe(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),NFe(e)}function NFe(t){if(t.length<=1)return t.slice();const e=[];for(let n=0;n=2;){const o=e[e.length-1],c=e[e.length-2];if((o.x-c.x)*(i.y-c.y)>=(o.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 o=r[r.length-1],c=r[r.length-2];if((o.x-c.x)*(i.y-c.y)>=(o.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 PFe=fpe,RFe=mpe,LFe=ppe,_pe=gpe;const vpe=PFe,DFe=RFe,MFe=LFe,bpe=I.forwardRef(({className:t,sideOffset:e=4,...r},n)=>a.jsx(_pe,{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}));bpe.displayName=_pe.displayName;var FS=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(){}},$_=typeof window>"u"||"Deno"in globalThis;function qc(){}function OFe(t,e){return typeof t=="function"?t(e):t}function kU(t){return typeof t=="number"&&t>=0&&t!==1/0}function wpe(t,e){return Math.max(t+(e||0)-Date.now(),0)}function By(t,e){return typeof t=="function"?t(e):t}function Gd(t,e){return typeof t=="function"?t(e):t}function Gee(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:o,queryKey:c,stale:s}=t;if(c){if(n){if(e.queryHash!==P9(c,e.options))return!1}else if(!Cj(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||o&&!o(e))}function Hee(t,e){const{exact:r,status:n,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(r){if(U_(e.options.mutationKey)!==U_(o))return!1}else if(!Cj(e.options.mutationKey,o))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function P9(t,e){return((e==null?void 0:e.queryKeyHashFn)||U_)(t)}function U_(t){return JSON.stringify(t,(e,r)=>CU(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function Cj(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>Cj(t[r],e[r])):!1}function Spe(t,e){if(t===e)return t;const r=Wee(t)&&Wee(e);if(r||CU(t)&&CU(e)){const n=r?t:Object.keys(t),i=n.length,o=r?e:Object.keys(e),c=o.length,s=r?[]:{},f=new Set(n);let p=0;for(let y=0;y{setTimeout(e,t)})}function IU(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Spe(t,e):e}function BFe(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function zFe(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}var R9=Symbol();function Tpe(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===R9?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function Epe(t,e){return typeof t=="function"?t(...e):!!t}var g_,py,h1,jue,$Fe=(jue=class extends FS{constructor(){super();Xn(this,g_);Xn(this,py);Xn(this,h1);vn(this,h1,e=>{if(!$_&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Tt(this,py)||this.setEventListener(Tt(this,h1))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,py))==null||e.call(this),vn(this,py,void 0))}setEventListener(e){var r;vn(this,h1,e),(r=Tt(this,py))==null||r.call(this),vn(this,py,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Tt(this,g_)!==e&&(vn(this,g_,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Tt(this,g_)=="boolean"?Tt(this,g_):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},g_=new WeakMap,py=new WeakMap,h1=new WeakMap,jue),L9=new $Fe,f1,gy,m1,kue,UFe=(kue=class extends FS{constructor(){super();Xn(this,f1,!0);Xn(this,gy);Xn(this,m1);vn(this,m1,e=>{if(!$_&&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,gy)||this.setEventListener(Tt(this,m1))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,gy))==null||e.call(this),vn(this,gy,void 0))}setEventListener(e){var r;vn(this,m1,e),(r=Tt(this,gy))==null||r.call(this),vn(this,gy,e(this.setOnline.bind(this)))}setOnline(e){Tt(this,f1)!==e&&(vn(this,f1,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Tt(this,f1)}},f1=new WeakMap,gy=new WeakMap,m1=new WeakMap,kue),_D=new UFe;function NU(){let t,e;const r=new Promise((i,o)=>{t=i,e=o});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 VFe(t){return Math.min(1e3*2**t,3e4)}function Ape(t){return(t??"online")==="online"?_D.isOnline():!0}var jpe=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function JB(t){return t instanceof jpe}function kpe(t){let e=!1,r=0,n=!1,i;const o=NU(),c=P=>{var R;n||(T(new jpe(P)),(R=t.abort)==null||R.call(t))},s=()=>{e=!0},f=()=>{e=!1},p=()=>L9.isFocused()&&(t.networkMode==="always"||_D.isOnline())&&t.canRun(),y=()=>Ape(t.networkMode)&&t.canRun(),_=P=>{var R;n||(n=!0,(R=t.onSuccess)==null||R.call(t,P),i==null||i(),o.resolve(P))},T=P=>{var R;n||(n=!0,(R=t.onError)==null||R.call(t,P),i==null||i(),o.reject(P))},E=()=>new Promise(P=>{var R;i=D=>{(n||p())&&P(D)},(R=t.onPause)==null||R.call(t)}).then(()=>{var P;i=void 0,n||(P=t.onContinue)==null||P.call(t)}),k=()=>{if(n)return;let P;const R=r===0?t.initialPromise:void 0;try{P=R??t.fn()}catch(D){P=Promise.reject(D)}Promise.resolve(P).then(_).catch(D=>{var W;if(n)return;const M=t.retry??($_?0:3),B=t.retryDelay??VFe,V=typeof B=="function"?B(r,D):B,G=M===!0||typeof M=="number"&&rp()?void 0:E()).then(()=>{e?T(D):k()})})};return{promise:o,cancel:c,continue:()=>(i==null||i(),o),cancelRetry:s,continueRetry:f,canStart:y,start:()=>(y()?k():E().then(k),o)}}var qFe=t=>setTimeout(t,0);function GFe(){let t=[],e=0,r=s=>{s()},n=s=>{s()},i=qFe;const o=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)=>{o(()=>{s(...f)})},schedule:o,setNotifyFunction:s=>{r=s},setBatchNotifyFunction:s=>{n=s},setScheduler:s=>{i=s}}}var cl=GFe(),y_,Cue,Cpe=(Cue=class{constructor(){Xn(this,y_)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kU(this.gcTime)&&vn(this,y_,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??($_?1/0:5*60*1e3))}clearGcTimeout(){Tt(this,y_)&&(clearTimeout(Tt(this,y_)),vn(this,y_,void 0))}},y_=new WeakMap,Cue),p1,x_,qd,__,gc,$k,v_,Bh,dp,Iue,HFe=(Iue=class extends Cpe{constructor(e){super();Xn(this,Bh);Xn(this,p1);Xn(this,x_);Xn(this,qd);Xn(this,__);Xn(this,gc);Xn(this,$k);Xn(this,v_);vn(this,v_,!1),vn(this,$k,e.defaultOptions),this.setOptions(e.options),this.observers=[],vn(this,__,e.client),vn(this,qd,Tt(this,__).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,vn(this,p1,WFe(this.options)),this.state=e.state??Tt(this,p1),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=Tt(this,gc))==null?void 0:e.promise}setOptions(e){this.options={...Tt(this,$k),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Tt(this,qd).remove(this)}setData(e,r){const n=IU(this.state.data,e,this.options);return Ui(this,Bh,dp).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e,r){Ui(this,Bh,dp).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var n,i;const r=(n=Tt(this,gc))==null?void 0:n.promise;return(i=Tt(this,gc))==null||i.cancel(e),r?r.then(qc).catch(qc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Tt(this,p1))}isActive(){return this.observers.some(e=>Gd(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===R9||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>By(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:!wpe(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,gc))==null||r.continue()}onOnline(){var r;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,gc))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Tt(this,qd).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,gc)&&(Tt(this,v_)?Tt(this,gc).cancel({revert:!0}):Tt(this,gc).cancelRetry()),this.scheduleGc()),Tt(this,qd).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ui(this,Bh,dp).call(this,{type:"invalidate"})}fetch(e,r){var p,y,_;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Tt(this,gc))return Tt(this,gc).continueRetry(),Tt(this,gc).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:()=>(vn(this,v_,!0),n.signal)})},o=()=>{const T=Tpe(this.options,r),k=(()=>{const P={client:Tt(this,__),queryKey:this.queryKey,meta:this.meta};return i(P),P})();return vn(this,v_,!1),this.options.persister?this.options.persister(T,k,this):T(k)},s=(()=>{const T={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Tt(this,__),state:this.state,fetchFn:o};return i(T),T})();(p=this.options.behavior)==null||p.onFetch(s,this),vn(this,x_,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((y=s.fetchOptions)==null?void 0:y.meta))&&Ui(this,Bh,dp).call(this,{type:"fetch",meta:(_=s.fetchOptions)==null?void 0:_.meta});const f=T=>{var E,k,P,R;JB(T)&&T.silent||Ui(this,Bh,dp).call(this,{type:"error",error:T}),JB(T)||((k=(E=Tt(this,qd).config).onError)==null||k.call(E,T,this),(R=(P=Tt(this,qd).config).onSettled)==null||R.call(P,this.state.data,T,this)),this.scheduleGc()};return vn(this,gc,kpe({initialPromise:r==null?void 0:r.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:T=>{var E,k,P,R;if(T===void 0){f(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(T)}catch(D){f(D);return}(k=(E=Tt(this,qd).config).onSuccess)==null||k.call(E,T,this),(R=(P=Tt(this,qd).config).onSettled)==null||R.call(P,T,this.state.error,this),this.scheduleGc()},onError:f,onFail:(T,E)=>{Ui(this,Bh,dp).call(this,{type:"failed",failureCount:T,error:E})},onPause:()=>{Ui(this,Bh,dp).call(this,{type:"pause"})},onContinue:()=>{Ui(this,Bh,dp).call(this,{type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0})),Tt(this,gc).start()}},p1=new WeakMap,x_=new WeakMap,qd=new WeakMap,__=new WeakMap,gc=new WeakMap,$k=new WeakMap,v_=new WeakMap,Bh=new WeakSet,dp=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,...Ipe(n.data,this.options),fetchMeta:e.meta??null};case"success":return vn(this,x_,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 JB(i)&&i.revert&&Tt(this,x_)?{...Tt(this,x_),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),cl.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Tt(this,qd).notify({query:this,type:"updated",action:e})})},Iue);function Ipe(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ape(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function WFe(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 Uf,Nue,KFe=(Nue=class extends FS{constructor(e={}){super();Xn(this,Uf);this.config=e,vn(this,Uf,new Map)}build(e,r,n){const i=r.queryKey,o=r.queryHash??P9(i,r);let c=this.get(o);return c||(c=new HFe({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Tt(this,Uf).has(e.queryHash)||(Tt(this,Uf).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=Tt(this,Uf).get(e.queryHash);r&&(e.destroy(),r===e&&Tt(this,Uf).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){cl.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Tt(this,Uf).get(e)}getAll(){return[...Tt(this,Uf).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>Gee(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>Gee(e,n)):r}notify(e){cl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){cl.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){cl.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Uf=new WeakMap,Nue),Vf,$c,b_,qf,Jg,Pue,YFe=(Pue=class extends Cpe{constructor(e){super();Xn(this,qf);Xn(this,Vf);Xn(this,$c);Xn(this,b_);this.mutationId=e.mutationId,vn(this,$c,e.mutationCache),vn(this,Vf,[]),this.state=e.state||Npe(),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,Vf).includes(e)||(Tt(this,Vf).push(e),this.clearGcTimeout(),Tt(this,$c).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){vn(this,Vf,Tt(this,Vf).filter(r=>r!==e)),this.scheduleGc(),Tt(this,$c).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Tt(this,Vf).length||(this.state.status==="pending"?this.scheduleGc():Tt(this,$c).remove(this))}continue(){var e;return((e=Tt(this,b_))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var o,c,s,f,p,y,_,T,E,k,P,R,D,M,B,V,G,W,Z,Q;const r=()=>{Ui(this,qf,Jg).call(this,{type:"continue"})};vn(this,b_,kpe({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(re,se)=>{Ui(this,qf,Jg).call(this,{type:"failed",failureCount:re,error:se})},onPause:()=>{Ui(this,qf,Jg).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Tt(this,$c).canRun(this)}));const n=this.state.status==="pending",i=!Tt(this,b_).canStart();try{if(n)r();else{Ui(this,qf,Jg).call(this,{type:"pending",variables:e,isPaused:i}),await((c=(o=Tt(this,$c).config).onMutate)==null?void 0:c.call(o,e,this));const se=await((f=(s=this.options).onMutate)==null?void 0:f.call(s,e));se!==this.state.context&&Ui(this,qf,Jg).call(this,{type:"pending",context:se,variables:e,isPaused:i})}const re=await Tt(this,b_).start();return await((y=(p=Tt(this,$c).config).onSuccess)==null?void 0:y.call(p,re,e,this.state.context,this)),await((T=(_=this.options).onSuccess)==null?void 0:T.call(_,re,e,this.state.context)),await((k=(E=Tt(this,$c).config).onSettled)==null?void 0:k.call(E,re,null,this.state.variables,this.state.context,this)),await((R=(P=this.options).onSettled)==null?void 0:R.call(P,re,null,e,this.state.context)),Ui(this,qf,Jg).call(this,{type:"success",data:re}),re}catch(re){try{throw await((M=(D=Tt(this,$c).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,$c).config).onSettled)==null?void 0:W.call(G,void 0,re,this.state.variables,this.state.context,this)),await((Q=(Z=this.options).onSettled)==null?void 0:Q.call(Z,void 0,re,e,this.state.context)),re}finally{Ui(this,qf,Jg).call(this,{type:"error",error:re})}}finally{Tt(this,$c).runNext(this)}}},Vf=new WeakMap,$c=new WeakMap,b_=new WeakMap,qf=new WeakSet,Jg=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),cl.batch(()=>{Tt(this,Vf).forEach(n=>{n.onMutationUpdate(e)}),Tt(this,$c).notify({mutation:this,type:"updated",action:e})})},Pue);function Npe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var xp,zh,Uk,Rue,ZFe=(Rue=class extends FS{constructor(e={}){super();Xn(this,xp);Xn(this,zh);Xn(this,Uk);this.config=e,vn(this,xp,new Set),vn(this,zh,new Map),vn(this,Uk,0)}build(e,r,n){const i=new YFe({mutationCache:this,mutationId:++cP(this,Uk)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Tt(this,xp).add(e);const r=DP(e);if(typeof r=="string"){const n=Tt(this,zh).get(r);n?n.push(e):Tt(this,zh).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Tt(this,xp).delete(e)){const r=DP(e);if(typeof r=="string"){const n=Tt(this,zh).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,zh).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=DP(e);if(typeof r=="string"){const n=Tt(this,zh).get(r),i=n==null?void 0:n.find(o=>o.state.status==="pending");return!i||i===e}else return!0}runNext(e){var n;const r=DP(e);if(typeof r=="string"){const i=(n=Tt(this,zh).get(r))==null?void 0:n.find(o=>o!==e&&o.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){cl.batch(()=>{Tt(this,xp).forEach(e=>{this.notify({type:"removed",mutation:e})}),Tt(this,xp).clear(),Tt(this,zh).clear()})}getAll(){return Array.from(Tt(this,xp))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>Hee(r,n))}findAll(e={}){return this.getAll().filter(r=>Hee(e,r))}notify(e){cl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return cl.batch(()=>Promise.all(e.map(r=>r.continue().catch(qc))))}},xp=new WeakMap,zh=new WeakMap,Uk=new WeakMap,Rue);function DP(t){var e;return(e=t.options.scope)==null?void 0:e.id}function Yee(t){return{onFetch:(e,r)=>{var y,_,T,E,k;const n=e.options,i=(T=(_=(y=e.fetchOptions)==null?void 0:y.meta)==null?void 0:_.fetchMore)==null?void 0:T.direction,o=((E=e.state.data)==null?void 0:E.pages)||[],c=((k=e.state.data)==null?void 0:k.pageParams)||[];let s={pages:[],pageParams:[]},f=0;const p=async()=>{let P=!1;const R=B=>{Object.defineProperty(B,"signal",{enumerable:!0,get:()=>(e.signal.aborted?P=!0:e.signal.addEventListener("abort",()=>{P=!0}),e.signal)})},D=Tpe(e.options,e.fetchOptions),M=async(B,V,G)=>{if(P)return Promise.reject();if(V==null&&B.pages.length)return Promise.resolve(B);const Z=(()=>{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(Z),{maxPages:re}=e.options,se=G?zFe:BFe;return{pages:se(B.pages,Q,re),pageParams:se(B.pageParams,V,re)}};if(i&&o.length){const B=i==="backward",V=B?Ppe:PU,G={pages:o,pageParams:c},W=V(n,G);s=await M(G,W,B)}else{const B=t??o.length;do{const V=f===0?c[0]??n.initialPageParam:PU(n,s);if(f>0&&V==null)break;s=await M(s,V),f++}while(f{var P,R;return(R=(P=e.options).persister)==null?void 0:R.call(P,p,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=p}}}function PU(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 Ppe(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 bVt(t,e){return e?PU(t,e)!=null:!1}function wVt(t,e){return!e||!t.getPreviousPageParam?!1:Ppe(t,e)!=null}var ho,yy,xy,g1,y1,_y,x1,_1,Lue,XFe=(Lue=class{constructor(t={}){Xn(this,ho);Xn(this,yy);Xn(this,xy);Xn(this,g1);Xn(this,y1);Xn(this,_y);Xn(this,x1);Xn(this,_1);vn(this,ho,t.queryCache||new KFe),vn(this,yy,t.mutationCache||new ZFe),vn(this,xy,t.defaultOptions||{}),vn(this,g1,new Map),vn(this,y1,new Map),vn(this,_y,0)}mount(){cP(this,_y)._++,Tt(this,_y)===1&&(vn(this,x1,L9.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,ho).onFocus())})),vn(this,_1,_D.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,ho).onOnline())})))}unmount(){var t,e;cP(this,_y)._--,Tt(this,_y)===0&&((t=Tt(this,x1))==null||t.call(this),vn(this,x1,void 0),(e=Tt(this,_1))==null||e.call(this),vn(this,_1,void 0))}isFetching(t){return Tt(this,ho).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Tt(this,yy).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Tt(this,ho).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Tt(this,ho).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(By(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Tt(this,ho).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,ho).get(n.queryHash),o=i==null?void 0:i.state.data,c=OFe(e,o);if(c!==void 0)return Tt(this,ho).build(this,n).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return cl.batch(()=>Tt(this,ho).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,ho).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Tt(this,ho);cl.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Tt(this,ho);return cl.batch(()=>(r.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},n=cl.batch(()=>Tt(this,ho).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(qc).catch(qc)}invalidateQueries(t,e={}){return cl.batch(()=>(Tt(this,ho).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=cl.batch(()=>Tt(this,ho).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,r);return r.throwOnError||(o=o.catch(qc)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(n).then(qc)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Tt(this,ho).build(this,e);return r.isStaleByTime(By(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(qc).catch(qc)}fetchInfiniteQuery(t){return t.behavior=Yee(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(qc).catch(qc)}ensureInfiniteQueryData(t){return t.behavior=Yee(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return _D.isOnline()?Tt(this,yy).resumePausedMutations():Promise.resolve()}getQueryCache(){return Tt(this,ho)}getMutationCache(){return Tt(this,yy)}getDefaultOptions(){return Tt(this,xy)}setDefaultOptions(t){vn(this,xy,t)}setQueryDefaults(t,e){Tt(this,g1).set(U_(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Tt(this,g1).values()],r={};return e.forEach(n=>{Cj(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Tt(this,y1).set(U_(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Tt(this,y1).values()],r={};return e.forEach(n=>{Cj(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Tt(this,xy).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=P9(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===R9&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Tt(this,xy).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Tt(this,ho).clear(),Tt(this,yy).clear()}},ho=new WeakMap,yy=new WeakMap,xy=new WeakMap,g1=new WeakMap,y1=new WeakMap,_y=new WeakMap,x1=new WeakMap,_1=new WeakMap,Lue),_u,is,Vk,Uc,w_,v1,vy,by,qk,b1,w1,S_,T_,wy,S1,Ls,mA,RU,LU,DU,MU,OU,FU,BU,Rpe,Due,QFe=(Due=class extends FS{constructor(e,r){super();Xn(this,Ls);Xn(this,_u);Xn(this,is);Xn(this,Vk);Xn(this,Uc);Xn(this,w_);Xn(this,v1);Xn(this,vy);Xn(this,by);Xn(this,qk);Xn(this,b1);Xn(this,w1);Xn(this,S_);Xn(this,T_);Xn(this,wy);Xn(this,S1,new Set);this.options=r,vn(this,_u,e),vn(this,by,null),vn(this,vy,NU()),this.options.experimental_prefetchInRender||Tt(this,vy).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,is).addObserver(this),Zee(Tt(this,is),this.options)?Ui(this,Ls,mA).call(this):this.updateResult(),Ui(this,Ls,MU).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zU(Tt(this,is),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zU(Tt(this,is),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ui(this,Ls,OU).call(this),Ui(this,Ls,FU).call(this),Tt(this,is).removeObserver(this)}setOptions(e){const r=this.options,n=Tt(this,is);if(this.options=Tt(this,_u).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Gd(this.options.enabled,Tt(this,is))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ui(this,Ls,BU).call(this),Tt(this,is).setOptions(this.options),r._defaulted&&!xD(this.options,r)&&Tt(this,_u).getQueryCache().notify({type:"observerOptionsUpdated",query:Tt(this,is),observer:this});const i=this.hasListeners();i&&Xee(Tt(this,is),n,this.options,r)&&Ui(this,Ls,mA).call(this),this.updateResult(),i&&(Tt(this,is)!==n||Gd(this.options.enabled,Tt(this,is))!==Gd(r.enabled,Tt(this,is))||By(this.options.staleTime,Tt(this,is))!==By(r.staleTime,Tt(this,is)))&&Ui(this,Ls,RU).call(this);const o=Ui(this,Ls,LU).call(this);i&&(Tt(this,is)!==n||Gd(this.options.enabled,Tt(this,is))!==Gd(r.enabled,Tt(this,is))||o!==Tt(this,wy))&&Ui(this,Ls,DU).call(this,o)}getOptimisticResult(e){const r=Tt(this,_u).getQueryCache().build(Tt(this,_u),e),n=this.createResult(r,e);return e5e(this,n)&&(vn(this,Uc,n),vn(this,v1,this.options),vn(this,w_,Tt(this,is).state)),n}getCurrentResult(){return Tt(this,Uc)}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,S1).add(e)}getCurrentQuery(){return Tt(this,is)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Tt(this,_u).defaultQueryOptions(e),n=Tt(this,_u).getQueryCache().build(Tt(this,_u),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(e){return Ui(this,Ls,mA).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Tt(this,Uc)))}createResult(e,r){var re;const n=Tt(this,is),i=this.options,o=Tt(this,Uc),c=Tt(this,w_),s=Tt(this,v1),p=e!==n?e.state:Tt(this,Vk),{state:y}=e;let _={...y},T=!1,E;if(r._optimisticResults){const se=this.hasListeners(),ue=!se&&Zee(e,r),_e=se&&Xee(e,n,r,i);(ue||_e)&&(_={..._,...Ipe(y.data,e.options)}),r._optimisticResults==="isRestoring"&&(_.fetchStatus="idle")}let{error:k,errorUpdatedAt:P,status:R}=_;E=_.data;let D=!1;if(r.placeholderData!==void 0&&E===void 0&&R==="pending"){let se;o!=null&&o.isPlaceholderData&&r.placeholderData===(s==null?void 0:s.placeholderData)?(se=o.data,D=!0):se=typeof r.placeholderData=="function"?r.placeholderData((re=Tt(this,w1))==null?void 0:re.state.data,Tt(this,w1)):r.placeholderData,se!==void 0&&(R="success",E=IU(o==null?void 0:o.data,se,r),T=!0)}if(r.select&&E!==void 0&&!D)if(o&&E===(c==null?void 0:c.data)&&r.select===Tt(this,qk))E=Tt(this,b1);else try{vn(this,qk,r.select),E=r.select(E),E=IU(o==null?void 0:o.data,E,r),vn(this,b1,E),vn(this,by,null)}catch(se){vn(this,by,se)}Tt(this,by)&&(k=Tt(this,by),E=Tt(this,b1),P=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:k,errorUpdatedAt:P,failureCount:_.fetchFailureCount,failureReason:_.fetchFailureReason,errorUpdateCount:_.errorUpdateCount,isFetched:_.dataUpdateCount>0||_.errorUpdateCount>0,isFetchedAfterMount:_.dataUpdateCount>p.dataUpdateCount||_.errorUpdateCount>p.errorUpdateCount,isFetching:M,isRefetching:M&&!B,isLoadingError:V&&!W,isPaused:_.fetchStatus==="paused",isPlaceholderData:T,isRefetchError:V&&W,isStale:D9(e,r),refetch:this.refetch,promise:Tt(this,vy),isEnabled:Gd(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const se=we=>{Q.status==="error"?we.reject(Q.error):Q.data!==void 0&&we.resolve(Q.data)},ue=()=>{const we=vn(this,vy,Q.promise=NU());se(we)},_e=Tt(this,vy);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,Uc),r=this.createResult(Tt(this,is),this.options);if(vn(this,w_,Tt(this,is).state),vn(this,v1,this.options),Tt(this,w_).data!==void 0&&vn(this,w1,Tt(this,is)),xD(r,e))return;vn(this,Uc,r);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Tt(this,S1).size)return!0;const c=new Set(o??Tt(this,S1));return this.options.throwOnError&&c.add("error"),Object.keys(Tt(this,Uc)).some(s=>{const f=s;return Tt(this,Uc)[f]!==e[f]&&c.has(f)})};Ui(this,Ls,Rpe).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ui(this,Ls,MU).call(this)}},_u=new WeakMap,is=new WeakMap,Vk=new WeakMap,Uc=new WeakMap,w_=new WeakMap,v1=new WeakMap,vy=new WeakMap,by=new WeakMap,qk=new WeakMap,b1=new WeakMap,w1=new WeakMap,S_=new WeakMap,T_=new WeakMap,wy=new WeakMap,S1=new WeakMap,Ls=new WeakSet,mA=function(e){Ui(this,Ls,BU).call(this);let r=Tt(this,is).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(qc)),r},RU=function(){Ui(this,Ls,OU).call(this);const e=By(this.options.staleTime,Tt(this,is));if($_||Tt(this,Uc).isStale||!kU(e))return;const n=wpe(Tt(this,Uc).dataUpdatedAt,e)+1;vn(this,S_,setTimeout(()=>{Tt(this,Uc).isStale||this.updateResult()},n))},LU=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Tt(this,is)):this.options.refetchInterval)??!1},DU=function(e){Ui(this,Ls,FU).call(this),vn(this,wy,e),!($_||Gd(this.options.enabled,Tt(this,is))===!1||!kU(Tt(this,wy))||Tt(this,wy)===0)&&vn(this,T_,setInterval(()=>{(this.options.refetchIntervalInBackground||L9.isFocused())&&Ui(this,Ls,mA).call(this)},Tt(this,wy)))},MU=function(){Ui(this,Ls,RU).call(this),Ui(this,Ls,DU).call(this,Ui(this,Ls,LU).call(this))},OU=function(){Tt(this,S_)&&(clearTimeout(Tt(this,S_)),vn(this,S_,void 0))},FU=function(){Tt(this,T_)&&(clearInterval(Tt(this,T_)),vn(this,T_,void 0))},BU=function(){const e=Tt(this,_u).getQueryCache().build(Tt(this,_u),this.options);if(e===Tt(this,is))return;const r=Tt(this,is);vn(this,is,e),vn(this,Vk,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Rpe=function(e){cl.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(Tt(this,Uc))}),Tt(this,_u).getQueryCache().notify({query:Tt(this,is),type:"observerResultsUpdated"})})},Due);function JFe(t,e){return Gd(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Zee(t,e){return JFe(t,e)||t.state.data!==void 0&&zU(t,e,e.refetchOnMount)}function zU(t,e,r){if(Gd(e.enabled,t)!==!1&&By(e.staleTime,t)!=="static"){const n=typeof r=="function"?r(t):r;return n==="always"||n!==!1&&D9(t,e)}return!1}function Xee(t,e,r,n){return(t!==e||Gd(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&D9(t,r)}function D9(t,e){return Gd(e.enabled,t)!==!1&&t.isStaleByTime(By(e.staleTime,t))}function e5e(t,e){return!xD(t.getCurrentResult(),e)}var Sy,Ty,vu,_p,Rp,sL,$U,Mue,t5e=(Mue=class extends FS{constructor(r,n){super();Xn(this,Rp);Xn(this,Sy);Xn(this,Ty);Xn(this,vu);Xn(this,_p);vn(this,Sy,r),this.setOptions(n),this.bindMethods(),Ui(this,Rp,sL).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,Sy).defaultMutationOptions(r),xD(this.options,n)||Tt(this,Sy).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Tt(this,vu),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&U_(n.mutationKey)!==U_(this.options.mutationKey)?this.reset():((i=Tt(this,vu))==null?void 0:i.state.status)==="pending"&&Tt(this,vu).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Tt(this,vu))==null||r.removeObserver(this)}onMutationUpdate(r){Ui(this,Rp,sL).call(this),Ui(this,Rp,$U).call(this,r)}getCurrentResult(){return Tt(this,Ty)}reset(){var r;(r=Tt(this,vu))==null||r.removeObserver(this),vn(this,vu,void 0),Ui(this,Rp,sL).call(this),Ui(this,Rp,$U).call(this)}mutate(r,n){var i;return vn(this,_p,n),(i=Tt(this,vu))==null||i.removeObserver(this),vn(this,vu,Tt(this,Sy).getMutationCache().build(Tt(this,Sy),this.options)),Tt(this,vu).addObserver(this),Tt(this,vu).execute(r)}},Sy=new WeakMap,Ty=new WeakMap,vu=new WeakMap,_p=new WeakMap,Rp=new WeakSet,sL=function(){var n;const r=((n=Tt(this,vu))==null?void 0:n.state)??Npe();vn(this,Ty,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},$U=function(r){cl.batch(()=>{var n,i,o,c,s,f,p,y;if(Tt(this,_p)&&this.hasListeners()){const _=Tt(this,Ty).variables,T=Tt(this,Ty).context;(r==null?void 0:r.type)==="success"?((i=(n=Tt(this,_p)).onSuccess)==null||i.call(n,r.data,_,T),(c=(o=Tt(this,_p)).onSettled)==null||c.call(o,r.data,null,_,T)):(r==null?void 0:r.type)==="error"&&((f=(s=Tt(this,_p)).onError)==null||f.call(s,r.error,_,T),(y=(p=Tt(this,_p)).onSettled)==null||y.call(p,void 0,r.error,_,T))}this.listeners.forEach(_=>{_(Tt(this,Ty))})})},Mue),Lpe=I.createContext(void 0),Nr=t=>{const e=I.useContext(Lpe);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},r5e=({client:t,children:e})=>(I.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),a.jsx(Lpe.Provider,{value:t,children:e})),Dpe=I.createContext(!1),n5e=()=>I.useContext(Dpe);Dpe.Provider;function i5e(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var s5e=I.createContext(i5e()),a5e=()=>I.useContext(s5e),o5e=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},l5e=t=>{I.useEffect(()=>{t.clearReset()},[t])},c5e=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||Epe(r,[t.error,n])),u5e=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))}},d5e=(t,e)=>t.isLoading&&t.isFetching&&!e,h5e=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Qee=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function f5e(t,e,r){var _,T,E,k,P;const n=n5e(),i=a5e(),o=Nr(),c=o.defaultQueryOptions(t);(T=(_=o.getDefaultOptions().queries)==null?void 0:_._experimental_beforeQuery)==null||T.call(_,c),c._optimisticResults=n?"isRestoring":"optimistic",u5e(c),o5e(c,i),l5e(i);const s=!o.getQueryCache().get(c.queryHash),[f]=I.useState(()=>new e(o,c)),p=f.getOptimisticResult(c),y=!n&&t.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(R=>{const D=y?f.subscribe(cl.batchCalls(R)):qc;return f.updateResult(),D},[f,y]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),I.useEffect(()=>{f.setOptions(c)},[c,f]),h5e(c,p))throw Qee(c,f,i);if(c5e({result:p,errorResetBoundary:i,throwOnError:c.throwOnError,query:o.getQueryCache().get(c.queryHash),suspense:c.suspense}))throw p.error;if((k=(E=o.getDefaultOptions().queries)==null?void 0:E._experimental_afterQuery)==null||k.call(E,c,p),c.experimental_prefetchInRender&&!$_&&d5e(p,n)){const R=s?Qee(c,f,i):(P=o.getQueryCache().get(c.queryHash))==null?void 0:P.promise;R==null||R.catch(qc).finally(()=>{f.updateResult()})}return c.notifyOnChangeProps?p:f.trackResult(p)}function gr(t,e){return f5e(t,QFe)}function kr(t,e){const r=Nr(),[n]=I.useState(()=>new t5e(r,t));I.useEffect(()=>{n.setOptions(t)},[n,t]);const i=I.useSyncExternalStore(I.useCallback(c=>n.subscribe(cl.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),o=I.useCallback((c,s)=>{n.mutate(c,s).catch(qc)},[n]);if(i.error&&Epe(n.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,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 Ij(){return Ij=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function Mpe(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function p5e(){return Math.random().toString(36).substr(2,8)}function ete(t,e){return{usr:t.state,key:t.key,idx:e}}function UU(t,e,r,n){return r===void 0&&(r=null),Ij({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?BS(e):e,{state:r,key:e&&e.key||n||p5e()})}function vD(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 BS(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 g5e(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,c=i.history,s=jy.Pop,f=null,p=y();p==null&&(p=0,c.replaceState(Ij({},c.state,{idx:p}),""));function y(){return(c.state||{idx:null}).idx}function _(){s=jy.Pop;let R=y(),D=R==null?null:R-p;p=R,f&&f({action:s,location:P.location,delta:D})}function T(R,D){s=jy.Push;let M=UU(P.location,R,D);p=y()+1;let B=ete(M,p),V=P.createHref(M);try{c.pushState(B,"",V)}catch(G){if(G instanceof DOMException&&G.name==="DataCloneError")throw G;i.location.assign(V)}o&&f&&f({action:s,location:P.location,delta:1})}function E(R,D){s=jy.Replace;let M=UU(P.location,R,D);p=y();let B=ete(M,p),V=P.createHref(M);c.replaceState(B,"",V),o&&f&&f({action:s,location:P.location,delta:0})}function k(R){let D=i.location.origin!=="null"?i.location.origin:i.location.href,M=typeof R=="string"?R:vD(R);return M=M.replace(/ $/,"%20"),ro(D,"No window.location.(origin|href) available to create URL for href: "+M),new URL(M,D)}let P={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(Jee,_),f=R,()=>{i.removeEventListener(Jee,_),f=null}},createHref(R){return e(i,R)},createURL:k,encodeLocation(R){let D=k(R);return{pathname:D.pathname,search:D.search,hash:D.hash}},push:T,replace:E,go(R){return c.go(R)}};return P}var tte;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(tte||(tte={}));function y5e(t,e,r){return r===void 0&&(r="/"),x5e(t,e,r,!1)}function x5e(t,e,r,n){let i=typeof e=="string"?BS(e):e,o=M1(i.pathname||"/",r);if(o==null)return null;let c=Ope(t);_5e(c);let s=null;for(let f=0;s==null&&f{let f={relativePath:s===void 0?o.path||"":s,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};f.relativePath.startsWith("/")&&(ro(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 p=zy([n,f.relativePath]),y=r.concat(f);o.children&&o.children.length>0&&(ro(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+p+'".')),Ope(o.children,e,y,p)),!(o.path==null&&!o.index)&&e.push({path:p,score:A5e(p,o.index),routesMeta:y})};return t.forEach((o,c)=>{var s;if(o.path===""||!((s=o.path)!=null&&s.includes("?")))i(o,c);else for(let f of Fpe(o.path))i(o,c,f)}),e}function Fpe(t){let e=t.split("/");if(e.length===0)return[];let[r,...n]=e,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(n.length===0)return i?[o,""]:[o];let c=Fpe(n.join("/")),s=[];return s.push(...c.map(f=>f===""?o:[o,f].join("/"))),i&&s.push(...c),s.map(f=>t.startsWith("/")&&f===""?"/":f)}function _5e(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:j5e(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const v5e=/^:[\w-]+$/,b5e=3,w5e=2,S5e=1,T5e=10,E5e=-2,rte=t=>t==="*";function A5e(t,e){let r=t.split("/"),n=r.length;return r.some(rte)&&(n+=E5e),e&&(n+=w5e),r.filter(i=>!rte(i)).reduce((i,o)=>i+(v5e.test(o)?b5e:o===""?S5e:T5e),n)}function j5e(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 k5e(t,e,r){let{routesMeta:n}=t,i={},o="/",c=[];for(let s=0;s{let{paramName:T,isOptional:E}=y;if(T==="*"){let P=s[_]||"";c=o.slice(0,o.length-P.length).replace(/(.)\/+$/,"$1")}const k=s[_];return E&&!k?p[T]=void 0:p[T]=(k||"").replace(/%2F/g,"/"),p},{}),pathname:o,pathnameBase:c,pattern:t}}function C5e(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),Mpe(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 I5e(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Mpe(!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 M1(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 N5e(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?BS(t):t;return{pathname:r?r.startsWith("/")?r:P5e(r,e):e,search:D5e(n),hash:M5e(i)}}function P5e(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 ez(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 R5e(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function M9(t,e){let r=R5e(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function O9(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=BS(t):(i=Ij({},t),ro(!i.pathname||!i.pathname.includes("?"),ez("?","pathname","search",i)),ro(!i.pathname||!i.pathname.includes("#"),ez("#","pathname","hash",i)),ro(!i.search||!i.search.includes("#"),ez("#","search","hash",i)));let o=t===""||i.pathname==="",c=o?"/":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=N5e(i,s),p=c&&c!=="/"&&c.endsWith("/"),y=(o||c===".")&&r.endsWith("/");return!f.pathname.endsWith("/")&&(p||y)&&(f.pathname+="/"),f}const zy=t=>t.join("/").replace(/\/\/+/g,"/"),L5e=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),D5e=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,M5e=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function O5e(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const Bpe=["post","put","patch","delete"];new Set(Bpe);const F5e=["get",...Bpe];new Set(F5e);/** * 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 Nj(){return Nj=Object.assign?Object.assign.bind():function(t){for(var e=1;e{s.current=!0}),I.useCallback(function(p,y){if(y===void 0&&(y={}),!s.current)return;if(typeof p=="number"){n.go(p);return}let _=O9(p,JSON.parse(c),o,y.relative==="path");t==null&&e!=="/"&&(_.pathname=_.pathname==="/"?e:zy([e,_.pathname])),(y.replace?n.replace:n.push)(_,y.state,y)},[e,n,c,o,t])}const $5e=I.createContext(null);function U5e(t){let e=I.useContext(vm).outlet;return e&&I.createElement($5e.Provider,{value:t},e)}function bm(){let{matches:t}=I.useContext(vm),e=t[t.length-1];return e?e.params:{}}function QO(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=I.useContext(Xp),{matches:i}=I.useContext(vm),{pathname:o}=Bi(),c=JSON.stringify(M9(i,n.v7_relativeSplatPath));return I.useMemo(()=>O9(t,JSON.parse(c),o,r==="path"),[t,c,o,r])}function V5e(t,e){return q5e(t,e)}function q5e(t,e,r,n){zS()||ro(!1);let{navigator:i}=I.useContext(Xp),{matches:o}=I.useContext(vm),c=o[o.length-1],s=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let p=Bi(),y;if(e){var _;let R=typeof e=="string"?BS(e):e;f==="/"||(_=R.pathname)!=null&&_.startsWith(f)||ro(!1),y=R}else y=p;let T=y.pathname||"/",E=T;if(f!=="/"){let R=f.replace(/^\//,"").split("/");E="/"+T.replace(/^\//,"").split("/").slice(R.length).join("/")}let k=y5e(t,{pathname:E}),P=Y5e(k&&k.map(R=>Object.assign({},R,{params:Object.assign({},s,R.params),pathname:zy([f,i.encodeLocation?i.encodeLocation(R.pathname).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?f:zy([f,i.encodeLocation?i.encodeLocation(R.pathnameBase).pathname:R.pathnameBase])})),o,r,n);return e&&P?I.createElement(XO.Provider,{value:{location:Nj({pathname:"/",search:"",hash:"",state:null,key:"default"},y),navigationType:jy.Pop}},P):P}function G5e(){let t=J5e(),e=O5e(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 I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},e),r?I.createElement("pre",{style:i},r):null,null)}const H5e=I.createElement(G5e,null);class W5e extends I.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?I.createElement(vm.Provider,{value:this.props.routeContext},I.createElement($pe.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function K5e(t){let{routeContext:e,match:r,children:n}=t,i=I.useContext(ZO);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),I.createElement(vm.Provider,{value:e},n)}function Y5e(t,e,r,n){var i;if(e===void 0&&(e=[]),r===void 0&&(r=null),n===void 0&&(n=null),t==null){var o;if(!r)return null;if(r.errors)t=r.matches;else if((o=n)!=null&&o.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 y=c.findIndex(_=>_.route.id&&(s==null?void 0:s[_.route.id])!==void 0);y>=0||ro(!1),c=c.slice(0,Math.min(c.length,y+1))}let f=!1,p=-1;if(r&&n&&n.v7_partialHydration)for(let y=0;y=0?c=c.slice(0,p+1):c=[c[0]];break}}}return c.reduceRight((y,_,T)=>{let E,k=!1,P=null,R=null;r&&(E=s&&_.route.id?s[_.route.id]:void 0,P=_.route.errorElement||H5e,f&&(p<0&&T===0?(k=!0,R=null):p===T&&(k=!0,R=_.route.hydrateFallbackElement||null)));let D=e.concat(c.slice(0,T+1)),M=()=>{let B;return E?B=P:k?B=R:_.route.Component?B=I.createElement(_.route.Component,null):_.route.element?B=_.route.element:B=y,I.createElement(K5e,{match:_,routeContext:{outlet:y,matches:D,isDataRoute:r!=null},children:B})};return r&&(_.route.ErrorBoundary||_.route.errorElement||T===0)?I.createElement(W5e,{location:r.location,revalidation:r.revalidation,component:P,error:E,children:M(),routeContext:{outlet:null,matches:D,isDataRoute:!0}}):M()},null)}var Vpe=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(Vpe||{}),wD=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}(wD||{});function Z5e(t){let e=I.useContext(ZO);return e||ro(!1),e}function X5e(t){let e=I.useContext(zpe);return e||ro(!1),e}function Q5e(t){let e=I.useContext(vm);return e||ro(!1),e}function qpe(t){let e=Q5e(),r=e.matches[e.matches.length-1];return r.route.id||ro(!1),r.route.id}function J5e(){var t;let e=I.useContext($pe),r=X5e(wD.UseRouteError),n=qpe(wD.UseRouteError);return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function e4e(){let{router:t}=Z5e(Vpe.UseNavigateStable),e=qpe(wD.UseNavigateStable),r=I.useRef(!1);return Upe(()=>{r.current=!0}),I.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,Nj({fromRouteId:e},o)))},[t,e])}function t4e(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function li(t){let{to:e,replace:r,state:n,relative:i}=t;zS()||ro(!1);let{future:o,static:c}=I.useContext(Xp),{matches:s}=I.useContext(vm),{pathname:f}=Bi(),p=Gs(),y=O9(e,M9(s,o.v7_relativeSplatPath),f,i==="path"),_=JSON.stringify(y);return I.useEffect(()=>p(JSON.parse(_),{replace:r,state:n,relative:i}),[p,_,i,r,n]),null}function TVt(t){return U5e(t.context)}function Te(t){ro(!1)}function r4e(t){let{basename:e="/",children:r=null,location:n,navigationType:i=jy.Pop,navigator:o,static:c=!1,future:s}=t;zS()&&ro(!1);let f=e.replace(/^\/*/,"/"),p=I.useMemo(()=>({basename:f,navigator:o,static:c,future:Nj({v7_relativeSplatPath:!1},s)}),[f,s,o,c]);typeof n=="string"&&(n=BS(n));let{pathname:y="/",search:_="",hash:T="",state:E=null,key:k="default"}=n,P=I.useMemo(()=>{let R=M1(y,f);return R==null?null:{location:{pathname:R,search:_,hash:T,state:E,key:k},navigationType:i}},[f,y,_,T,E,k,i]);return P==null?null:I.createElement(Xp.Provider,{value:p},I.createElement(XO.Provider,{children:r,value:P}))}function l_(t){let{children:e,location:r}=t;return V5e(VU(e),r)}new Promise(()=>{});function VU(t,e){e===void 0&&(e=[]);let r=[];return I.Children.forEach(t,(n,i)=>{if(!I.isValidElement(n))return;let o=[...e,i];if(n.type===I.Fragment){r.push.apply(r,VU(n.props.children,o));return}n.type!==Te&&ro(!1),!n.props.index||!n.props.children||ro(!1);let c={id:n.props.id||o.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=VU(n.props.children,o)),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 SD(){return SD=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function n4e(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function i4e(t,e){return t.button===0&&(!e||e==="_self")&&!n4e(t)}function qU(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 s4e(t,e){let r=qU(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(o=>{r.append(i,o)})}),r}const a4e=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],o4e=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],l4e="6";try{window.__reactRouterVersion=l4e}catch{}const c4e=I.createContext({isTransitioning:!1}),u4e="startTransition",nte=aG[u4e];function d4e(t){let{basename:e,children:r,future:n,window:i}=t,o=I.useRef();o.current==null&&(o.current=m5e({window:i,v5Compat:!0}));let c=o.current,[s,f]=I.useState({action:c.action,location:c.location}),{v7_startTransition:p}=n||{},y=I.useCallback(_=>{p&&nte?nte(()=>f(_)):f(_)},[f,p]);return I.useLayoutEffect(()=>c.listen(y),[c,y]),I.useEffect(()=>t4e(n),[n]),I.createElement(r4e,{basename:e,children:r,location:s.location,navigationType:s.action,navigator:c,future:n})}const h4e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",f4e=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,mn=I.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:o,replace:c,state:s,target:f,to:p,preventScrollReset:y,viewTransition:_}=e,T=Gpe(e,a4e),{basename:E}=I.useContext(Xp),k,P=!1;if(typeof p=="string"&&f4e.test(p)&&(k=p,h4e))try{let B=new URL(window.location.href),V=p.startsWith("//")?new URL(B.protocol+p):new URL(p),G=M1(V.pathname,E);V.origin===B.origin&&G!=null?p=G+V.search+V.hash:P=!0}catch{}let R=B5e(p,{relative:i}),D=p4e(p,{replace:c,state:s,target:f,preventScrollReset:y,relative:i,viewTransition:_});function M(B){n&&n(B),B.defaultPrevented||D(B)}return I.createElement("a",SD({},T,{href:k||R,onClick:P||o?n:M,ref:r,target:f}))}),EVt=I.forwardRef(function(e,r){let{"aria-current":n="page",caseSensitive:i=!1,className:o="",end:c=!1,style:s,to:f,viewTransition:p,children:y}=e,_=Gpe(e,o4e),T=QO(f,{relative:_.relative}),E=Bi(),k=I.useContext(zpe),{navigator:P,basename:R}=I.useContext(Xp),D=k!=null&&g4e(T)&&p===!0,M=P.encodeLocation?P.encodeLocation(T).pathname:T.pathname,B=E.pathname,V=k&&k.navigation&&k.navigation.location?k.navigation.location.pathname:null;i||(B=B.toLowerCase(),V=V?V.toLowerCase():null,M=M.toLowerCase()),V&&R&&(V=M1(V,R)||V);const G=M!=="/"&&M.endsWith("/")?M.length-1:M.length;let W=B===M||!c&&B.startsWith(M)&&B.charAt(G)==="/",Z=V!=null&&(V===M||!c&&V.startsWith(M)&&V.charAt(M.length)==="/"),Q={isActive:W,isPending:Z,isTransitioning:D},re=W?n:void 0,se;typeof o=="function"?se=o(Q):se=[o,W?"active":null,Z?"pending":null,D?"transitioning":null].filter(Boolean).join(" ");let ue=typeof s=="function"?s(Q):s;return I.createElement(mn,SD({},_,{"aria-current":re,className:se,ref:r,style:ue,to:f,viewTransition:p}),typeof y=="function"?y(Q):y)});var GU;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(GU||(GU={}));var ite;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(ite||(ite={}));function m4e(t){let e=I.useContext(ZO);return e||ro(!1),e}function p4e(t,e){let{target:r,replace:n,state:i,preventScrollReset:o,relative:c,viewTransition:s}=e===void 0?{}:e,f=Gs(),p=Bi(),y=QO(t,{relative:c});return I.useCallback(_=>{if(i4e(_,r)){_.preventDefault();let T=n!==void 0?n:vD(p)===vD(y);f(t,{replace:T,state:i,preventScrollReset:o,relative:c,viewTransition:s})}},[p,f,y,n,i,r,t,o,c,s])}function px(t){let e=I.useRef(qU(t)),r=I.useRef(!1),n=Bi(),i=I.useMemo(()=>s4e(n.search,r.current?null:e.current),[n.search]),o=Gs(),c=I.useCallback((s,f)=>{const p=qU(typeof s=="function"?s(i):s);r.current=!0,o("?"+p,f)},[o,i]);return[i,c]}function g4e(t,e){e===void 0&&(e={});let r=I.useContext(c4e);r==null&&ro(!1);let{basename:n}=m4e(GU.useViewTransitionState),i=QO(t,{relative:e.relative});if(!r.isTransitioning)return!1;let o=M1(r.currentLocation.pathname,n)||r.currentLocation.pathname,c=M1(r.nextLocation.pathname,n)||r.nextLocation.pathname;return bD(i.pathname,c)!=null||bD(i.pathname,o)!=null}var y4e=typeof Element<"u",x4e=typeof Map=="function",_4e=typeof Set=="function",v4e=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function aL(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(!aL(t[n],e[n]))return!1;return!0}var o;if(x4e&&t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(o=t.entries();!(n=o.next()).done;)if(!e.has(n.value[0]))return!1;for(o=t.entries();!(n=o.next()).done;)if(!aL(n.value[1],e.get(n.value[0])))return!1;return!0}if(_4e&&t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(o=t.entries();!(n=o.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(v4e&&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(y4e&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!aL(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var b4e=function(e,r){try{return aL(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 w4e=ds(b4e);var S4e=function(t,e,r,n,i,o,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 p=[r,n,i,o,c,s],y=0;f=new Error(e.replace(/%s/g,function(){return p[y++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}},T4e=S4e;const ste=ds(T4e);var E4e=function(e,r,n,i){var o=n?n.call(i,e,r):void 0;if(o!==void 0)return!!o;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),p=0;p(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))(Hpe||{}),tz={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"]}},ate=Object.values(Hpe),F9={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},j4e=Object.entries(F9).reduce((t,[e,r])=>(t[r]=e,t),{}),Xh="data-rh",Qw={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Jw=(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},k4e=t=>{let e=Jw(t,"title");const r=Jw(t,Qw.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=Jw(t,Qw.DEFAULT_TITLE);return e||n||void 0},C4e=t=>Jw(t,Qw.ON_CHANGE_CLIENT_STATE)||(()=>{}),rz=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),I4e=(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 o=0;oconsole&&typeof console.warn=="function"&&console.warn(t),M2=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&N4e(`Helmet: ${t} should be of type "Array". Instead found type "${typeof i[t]}"`),!1)).map(i=>i[t]).reverse().reduce((i,o)=>{const c={};o.filter(f=>{let p;const y=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:I4e(["href"],t),bodyAttributes:rz("bodyAttributes",t),defer:Jw(t,Qw.DEFER),encode:Jw(t,Qw.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:rz("htmlAttributes",t),linkTags:M2("link",["rel","href"],t),metaTags:M2("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:M2("noscript",["innerHTML"],t),onChangeClientState:C4e(t),scriptTags:M2("script",["src","innerHTML"],t),styleTags:M2("style",["cssText"],t),title:k4e(t),titleAttributes:rz("titleAttributes",t),prioritizeSeoTags:P4e(t,Qw.PRIORITIZE_SEO_TAGS)}),Wpe=t=>Array.isArray(t)?t.join(""):t,L4e=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(L4e(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},ote=(t,e)=>({...t,[e]:void 0}),D4e=["noscript","script","style"],HU=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Kpe=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),M4e=(t,e,r,n)=>{const i=Kpe(r),o=Wpe(e);return i?`<${t} ${Xh}="true" ${i}>${HU(o,n)}`:`<${t} ${Xh}="true">${HU(o,n)}`},O4e=(t,e,r=!0)=>e.reduce((n,i)=>{const o=i,c=Object.keys(o).filter(p=>!(p==="innerHTML"||p==="cssText")).reduce((p,y)=>{const _=typeof o[y]>"u"?y:`${y}="${HU(o[y],r)}"`;return p?`${p} ${_}`:_},""),s=o.innerHTML||o.cssText||"",f=D4e.indexOf(t)===-1;return`${n}<${t} ${Xh}="true" ${c}${f?"/>":`>${s}`}`},""),Ype=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=F9[n];return r[i||n]=t[n],r},e),F4e=(t,e,r)=>{const n={key:e,[Xh]:!0},i=Ype(r,n);return[Xe.createElement("title",i,e)]},oL=(t,e)=>e.map((r,n)=>{const i={key:n,[Xh]:!0};return Object.keys(r).forEach(o=>{const s=F9[o]||o;if(s==="innerHTML"||s==="cssText"){const f=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:f}}else i[s]=r[o]}),Xe.createElement(t,i)}),Vd=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>F4e(t,e.title,e.titleAttributes),toString:()=>M4e(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Ype(e),toString:()=>Kpe(e)};default:return{toComponent:()=>oL(t,e),toString:()=>O4e(t,e,r)}}},B4e=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=nz(t,tz.meta),o=nz(e,tz.link),c=nz(r,tz.script);return{priorityMethods:{toComponent:()=>[...oL("meta",i.priority),...oL("link",o.priority),...oL("script",c.priority)],toString:()=>`${Vd("meta",i.priority,n)} ${Vd("link",o.priority,n)} ${Vd("script",c.priority,n)}`},metaTags:i.default,linkTags:o.default,scriptTags:c.default}},z4e=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:o,styleTags:c,title:s="",titleAttributes:f,prioritizeSeoTags:p}=t;let{linkTags:y,metaTags:_,scriptTags:T}=t,E={toComponent:()=>{},toString:()=>""};return p&&({priorityMethods:E,linkTags:y,metaTags:_,scriptTags:T}=B4e(t)),{priority:E,base:Vd("base",e,n),bodyAttributes:Vd("bodyAttributes",r,n),htmlAttributes:Vd("htmlAttributes",i,n),link:Vd("link",y,n),meta:Vd("meta",_,n),noscript:Vd("noscript",o,n),script:Vd("script",T,n),style:Vd("style",c,n),title:Vd("title",{title:s,titleAttributes:f},n)}},WU=z4e,MP=[],Zpe=!!(typeof window<"u"&&window.document&&window.document.createElement),KU=class{constructor(t,e){un(this,"instances",[]);un(this,"canUseDOM",Zpe);un(this,"context");un(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?MP:this.instances,add:t=>{(this.canUseDOM?MP:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?MP:this.instances).indexOf(t);(this.canUseDOM?MP:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=WU({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},$4e={},Xpe=Xe.createContext($4e),E_,Qpe=(E_=class extends I.Component{constructor(r){super(r);un(this,"helmetData");this.helmetData=new KU(this.props.context||{},E_.canUseDOM)}render(){return Xe.createElement(Xpe.Provider,{value:this.helmetData.value},this.props.children)}},un(E_,"canUseDOM",Zpe),E_),Kb=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${Xh}]`),i=[].slice.call(n),o=[];let c;return e&&e.length&&e.forEach(s=>{const f=document.createElement(t);for(const p in s)if(Object.prototype.hasOwnProperty.call(s,p))if(p==="innerHTML")f.innerHTML=s.innerHTML;else if(p==="cssText")f.styleSheet?f.styleSheet.cssText=s.cssText:f.appendChild(document.createTextNode(s.cssText));else{const y=p,_=typeof s[y]>"u"?"":s[y];f.setAttribute(p,_)}f.setAttribute(Xh,"true"),i.some((p,y)=>(c=y,f.isEqualNode(p)))?i.splice(c,1):o.push(f)}),i.forEach(s=>{var f;return(f=s.parentNode)==null?void 0:f.removeChild(s)}),o.forEach(s=>r.appendChild(s)),{oldTags:i,newTags:o}},YU=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(Xh),i=n?n.split(","):[],o=[...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 p=o.indexOf(s);p!==-1&&o.splice(p,1)}for(let s=o.length-1;s>=0;s-=1)r.removeAttribute(o[s]);i.length===o.length?r.removeAttribute(Xh):r.getAttribute(Xh)!==c.join(",")&&r.setAttribute(Xh,c.join(","))},U4e=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=Wpe(t)),YU("title",e)},lte=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:o,metaTags:c,noscriptTags:s,onChangeClientState:f,scriptTags:p,styleTags:y,title:_,titleAttributes:T}=t;YU("body",n),YU("html",i),U4e(_,T);const E={baseTag:Kb("base",r),linkTags:Kb("link",o),metaTags:Kb("meta",c),noscriptTags:Kb("noscript",s),scriptTags:Kb("script",p),styleTags:Kb("style",y)},k={},P={};Object.keys(E).forEach(R=>{const{newTags:D,oldTags:M}=E[R];D.length&&(k[R]=D),M.length&&(P[R]=E[R].oldTags)}),e&&e(),f(t,k,P)},O2=null,V4e=t=>{O2&&cancelAnimationFrame(O2),t.defer?O2=requestAnimationFrame(()=>{lte(t,()=>{O2=null})}):(lte(t),O2=null)},q4e=V4e,cte=class extends I.Component{constructor(){super(...arguments);un(this,"rendered",!1)}shouldComponentUpdate(e){return!A4e(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=R4e(e.get().map(o=>{const c={...o.props};return delete c.context,c}));Qpe.canUseDOM?q4e(i):WU&&(n=WU(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}},m6,Wo=(m6=class extends I.Component{shouldComponentUpdate(t){return!w4e(ote(this.props,"helmetData"),ote(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 ste(ate.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 ${ate.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),ste(!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,...o}=n.props,c=Object.keys(o).reduce((f,p)=>(f[j4e[p]||p]=o[p],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 KU)){const i=n;n=new KU(i.context,!0),delete r.helmetData}return n?Xe.createElement(cte,{...r,context:n.value}):Xe.createElement(Xpe.Consumer,null,i=>Xe.createElement(cte,{...r,context:i}))}},un(m6,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),m6);const G4e=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(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 B9 extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class H4e extends B9{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class W4e extends B9{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class K4e extends B9{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var ZU;(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"})(ZU||(ZU={}));var Y4e=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};class Z4e{constructor(e,{headers:r={},customFetch:n,region:i=ZU.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=G4e(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return Y4e(this,void 0,void 0,function*(){try{const{headers:i,method:o,body:c}=r;let s={},{region:f}=r;f||(f=this.region),f&&f!=="any"&&(s["x-region"]=f);let p;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",p=c):typeof c=="string"?(s["Content-Type"]="text/plain",p=c):typeof FormData<"u"&&c instanceof FormData?p=c:(s["Content-Type"]="application/json",p=JSON.stringify(c)));const y=yield this.fetch(`${this.url}/${e}`,{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},s),this.headers),i),body:p}).catch(k=>{throw new H4e(k)}),_=y.headers.get("x-relay-error");if(_&&_==="true")throw new W4e(y);if(!y.ok)throw new K4e(y);let T=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return T==="application/json"?E=yield y.json():T==="application/octet-stream"?E=yield y.blob():T==="text/event-stream"?E=y:T==="multipart/form-data"?E=yield y.formData():E=yield y.text(),{data:E,error:null}}catch(i){return{data:null,error:i}}})}}var Tu={},z9={},JO={},cC={},e3={},t3={},X4e=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")},O1=X4e();const Q4e=O1.fetch,Jpe=O1.fetch.bind(O1),ege=O1.Headers,J4e=O1.Request,eBe=O1.Response,$S=Object.freeze(Object.defineProperty({__proto__:null,Headers:ege,Request:J4e,Response:eBe,default:Jpe,fetch:Q4e},Symbol.toStringTag,{value:"Module"})),tBe=pNe($S);var r3={};Object.defineProperty(r3,"__esModule",{value:!0});let rBe=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};r3.default=rBe;var tge=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(t3,"__esModule",{value:!0});const nBe=tge(tBe),iBe=tge(r3);let sBe=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=nBe.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 o=>{var c,s,f;let p=null,y=null,_=null,T=o.status,E=o.statusText;if(o.ok){if(this.method!=="HEAD"){const D=await o.text();D===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?y=D:y=JSON.parse(D))}const P=(c=this.headers.Prefer)===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),R=(s=o.headers.get("content-range"))===null||s===void 0?void 0:s.split("/");P&&R&&R.length>1&&(_=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(y)&&(y.length>1?(p={code:"PGRST116",details:`Results contain ${y.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},y=null,_=null,T=406,E="Not Acceptable"):y.length===1?y=y[0]:y=null)}else{const P=await o.text();try{p=JSON.parse(P),Array.isArray(p)&&o.status===404&&(y=[],p=null,T=200,E="OK")}catch{o.status===404&&P===""?(T=204,E="No Content"):p={message:P}}if(p&&this.isMaybeSingle&&(!((f=p==null?void 0:p.details)===null||f===void 0)&&f.includes("0 rows"))&&(p=null,T=200,E="OK"),p&&this.shouldThrowOnError)throw new iBe.default(p)}return{error:p,data:y,count:_,status:T,statusText:E}});return this.shouldThrowOnError||(i=i.catch(o=>{var c,s,f;return{error:{message:`${(c=o==null?void 0:o.name)!==null&&c!==void 0?c:"FetchError"}: ${o==null?void 0:o.message}`,details:`${(s=o==null?void 0:o.stack)!==null&&s!==void 0?s:""}`,hint:"",code:`${(f=o==null?void 0:o.code)!==null&&f!==void 0?f:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,r)}returns(){return this}overrideTypes(){return this}};t3.default=sBe;var aBe=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e3,"__esModule",{value:!0});const oBe=aBe(t3);let lBe=class extends oBe.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:o=i}={}){const c=o?`${o}.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 o=typeof i>"u"?"offset":`${i}.offset`,c=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(o,`${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:o=!1,format:c="text"}={}){var s;const f=[e?"analyze":null,r?"verbose":null,n?"settings":null,i?"buffers":null,o?"wal":null].filter(Boolean).join("|"),p=(s=this.headers.Accept)!==null&&s!==void 0?s:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${p}"; 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}};e3.default=lBe;var cBe=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cC,"__esModule",{value:!0});const uBe=cBe(e3);let dBe=class extends uBe.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 o="";i==="plain"?o="pl":i==="phrase"?o="ph":i==="websearch"&&(o="w");const c=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${o}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}};cC.default=dBe;var hBe=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(JO,"__esModule",{value:!0});const F2=hBe(cC);let fBe=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 o=!1;const c=(e??"*").split("").map(s=>/\s/.test(s)&&!o?"":(s==='"'&&(o=!o),s)).join("");return this.url.searchParams.set("select",c),n&&(this.headers.Prefer=`count=${n}`),new F2.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",o=[];if(this.headers.Prefer&&o.push(this.headers.Prefer),r&&o.push(`count=${r}`),n||o.push("missing=default"),this.headers.Prefer=o.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 F2.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:o=!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}`),o||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){const f=e.reduce((p,y)=>p.concat(Object.keys(y)),[]);if(f.length>0){const p=[...new Set(f)].map(y=>`"${y}"`);this.url.searchParams.set("columns",p.join(","))}}return new F2.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 F2.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 F2.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};JO.default=fBe;var n3={},i3={};Object.defineProperty(i3,"__esModule",{value:!0});i3.version=void 0;i3.version="0.0.0-automated";Object.defineProperty(n3,"__esModule",{value:!0});n3.DEFAULT_HEADERS=void 0;const mBe=i3;n3.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${mBe.version}`};var rge=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(z9,"__esModule",{value:!0});const pBe=rge(JO),gBe=rge(cC),yBe=n3;let xBe=class nge{constructor(e,{headers:r={},schema:n,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},yBe.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=i}from(e){const r=new URL(`${this.url}/${e}`);return new pBe.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new nge(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:i=!1,count:o}={}){let c;const s=new URL(`${this.url}/rpc/${e}`);let f;n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([y,_])=>_!==void 0).map(([y,_])=>[y,Array.isArray(_)?`{${_.join(",")}}`:`${_}`]).forEach(([y,_])=>{s.searchParams.append(y,_)})):(c="POST",f=r);const p=Object.assign({},this.headers);return o&&(p.Prefer=`count=${o}`),new gBe.default({method:c,url:s,headers:p,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}};z9.default=xBe;var US=Ql&&Ql.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tu,"__esModule",{value:!0});Tu.PostgrestError=Tu.PostgrestBuilder=Tu.PostgrestTransformBuilder=Tu.PostgrestFilterBuilder=Tu.PostgrestQueryBuilder=Tu.PostgrestClient=void 0;const ige=US(z9);Tu.PostgrestClient=ige.default;const sge=US(JO);Tu.PostgrestQueryBuilder=sge.default;const age=US(cC);Tu.PostgrestFilterBuilder=age.default;const oge=US(e3);Tu.PostgrestTransformBuilder=oge.default;const lge=US(t3);Tu.PostgrestBuilder=lge.default;const cge=US(r3);Tu.PostgrestError=cge.default;var _Be=Tu.default={PostgrestClient:ige.default,PostgrestQueryBuilder:sge.default,PostgrestFilterBuilder:age.default,PostgrestTransformBuilder:oge.default,PostgrestBuilder:lge.default,PostgrestError:cge.default};const{PostgrestClient:vBe,PostgrestQueryBuilder:NVt,PostgrestFilterBuilder:PVt,PostgrestTransformBuilder:RVt,PostgrestBuilder:LVt,PostgrestError:DVt}=_Be;let XU;typeof window>"u"?XU=require("ws"):XU=window.WebSocket;const bBe=XU,wBe="2.11.10",SBe={"X-Client-Info":`realtime-js/${wBe}`},TBe="1.0.0",uge=1e4,EBe=1e3;var e1;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(e1||(e1={}));var zc;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(zc||(zc={}));var Uh;(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"})(Uh||(Uh={}));var QU;(function(t){t.websocket="websocket"})(QU||(QU={}));var n_;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(n_||(n_={}));class ABe{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),o=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+o));c=c+o;const p=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:s,event:f,payload:p}}}class dge{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 ma;(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"})(ma||(ma={}));const ute=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((o,c)=>(o[c]=jBe(c,t,e,i),o),{})},jBe=(t,e,r,n)=>{const i=e.find(s=>s.name===t),o=i==null?void 0:i.type,c=r[t];return o&&!n.includes(o)?hge(o,c):JU(c)},hge=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return NBe(e,r)}switch(t){case ma.bool:return kBe(e);case ma.float4:case ma.float8:case ma.int2:case ma.int4:case ma.int8:case ma.numeric:case ma.oid:return CBe(e);case ma.json:case ma.jsonb:return IBe(e);case ma.timestamp:return PBe(e);case ma.abstime:case ma.date:case ma.daterange:case ma.int4range:case ma.int8range:case ma.money:case ma.reltime:case ma.text:case ma.time:case ma.timestamptz:case ma.timetz:case ma.tsrange:case ma.tstzrange:return JU(e);default:return JU(e)}},JU=t=>t,kBe=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},CBe=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},IBe=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},NBe=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let o;const c=t.slice(1,r);try{o=JSON.parse("["+c+"]")}catch{o=c?c.split(","):[]}return o.map(s=>hge(e,s))}return t},PBe=t=>typeof t=="string"?t.replace(" ","T"):t,fge=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class iz{constructor(e,r,n={},i=uge){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 dte;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(dte||(dte={}));class MA{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:o,onLeave:c,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=MA.syncState(this.state,i,o,c),this.pendingDiffs.forEach(f=>{this.state=MA.syncDiff(this.state,f,o,c)}),this.pendingDiffs=[],s()}),this.channel._on(n.diff,{},i=>{const{onJoin:o,onLeave:c,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=MA.syncDiff(this.state,i,o,c),s())}),this.onJoin((i,o,c)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:o,newPresences:c})}),this.onLeave((i,o,c)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:o,leftPresences:c})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,i){const o=this.cloneDeep(e),c=this.transformState(r),s={},f={};return this.map(o,(p,y)=>{c[p]||(f[p]=y)}),this.map(c,(p,y)=>{const _=o[p];if(_){const T=y.map(R=>R.presence_ref),E=_.map(R=>R.presence_ref),k=y.filter(R=>E.indexOf(R.presence_ref)<0),P=_.filter(R=>T.indexOf(R.presence_ref)<0);k.length>0&&(s[p]=k),P.length>0&&(f[p]=P)}else s[p]=y}),this.syncDiff(o,{joins:s,leaves:f},n,i)}static syncDiff(e,r,n,i){const{joins:o,leaves:c}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),i||(i=()=>{}),this.map(o,(s,f)=>{var p;const y=(p=e[s])!==null&&p!==void 0?p:[];if(e[s]=this.cloneDeep(f),y.length>0){const _=e[s].map(E=>E.presence_ref),T=y.filter(E=>_.indexOf(E.presence_ref)<0);e[s].unshift(...T)}n(s,y,f)}),this.map(c,(s,f)=>{let p=e[s];if(!p)return;const y=f.map(_=>_.presence_ref);p=p.filter(_=>y.indexOf(_.presence_ref)<0),e[s]=p,i(s,p,f),p.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(o=>(o.presence_ref=o.phx_ref,delete o.phx_ref,delete o.phx_ref_prev,o)):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 hte;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(hte||(hte={}));var fte;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(fte||(fte={}));var fp;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(fp||(fp={}));class $9{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=zc.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 iz(this,Uh.join,this.params,this.timeout),this.rejoinTimer=new dge(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=zc.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=zc.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=zc.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=zc.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Uh.reply,{},(i,o)=>{this._trigger(this._replyEventName(o),i)}),this.presence=new MA(this),this.broadcastEndpointURL=fge(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:o,presence:c,private:s}}=this.params;this._onError(y=>e==null?void 0:e(fp.CHANNEL_ERROR,y)),this._onClose(()=>e==null?void 0:e(fp.CLOSED));const f={},p={broadcast:o,presence:c,postgres_changes:(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(y=>y.filter))!==null&&i!==void 0?i:[],private:s};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:p},f)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:y})=>{var _;if(this.socket.setAuth(),y===void 0){e==null||e(fp.SUBSCRIBED);return}else{const T=this.bindings.postgres_changes,E=(_=T==null?void 0:T.length)!==null&&_!==void 0?_:0,k=[];for(let P=0;P{this.state=zc.errored,e==null||e(fp.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(y).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(fp.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:o,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:o,payload:c,private:this.private}]})};try{const p=await this._fetchWithTimeout(this.broadcastEndpointURL,f,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=p.body)===null||i===void 0?void 0:i.cancel()),p.ok?"ok":"error"}catch(p){return p.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var c,s,f;const p=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)&&o("ok"),p.receive("ok",()=>o("ok")),p.receive("error",()=>o("error")),p.receive("timeout",()=>o("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=zc.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Uh.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const i=new iz(this,Uh.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,o=setTimeout(()=>i.abort(),n),c=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(o),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 iz(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,o;const c=e.toLocaleLowerCase(),{close:s,error:f,leave:p,join:y}=Uh;if(n&&[s,f,p,y].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 k,P,R;return((k=E.filter)===null||k===void 0?void 0:k.event)==="*"||((R=(P=E.filter)===null||P===void 0?void 0:P.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===c}).map(E=>E.callback(T,n)):(o=this.bindings[c])===null||o===void 0||o.filter(E=>{var k,P,R,D,M,B;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in E){const V=E.id,G=(k=E.filter)===null||k===void 0?void 0:k.event;return V&&((P=r.ids)===null||P===void 0?void 0:P.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 k=T.data,{schema:P,table:R,commit_timestamp:D,type:M,errors:B}=k;T=Object.assign(Object.assign({},{schema:P,table:R,commit_timestamp:D,eventType:M,new:{},old:{},errors:B}),this._getPayloadRecords(k))}E.callback(T,n)})}_isClosed(){return this.state===zc.closed}_isJoined(){return this.state===zc.joined}_isJoining(){return this.state===zc.joining}_isLeaving(){return this.state===zc.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){const i=e.toLocaleLowerCase(),o={type:i,filter:r,callback:n};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this}_off(e,r){const n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(i=>{var o;return!(((o=i.type)===null||o===void 0?void 0:o.toLocaleLowerCase())===n&&$9.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(Uh.close,{},e)}_onError(e){this._on(Uh.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=zc.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=ute(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=ute(e.columns,e.old_record)),r}}const mte=()=>{},RBe=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class LBe{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=SBe,this.params={},this.timeout=uge,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mte,this.ref=0,this.logger=mte,this.conn=null,this.sendBuffer=[],this.serializer=new ABe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=o=>{let c;return o?c=o:typeof fetch>"u"?c=(...s)=>Fe(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}/${QU.websocket}`,this.httpEndpoint=fge(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:o=>[1e3,2e3,5e3,1e4][o-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(o,c)=>c(JSON.stringify(o)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new dge(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=bBe),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 DBe(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:TBe}))}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 e1.connecting:return n_.Connecting;case e1.open:return n_.Open;case e1.closing:return n_.Closing;default:return n_.Closed}}isConnected(){return this.connectionState()===n_.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(o=>o.topic===n);if(i)return i;{const o=new $9(`realtime:${e}`,r,this);return this.channels.push(o),o}}push(e){const{topic:r,event:n,payload:i,ref:o}=e,c=()=>{this.encode(e,s=>{var f;(f=this.conn)===null||f===void 0||f.send(s)})};this.log("push",`${r} ${n} (${o})`,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(Uh.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(EBe,"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:o,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",`${o.status||""} ${n} ${i} ${c&&"("+c+")"||""}`,o),Array.from(this.channels).filter(s=>s._isMember(n)).forEach(s=>s._trigger(i,o,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(Uh.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([RBe],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class DBe{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=e1.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class U9 extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function Al(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class MBe extends U9{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class eV extends U9{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var OBe=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};const mge=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(async()=>{const{default:n}=await Promise.resolve().then(()=>$S);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},FBe=()=>OBe(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Fe(()=>Promise.resolve().then(()=>$S),void 0)).Response:Response}),tV=t=>{if(Array.isArray(t))return t.map(r=>tV(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,o=>o.toUpperCase().replace(/[-_]/g,""));e[i]=tV(n)}),e};var sv=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};const sz=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),BBe=(t,e,r)=>sv(void 0,void 0,void 0,function*(){const n=yield FBe();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{e(new MBe(sz(i),t.status||500))}).catch(i=>{e(new eV(sz(i),i))}):e(new eV(sz(t),t))}),zBe=(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 uC(t,e,r,n,i,o){return sv(this,void 0,void 0,function*(){return new Promise((c,s)=>{t(r,zBe(e,n,i,o)).then(f=>{if(!f.ok)throw f;return n!=null&&n.noResolveJson?f:f.json()}).then(f=>c(f)).catch(f=>BBe(f,s,n))})})}function TD(t,e,r,n){return sv(this,void 0,void 0,function*(){return uC(t,"GET",e,r,n)})}function ay(t,e,r,n,i){return sv(this,void 0,void 0,function*(){return uC(t,"POST",e,n,i,r)})}function $Be(t,e,r,n,i){return sv(this,void 0,void 0,function*(){return uC(t,"PUT",e,n,i,r)})}function UBe(t,e,r,n){return sv(this,void 0,void 0,function*(){return uC(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function pge(t,e,r,n,i){return sv(this,void 0,void 0,function*(){return uC(t,"DELETE",e,n,i,r)})}var yu=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};const VBe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},pte={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class qBe{constructor(e,r={},n,i){this.url=e,this.headers=r,this.bucketId=n,this.fetch=mge(i)}uploadOrUpdate(e,r,n,i){return yu(this,void 0,void 0,function*(){try{let o;const c=Object.assign(Object.assign({},pte),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?(o=new FormData,o.append("cacheControl",c.cacheControl),f&&o.append("metadata",this.encodeMetadata(f)),o.append("",n)):typeof FormData<"u"&&n instanceof FormData?(o=n,o.append("cacheControl",c.cacheControl),f&&o.append("metadata",this.encodeMetadata(f))):(o=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 p=this._removeEmptyFolders(r),y=this._getFinalPath(p),_=yield this.fetch(`${this.url}/object/${y}`,Object.assign({method:e,body:o,headers:s},c!=null&&c.duplex?{duplex:c.duplex}:{})),T=yield _.json();return _.ok?{data:{path:p,id:T.Id,fullPath:T.Key},error:null}:{data:null,error:T}}catch(o){if(Al(o))return{data:null,error:o};throw o}})}upload(e,r,n){return yu(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return yu(this,void 0,void 0,function*(){const o=this._removeEmptyFolders(e),c=this._getFinalPath(o),s=new URL(this.url+`/object/upload/sign/${c}`);s.searchParams.set("token",r);try{let f;const p=Object.assign({upsert:pte.upsert},i),y=Object.assign(Object.assign({},this.headers),{"x-upsert":String(p.upsert)});typeof Blob<"u"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",p.cacheControl),f.append("",n)):typeof FormData<"u"&&n instanceof FormData?(f=n,f.append("cacheControl",p.cacheControl)):(f=n,y["cache-control"]=`max-age=${p.cacheControl}`,y["content-type"]=p.contentType);const _=yield this.fetch(s.toString(),{method:"PUT",body:f,headers:y}),T=yield _.json();return _.ok?{data:{path:o,fullPath:T.Key},error:null}:{data:null,error:T}}catch(f){if(Al(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,r){return yu(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 o=yield ay(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:i}),c=new URL(this.url+o.url),s=c.searchParams.get("token");if(!s)throw new U9("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:s},error:null}}catch(n){if(Al(n))return{data:null,error:n};throw n}})}update(e,r,n){return yu(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return yu(this,void 0,void 0,function*(){try{return{data:yield ay(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(Al(i))return{data:null,error:i};throw i}})}copy(e,r,n){return yu(this,void 0,void 0,function*(){try{return{data:{path:(yield ay(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(Al(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return yu(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),o=yield ay(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 o={signedUrl:encodeURI(`${this.url}${o.signedURL}${c}`)},{data:o,error:null}}catch(i){if(Al(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return yu(this,void 0,void 0,function*(){try{const i=yield ay(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:e},{headers:this.headers}),o=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}${o}`):null})),error:null}}catch(i){if(Al(i))return{data:null,error:i};throw i}})}download(e,r){return yu(this,void 0,void 0,function*(){const i=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",o=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),c=o?`?${o}`:"";try{const s=this._getFinalPath(e);return{data:yield(yield TD(this.fetch,`${this.url}/${i}/${s}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(s){if(Al(s))return{data:null,error:s};throw s}})}info(e){return yu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield TD(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:tV(n),error:null}}catch(n){if(Al(n))return{data:null,error:n};throw n}})}exists(e){return yu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield UBe(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(Al(n)&&n instanceof eV){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=[],o=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";o!==""&&i.push(o);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 p=i.join("&");return p!==""&&(p=`?${p}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${n}${p}`)}}}remove(e){return yu(this,void 0,void 0,function*(){try{return{data:yield pge(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(Al(r))return{data:null,error:r};throw r}})}list(e,r,n){return yu(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},VBe),r),{prefix:e||""});return{data:yield ay(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(Al(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 GBe="2.7.1",HBe={"X-Client-Info":`storage-js/${GBe}`};var Yb=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};class WBe{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},HBe),r),this.fetch=mge(n)}listBuckets(){return Yb(this,void 0,void 0,function*(){try{return{data:yield TD(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(Al(e))return{data:null,error:e};throw e}})}getBucket(e){return Yb(this,void 0,void 0,function*(){try{return{data:yield TD(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(Al(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return Yb(this,void 0,void 0,function*(){try{return{data:yield ay(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(Al(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return Yb(this,void 0,void 0,function*(){try{return{data:yield $Be(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(Al(n))return{data:null,error:n};throw n}})}emptyBucket(e){return Yb(this,void 0,void 0,function*(){try{return{data:yield ay(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(Al(r))return{data:null,error:r};throw r}})}deleteBucket(e){return Yb(this,void 0,void 0,function*(){try{return{data:yield pge(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(Al(r))return{data:null,error:r};throw r}})}}class KBe extends WBe{constructor(e,r={},n){super(e,r,n)}from(e){return new qBe(this.url,this.headers,e,this.fetch)}}const YBe="2.49.10";let pA="";typeof Deno<"u"?pA="deno":typeof document<"u"?pA="web":typeof navigator<"u"&&navigator.product==="ReactNative"?pA="react-native":pA="node";const ZBe={"X-Client-Info":`supabase-js-${pA}/${YBe}`},XBe={headers:ZBe},QBe={schema:"public"},JBe={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},eze={};var tze=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};const rze=t=>{let e;return t?e=t:typeof fetch>"u"?e=Jpe:e=fetch,(...r)=>e(...r)},nze=()=>typeof Headers>"u"?ege:Headers,ize=(t,e,r)=>{const n=rze(r),i=nze();return(o,c)=>tze(void 0,void 0,void 0,function*(){var s;const f=(s=yield e())!==null&&s!==void 0?s:t;let p=new i(c==null?void 0:c.headers);return p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${f}`),n(o,Object.assign(Object.assign({},c),{headers:p}))})};var sze=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};function aze(t){return t.endsWith("/")?t:t+"/"}function oze(t,e){var r,n;const{db:i,auth:o,realtime:c,global:s}=t,{db:f,auth:p,realtime:y,global:_}=e,T={db:Object.assign(Object.assign({},f),i),auth:Object.assign(Object.assign({},p),o),realtime:Object.assign(Object.assign({},y),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:()=>sze(this,void 0,void 0,function*(){return""})};return t.accessToken?T.accessToken=t.accessToken:delete T.accessToken,T}const gge="2.69.1",fw=30*1e3,rV=3,az=rV*fw,lze="http://localhost:9999",cze="supabase.auth.token",uze={"X-Client-Info":`gotrue-js/${gge}`},nV="X-Supabase-Api-Version",yge={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},dze=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,hze=6e5;class V9 extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Mi(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class fze extends V9{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function mze(t){return Mi(t)&&t.name==="AuthApiError"}class xge extends V9{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class gx extends V9{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class ey extends gx{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function pze(t){return Mi(t)&&t.name==="AuthSessionMissingError"}class oz extends gx{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class OP extends gx{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class FP extends gx{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 gze(t){return Mi(t)&&t.name==="AuthImplicitGrantRedirectError"}class gte extends gx{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 iV extends gx{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function lz(t){return Mi(t)&&t.name==="AuthRetryableFetchError"}class yte extends gx{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class OA extends gx{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const xte="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),_te=` \r=`.split(""),yze=(()=>{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 vte(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=c=>{vze(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 _ze(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}xze(n,e)}}function vze(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 bze(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function Sze(t){return Math.round(Date.now()/1e3)+t}function Tze(){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 Ff=()=>typeof window<"u"&&typeof document<"u",B0={tested:!1,writable:!1},FA=()=>{if(!Ff())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(B0.tested)return B0.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),B0.tested=!0,B0.writable=!0}catch{B0.tested=!0,B0.writable=!1}return B0.writable};function Eze(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,o)=>{e[o]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}const vge=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(async()=>{const{default:n}=await Promise.resolve().then(()=>$S);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},Aze=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",bge=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},BP=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},zP=async(t,e)=>{await t.removeItem(e)};class s3{constructor(){this.promise=new s3.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}s3.promiseConstructor=Promise;function cz(t){const e=t.split(".");if(e.length!==3)throw new OA("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function kze(t,e){return new Promise((n,i)=>{(async()=>{for(let o=0;o<1/0;o++)try{const c=await t(o);if(!e(o,null,c)){n(c);return}}catch(c){if(!e(o,c)){i(c);return}}})()})}function Cze(t){return("0"+t.toString(16)).substr(-2)}function Ize(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let i="";for(let o=0;o<56;o++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Cze).join("")}async function Nze(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(o=>String.fromCharCode(o)).join("")}async function Pze(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 Nze(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Zb(t,e,r=!1){const n=Ize();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await bge(t,`${e}-code-verifier`,i);const o=await Pze(n);return[o,n===o?"plain":"s256"]}const Rze=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Lze(t){const e=t.headers.get(nV);if(!e||!e.match(Rze))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Dze(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 Mze(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 Oze=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),Fze=[502,503,504];async function bte(t){var e;if(!Aze(t))throw new iV(Z0(t),0);if(Fze.includes(t.status))throw new iV(Z0(t),t.status);let r;try{r=await t.json()}catch(o){throw new xge(Z0(o),o)}let n;const i=Lze(t);if(i&&i.getTime()>=yge["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 yte(Z0(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new ey}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((o,c)=>o&&typeof c=="string",!0))throw new yte(Z0(r),t.status,r.weak_password.reasons);throw new fze(Z0(r),t.status||500,n)}const Bze=(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 Qi(t,e,r,n){var i;const o=Object.assign({},n==null?void 0:n.headers);o[nV]||(o[nV]=yge["2024-01-01"].name),n!=null&&n.jwt&&(o.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 zze(t,e,r+s,{headers:o,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 zze(t,e,r,n,i,o){const c=Bze(e,n,i,o);let s;try{s=await t(r,Object.assign({},c))}catch(f){throw console.error(f),new iV(Z0(f),0)}if(s.ok||await bte(s),n!=null&&n.noResolveJson)return s;try{return await s.json()}catch(f){await bte(f)}}function ty(t){var e;let r=null;qze(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Sze(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function wte(t){const e=ty(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 fy(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function $ze(t){return{data:t,error:null}}function Uze(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o}=t,c=Oze(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:o},f=Object.assign({},c);return{data:{properties:s,user:f},error:null}}function Vze(t){return t}function qze(t){return t.access_token&&t.refresh_token&&t.expires_in}var Gze=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(k=>{const P=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(k.split(";")[1].split("=")[1]);p[`${R}Page`]=P}),p.total=parseInt(T)),{data:Object.assign(Object.assign({},_),p),error:null}}catch(p){if(Mi(p))return{data:{users:[]},error:p};throw p}}async getUserById(e){try{return await Qi(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:fy})}catch(r){if(Mi(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){try{return await Qi(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:fy})}catch(n){if(Mi(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){try{return await Qi(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:fy})}catch(n){if(Mi(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:r,error:n}=await Qi(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(Mi(r))return{data:null,error:r};throw r}}async _deleteFactor(e){try{return{data:await Qi(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Mi(r))return{data:null,error:r};throw r}}}const Wze={getItem:t=>FA()?globalThis.localStorage.getItem(t):null,setItem:(t,e)=>{FA()&&globalThis.localStorage.setItem(t,e)},removeItem:t=>{FA()&&globalThis.localStorage.removeItem(t)}};function Ste(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}function Kze(){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 Xb={debug:!!(globalThis&&FA()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class wge extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Yze extends wge{}async function Zze(t,e,r){Xb.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Xb.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){Xb.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{Xb.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw Xb.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Yze(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Xb.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}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()}}))}Kze();const Xze={url:lze,storageKey:cze,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:uze,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Tte(t,e,r){return await r()}class Pj{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=Pj.nextInstanceID,Pj.nextInstanceID+=1,this.instanceID>0&&Ff()&&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({},Xze),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 Hze({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=vge(i.fetch),this.lock=i.lock||Tte,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Ff()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Zze:this.lock=Tte,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:FA()?this.storage=Wze:(this.memoryStorage={},this.storage=Ste(this.memoryStorage)):(this.memoryStorage={},this.storage=Ste(this.memoryStorage)),Ff()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${gge}) ${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=Eze(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Ff()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:o}=await this._getSessionFromURL(r,n);if(o){if(this._debug("#_initialize()","error detecting session from URL",o),gze(o)){const f=(e=o.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:o}}return await this._removeSession(),{error:o}}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 Mi(r)?{error:r}:{error:new xge("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const o=await Qi(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:ty}),{data:c,error:s}=o;if(s||!c)return{data:{user:null,session:null},error:s};const f=c.session,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:p,session:f},error:null}}catch(o){if(Mi(o))return{data:{user:null,session:null},error:o};throw o}}async signUp(e){var r,n,i;try{let o;if("email"in e){const{email:y,password:_,options:T}=e;let E=null,k=null;this.flowType==="pkce"&&([E,k]=await Zb(this.storage,this.storageKey)),o=await Qi(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:T==null?void 0:T.emailRedirectTo,body:{email:y,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:k},xform:ty})}else if("phone"in e){const{phone:y,password:_,options:T}=e;o=await Qi(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:y,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:ty})}else throw new OP("You must provide either an email or phone number and a password");const{data:c,error:s}=o;if(s||!c)return{data:{user:null,session:null},error:s};const f=c.session,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:p,session:f},error:null}}catch(o){if(Mi(o))return{data:{user:null,session:null},error:o};throw o}}async signInWithPassword(e){try{let r;if("email"in e){const{email:o,password:c,options:s}=e;r=await Qi(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:c,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:wte})}else if("phone"in e){const{phone:o,password:c,options:s}=e;r=await Qi(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:c,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:wte})}else throw new OP("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 oz}:(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(Mi(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(e){var r,n,i,o;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:(o=e.options)===null||o===void 0?void 0:o.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const r=await BP(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:o,error:c}=await Qi(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:ty});if(await zP(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!o||!o.session||!o.user?{data:{user:null,session:null,redirectType:null},error:new oz}:(o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),{data:Object.assign(Object.assign({},o),{redirectType:i??null}),error:c})}catch(o){if(Mi(o))return{data:{user:null,session:null,redirectType:null},error:o};throw o}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:o,nonce:c}=e,s=await Qi(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:o,nonce:c,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:ty}),{data:f,error:p}=s;return p?{data:{user:null,session:null},error:p}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new oz}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:p})}catch(r){if(Mi(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(e){var r,n,i,o,c;try{if("email"in e){const{email:s,options:f}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await Zb(this.storage,this.storageKey));const{error:_}=await Qi(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:p,code_challenge_method:y},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:p,error:y}=await Qi(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:(o=f==null?void 0:f.shouldCreateUser)!==null&&o!==void 0?o:!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:p==null?void 0:p.message_id},error:y}}throw new OP("You must provide either an email or phone number.")}catch(s){if(Mi(s))return{data:{user:null,session:null},error:s};throw s}}async verifyOtp(e){var r,n;try{let i,o;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,o=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:c,error:s}=await Qi(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:ty});if(s)throw s;if(!c)throw new Error("An error occurred on token verification.");const f=c.session,p=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:p,session:f},error:null}}catch(i){if(Mi(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var r,n,i;try{let o=null,c=null;return this.flowType==="pkce"&&([o,c]=await Zb(this.storage,this.storageKey)),await Qi(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:o,code_challenge_method:c}),headers:this.headers,xform:$ze})}catch(o){if(Mi(o))return{data:null,error:o};throw o}}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 ey;const{error:i}=await Qi(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(Mi(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:o}=e,{error:c}=await Qi(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},redirectTo:o==null?void 0:o.emailRedirectTo});return{data:{user:null,session:null},error:c}}else if("phone"in e){const{phone:n,type:i,options:o}=e,{data:c,error:s}=await Qi(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:s}}throw new OP("You must provide either an email or phone number and a type")}catch(r){if(Mi(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 BP(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&&p==="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,p,y))})}return{data:{session:e},error:null}}const{session:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?{data:{session:null},error:o}:{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 Qi(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:fy}):await this._useSession(async r=>{var n,i,o;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 ey}:await Qi(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(o=(i=c.session)===null||i===void 0?void 0:i.access_token)!==null&&o!==void 0?o:void 0,xform:fy})})}catch(r){if(Mi(r))return pze(r)&&(await this._removeSession(),await zP(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:o}=n;if(o)throw o;if(!i.session)throw new ey;const c=i.session;let s=null,f=null;this.flowType==="pkce"&&e.email!=null&&([s,f]=await Zb(this.storage,this.storageKey));const{data:p,error:y}=await Qi(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:fy});if(y)throw y;return c.user=p.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(Mi(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 ey;const r=Date.now()/1e3;let n=r,i=!0,o=null;const{payload:c}=cz(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};o=s}else{const{data:s,error:f}=await this._getUser(e.access_token);if(f)throw f;o={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(o),await this._notifyAllSubscribers("SIGNED_IN",o)}return{data:{user:o.user,session:o},error:null}}catch(r){if(Mi(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 ey;const{session:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?{data:{user:null,session:null},error:o}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(Mi(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Ff())throw new FP("No browser detected.");if(e.error||e.error_description||e.error_code)throw new FP(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 gte("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new FP("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 gte("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:o,refresh_token:c,expires_in:s,expires_at:f,token_type:p}=e;if(!o||!s||!c||!p)throw new FP("No session defined in URL");const y=Math.round(Date.now()/1e3),_=parseInt(s);let T=y+_;f&&(T=parseInt(f));const E=T-y;E*1e3<=fw&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}s, should have been closer to ${_}s`);const k=T-_;y-k>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",k,T,y):y-k<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",k,T,y);const{data:P,error:R}=await this._getUser(o);if(R)throw R;const D={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:_,expires_at:T,refresh_token:c,token_type:p,user:P.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:D,redirectType:e.type},error:null}}catch(n){if(Mi(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 BP(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:o}=r;if(o)return{error:o};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&&!(mze(s)&&(s.status===404||s.status===401||s.status===403)))return{error:s}}return e!=="others"&&(await this._removeSession(),await zP(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=Tze(),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:o},error:c}=r;if(c)throw c;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",o)),this._debug("INITIAL_SESSION","callback id",e,"session",o)}catch(o){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",o),console.error(o)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Zb(this.storage,this.storageKey,!0));try{return await Qi(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(o){if(Mi(o))return{data:null,error:o};throw o}}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(Mi(r))return{data:null,error:r};throw r}}async linkIdentity(e){var r;try{const{data:n,error:i}=await this._useSession(async o=>{var c,s,f,p,y;const{data:_,error:T}=o;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 Qi(this.fetch,"GET",E,{headers:this.headers,jwt:(y=(p=_.session)===null||p===void 0?void 0:p.access_token)!==null&&y!==void 0?y:void 0})});if(i)throw i;return Ff()&&!(!((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(Mi(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:o,error:c}=r;if(c)throw c;return await Qi(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(Mi(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 kze(async i=>(i>0&&await jze(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Qi(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ty})),(i,o)=>{const c=200*Math.pow(2,i);return o&&lz(o)&&Date.now()+c-n{try{await s.callback(e,r)}catch(f){o.push(f)}});if(await Promise.all(c),o.length>0){for(let s=0;sthis._autoRefreshTokenTick(),fw);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)/fw);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${fw}ms, refresh threshold is ${rV} ticks`),i<=rV&&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 wge)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ff()||!(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[o,c]=await Zb(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(o)}`,code_challenge_method:`${encodeURIComponent(c)}`});i.push(s.toString())}if(n!=null&&n.queryParams){const o=new URLSearchParams(n.queryParams);i.push(o.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:o}=r;return o?{data:null,error:o}:await Qi(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(Mi(r))return{data:null,error:r};throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:o,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:p}=await Qi(this.fetch,"POST",`${this.url}/factors`,{body:s,headers:this.headers,jwt:(n=o==null?void 0:o.session)===null||n===void 0?void 0:n.access_token});return p?{data:null,error:p}:(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(Mi(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:o}=r;if(o)return{data:null,error:o};const{data:c,error:s}=await Qi(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(Mi(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:o}=r;return o?{data:null,error:o}:await Qi(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(Mi(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"),o=n.filter(c=>c.factor_type==="phone"&&c.status==="verified");return{data:{all:n,totp:i,phone:o},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var r,n;const{data:{session:i},error:o}=e;if(o)return{data:null,error:o};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=cz(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 y=c.amr||[];return{data:{currentLevel:s,nextLevel:f,currentAuthenticationMethods:y},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+hze>Date.now()))return n;const{data:i,error:o}=await Qi(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;if(!i.keys||i.keys.length===0)throw new OA("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),n=i.keys.find(c=>c.kid===e),!n)throw new OA("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:E,error:k}=await this.getSession();if(k||!E.session)return{data:null,error:k};n=E.session.access_token}const{header:i,payload:o,signature:c,raw:{header:s,payload:f}}=cz(n);if(Dze(o.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:o,header:i,signature:c},error:null}}const p=Mze(i.alg),y=await this.fetchJwk(i.kid,r),_=await crypto.subtle.importKey("jwk",y,p,!0,["verify"]);if(!await crypto.subtle.verify(p,_,c,wze(`${s}.${f}`)))throw new OA("Invalid JWT signature");return{data:{claims:o,header:i,signature:c},error:null}}catch(n){if(Mi(n))return{data:null,error:n};throw n}}}Pj.nextInstanceID=0;const Qze=Pj;class Jze extends Qze{constructor(e){super(e)}}var e$e=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function s(y){try{p(n.next(y))}catch(_){c(_)}}function f(y){try{p(n.throw(y))}catch(_){c(_)}}function p(y){y.done?o(y.value):i(y.value).then(s,f)}p((n=n.apply(t,e||[])).next())})};class t$e{constructor(e,r,n){var i,o,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=aze(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 p=`sb-${f.hostname.split(".")[0]}-auth-token`,y={db:QBe,realtime:eze,auth:Object.assign(Object.assign({},JBe),{storageKey:p}),global:XBe},_=oze(n??{},y);this.storageKey=(i=_.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(o=_.global.headers)!==null&&o!==void 0?o:{},_.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=ize(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 vBe(new URL("rest/v1",f).href,{headers:this.headers,schema:_.db.schema,fetch:this.fetch}),_.accessToken||this._listenForAuthEvents()}get functions(){return new Z4e(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new KBe(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 e$e(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:o,flowType:c,lock:s,debug:f},p,y){const _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Jze({url:this.authUrl.href,headers:Object.assign(Object.assign({},_),p),storageKey:o,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,flowType:c,lock:s,debug:f,fetch:y,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new LBe(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 r$e=(t,e,r)=>new t$e(t,e,r),n$e="lovable-preview-auth:result";function i$e(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!==n$e||!("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 s$e(){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,o=window.parent;if(!i||!(o!==null&&o!==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)$/,p=location.ancestorOrigins,y=(p==null?void 0:p[0])??(document.referrer?new URL(document.referrer).origin:""),_=y&&f.test(y)?[y]:s?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],T=2e3,E=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),k=(V,G,W)=>new Promise(Z=>{const Q=E();let re=!1;const se=Ce=>{re||(re=!0,clearTimeout(_e),window.removeEventListener("message",ue),Z(Ce))},ue=Ce=>{if(!_.includes(Ce.origin))return;const Me=i$e(Ce.data,Q);Me&&se(Me)};window.addEventListener("message",ue);const _e=setTimeout(()=>{se(null)},T),we={type:V,requestId:Q,projectId:i,key:G};W!==void 0&&(we.value=W);for(const Ce of _)window.parent.postMessage(we,Ce)});let P=!0;const R=250,D=V=>{try{return localStorage.getItem(V)}catch{return}};return{getItem:async V=>{const G=D(V);let W=await k("lovable-preview-auth:get",V,G??void 0);if(!W&&P&&(await new Promise(Z=>setTimeout(Z,R)),W=await k("lovable-preview-auth:get",V,G??void 0)),P=!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),k("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),k("lovable-preview-auth:remove",V,G??void 0).then(()=>{})}}}const a$e="https://relzejiswnotikjgvjhz.supabase.co",o$e="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",Re=r$e(a$e,o$e,{auth:{storage:s$e(),persistSession:!0,autoRefreshToken:!0}}),MVt=Object.freeze(Object.defineProperty({__proto__:null,supabase:Re},Symbol.toStringTag,{value:"Module"})),Sge=I.createContext(void 0),l$e=({children:t})=>{const[e,r]=I.useState(null),[n,i]=I.useState(null),[o,c]=I.useState(!0),[s,f]=I.useState(!0),[p,y]=I.useState(!1),[_,T]=I.useState(!1),[E,k]=I.useState(!1),[P,R]=I.useState(null),[D,M]=I.useState([]),[B,V]=I.useState(null),G=I.useRef(null),W=I.useRef(!1),Z=I.useRef(!1),Q=Gs(),re=()=>{y(!1),T(!1),k(!1),R(null),M([]),V(null),G.current=null,W.current=!1},se=async Ce=>{if(W.current&&G.current===Ce||Z.current)return;Z.current=!0,f(!0);const Me=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),Z.current=!1,f(!1)},8e3);try{console.log("Checking roles via RPC for user:",Ce);const[{data:Ae,error:be},{data:me,error:Pe},{data:Ie,error:Se}]=await Promise.all([Re.rpc("has_role",{_user_id:Ce,_role:"admin"}),Re.rpc("has_role",{_user_id:Ce,_role:"brokerage_manager"}),Re.rpc("has_role",{_user_id:Ce,_role:"coach"})]);if(be||Pe)console.error("Role RPC errors:",{isAdminError:be,isBrokerError:Pe,isCoachError:Se}),y(!1),T(!1),k(!1);else{const rt=!!Ae,at=!!me,Et=!!Ie;console.log("RPC roles result:",{adminValue:rt,brokerValue:at,coachValue:Et}),y(rt),T(at),k(Et)}G.current=Ce,W.current=!0,window.clearTimeout(Me),f(!1);const{data:ve,error:We}=await Re.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",Ce).single();if(!We&&(ve!=null&&ve.is_paused)){const rt=ve.paused_reason;try{sessionStorage.setItem("accountPausedReason",rt||"")}catch{}await Re.auth.signOut(),re(),Q("/auth?paused=1",{replace:!0});return}if(R(!We&&ve?ve.brokerage_id:null),me){console.log("Fetching managed brokerages for user:",Ce);const{data:rt,error:at}=await Re.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",Ce);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(Nt=>Nt.brokerage_id).filter(Boolean)));if(Et.length===0){M([]);return}const{data:_t,error:Vt}=await Re.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 pt=_t.map(Nt=>({id:Nt.id,name:Nt.name})).sort((Nt,er)=>Et.indexOf(Nt.id)-Et.indexOf(er.id));console.log("Parsed managed brokerages:",pt),M(pt),pt.length>0&&V(Nt=>Nt??pt[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),M([]);G.current=Ce,W.current=!0}catch(Ae){console.error("Unexpected error in checkRoles:",Ae),re()}finally{window.clearTimeout(Me),Z.current=!1,f(!1)}};I.useEffect(()=>{let Ce=!0,Me=!1;const Ae=()=>{!Ce||Me||(Me=!0,c(!1))},{data:{subscription:be}}=Re.auth.onAuthStateChange((Pe,Ie)=>{console.log("Auth event:",Pe),Ce&&(i(Ie),r((Ie==null?void 0:Ie.user)??null),Ae(),Pe==="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)))}),me=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Ae()},8e3);return()=>{Ce=!1,window.clearTimeout(me),be.unsubscribe()}},[]);const ue=async(Ce,Me)=>{var Pe;const Ae=(Ce||"").trim().toLowerCase(),{data:be,error:me}=await Re.auth.signInWithPassword({email:Ae,password:Me});if(me)throw Gt.error(/invalid login credentials/i.test(me.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:me.message),me;if((Pe=be.user)!=null&&Pe.id){const{data:Ie}=await Re.from("profiles").select("is_paused, paused_reason").eq("id",be.user.id).maybeSingle();if(Ie!=null&&Ie.is_paused){const Se=Ie.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",Se)}catch{}await Re.auth.signOut(),re(),r(null),i(null);const ve=new Error(Se?`Your account is paused. ${Se}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw ve.name="AccountPaused",Gt.error(ve.message),ve}}Gt.success("Welcome back!")},_e=async(Ce,Me,Ae)=>{var Se;const be="https://dashboard.relevelup.com/dashboard",me=localStorage.getItem("levelup_referral_code")||null,{data:Pe,error:Ie}=await Re.auth.signUp({email:Ce,password:Me,options:{emailRedirectTo:be,data:{name:Ae,referred_by_code:me}}});if(Ie)throw Gt.error(Ie.message),Ie;if(me&&((Se=Pe.user)!=null&&Se.id))try{await Re.from("profiles").update({referred_by_code:me}).eq("id",Pe.user.id),localStorage.removeItem("levelup_referral_code")}catch(ve){console.warn("Failed to attach referral code to profile",ve)}Gt.success("Account created! Welcome to LevelUp."),Q("/dashboard")},we=async()=>{try{const{data:{session:Ce}}=await Re.auth.getSession();if(Ce){const{error:Me}=await Re.auth.signOut();Me?Me.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",Me.message):(console.error("Sign out error:",Me),Gt.error(Me.message)):Gt.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),y(!1),T(!1),R(null),M([]),V(null),Q("/auth")}catch(Ce){console.error("Unexpected sign out error:",Ce),Q("/auth")}};return a.jsx(Sge.Provider,{value:{user:e,session:n,loading:o,rolesLoading:s,signIn:ue,signUp:_e,signOut:we,isAdmin:p,isBrokerageManager:_,isCoach:E,brokerageId:P,managedBrokerages:D,selectedBrokerageId:B,setSelectedBrokerageId:V},children:t})},Gn=()=>{const t=I.useContext(Sge);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},Tge=I.createContext({onlineUsers:[],totalOnline:0}),c$e=3*60*1e3,u$e=45*1e3,d$e=30*1e3,h$e=({children:t})=>{const{user:e,brokerageId:r,isAdmin:n}=Gn(),[i,o]=I.useState([]),c=I.useRef(new Date().toISOString()),s=I.useCallback(async()=>{e&&await Re.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=I.useCallback(async()=>{if(!e)return;const y=new Date(Date.now()-c$e).toISOString(),{data:_}=await Re.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",y).order("last_seen_at",{ascending:!1}).limit(200);if(!(_!=null&&_.length)){o([]);return}const T=_.map(P=>P.user_id),{data:E}=await Re.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",T),k=new Map((E||[]).map(P=>[P.id,P]));o(_.map(P=>{var D;const R=k.get(P.user_id);return{id:P.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:P.online_since||P.last_seen_at}}))},[e==null?void 0:e.id]);I.useEffect(()=>{if(!e){o([]);return}c.current=new Date().toISOString();let y=!1;const _=async()=>{y||(await s(),await f())};_();const T=window.setInterval(()=>{s()},u$e),E=window.setInterval(()=>{f()},d$e),k=()=>{document.visibilityState==="visible"&&_()};return document.addEventListener("visibilitychange",k),()=>{y=!0,window.clearInterval(T),window.clearInterval(E),document.removeEventListener("visibilitychange",k)}},[e==null?void 0:e.id,s,f]);const p=i.filter(y=>!!(y.id===(e==null?void 0:e.id)||n||r&&y.brokerageId===r||!r&&!y.brokerageId));return a.jsx(Tge.Provider,{value:{onlineUsers:p,totalOnline:p.length},children:t})},OVt=()=>I.useContext(Tge),Ege=I.createContext(void 0),z0="levelup_admin_session",qg="levelup_impersonation",uz="levelup_impersonation_return",f$e=({children:t})=>{const[e,r]=I.useState(!1),[n,i]=I.useState(null),[o,c]=I.useState(!1);I.useEffect(()=>{const p=sessionStorage.getItem(qg);if(p)try{const y=JSON.parse(p);r(!0),i(y)}catch{sessionStorage.removeItem(qg)}},[]);const s=async(p,y)=>{c(!0);try{const{data:{session:_}}=await Re.auth.getSession();if(!_)return Gt.error("No active session found"),!1;const T={access_token:_.access_token,refresh_token:_.refresh_token};sessionStorage.setItem(z0,JSON.stringify(T)),y&&sessionStorage.setItem(uz,y);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:p})}),k=await E.json();if(!E.ok)throw new Error(k.error||"Failed to impersonate user");const P={id:k.targetUser.id,name:k.targetUser.name,email:k.targetUser.email};if(sessionStorage.setItem(qg,JSON.stringify(P)),k.method==="session"){const{error:R}=await Re.auth.setSession({access_token:k.access_token,refresh_token:k.refresh_token});if(R)throw console.error("Set session error:",R),sessionStorage.removeItem(z0),sessionStorage.removeItem(qg),new Error("Failed to establish impersonation session")}else{const R=k.type||"recovery",{error:D}=await Re.auth.verifyOtp({token_hash:k.token_hash,type:R});if(D)throw console.error("Verify OTP error:",D),sessionStorage.removeItem(z0),sessionStorage.removeItem(qg),new Error("Failed to establish impersonation session")}return r(!0),i(P),Gt.success(`Now viewing as ${P.name}`),window.location.href="/dashboard",!0}catch(_){return console.error("Impersonation error:",_),Gt.error(_.message||"Failed to impersonate user"),sessionStorage.removeItem(z0),sessionStorage.removeItem(qg),!1}finally{c(!1)}},f=async()=>{c(!0);try{const p=sessionStorage.getItem(z0);if(!p){await Re.auth.signOut(),window.location.href="/auth";return}const y=JSON.parse(p);await Re.auth.signOut();const{error:_}=await Re.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(sessionStorage.removeItem(z0),sessionStorage.removeItem(qg),_){console.error("Failed to restore admin session:",_),Gt.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),i(null),Gt.success("Returned to your account");const T=sessionStorage.getItem(uz)||"/admin/members";sessionStorage.removeItem(uz),window.location.href=T}catch(p){console.error("Stop impersonation error:",p),Gt.error("Failed to restore admin session"),sessionStorage.removeItem(z0),sessionStorage.removeItem(qg),window.location.href="/auth"}finally{c(!1)}};return a.jsx(Ege.Provider,{value:{isImpersonating:e,impersonatedUser:n,startImpersonation:s,stopImpersonation:f,isLoading:o},children:t})},Age=()=>{const t=I.useContext(Ege);if(t===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return t},m$e=()=>{const{isImpersonating:t,impersonatedUser:e,stopImpersonation:r,isLoading:n}=Age();return!t||!e?null:a.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:a.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(PS,{className:"h-5 w-5 flex-shrink-0"}),a.jsxs("span",{className:"font-medium text-sm md:text-base",children:[a.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),a.jsx("strong",{children:e.name}),a.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",e.email,")"]})]})]}),a.jsx(zt,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?a.jsx(Ru,{className:"h-4 w-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(Ds,{className:"h-4 w-4 mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),a.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},jge=I.createContext(void 0),Qb="levelup_acting_as",$P="levelup_acting_as_self",p$e=({children:t})=>{const{user:e}=Gn(),[r,n]=I.useState(!1),[i,o]=I.useState([]),[c,s]=I.useState(null),[f,p]=I.useState({}),[y,_]=I.useState(!0),[T,E]=I.useState(()=>sessionStorage.getItem($P)==="true");I.useEffect(()=>{if(!(e!=null&&e.id)){n(!1),o([]),s(null),p({}),_(!1);return}(async()=>{_(!0);try{const{data:B}=await Re.rpc("has_role",{_user_id:e.id,_role:"assistant"});if(!B){n(!1),o([]),s(null),p({}),_(!1);return}n(!0);const{data:V,error:G}=await Re.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",e.id);if(G||!V||V.length===0){o([]),_(!1);return}const W=V.map(re=>re.agent_id),{data:Z}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",W),Q=(Z||[]).map(re=>({id:re.id,name:re.name||re.email||"Unknown",email:re.email||"",avatar_url:re.avatar_url}));if(o(Q),sessionStorage.getItem($P)==="true")E(!0),s(null),p({});else{const re=sessionStorage.getItem(Qb);if(re){const se=Q.find(ue=>ue.id===re);if(se){s(se);const ue=V.find(_e=>_e.agent_id===re);p((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);p((ue==null?void 0:ue.permissions)||{}),sessionStorage.setItem(Qb,Q[0].id)}}else if(Q.length>0){s(Q[0]);const se=V.find(ue=>ue.agent_id===Q[0].id);p((se==null?void 0:se.permissions)||{}),sessionStorage.setItem(Qb,Q[0].id)}}}catch(B){console.error("Error loading assistant data:",B)}finally{_(!1)}})()},[e==null?void 0:e.id]);const k=M=>{s(M),E(!1),sessionStorage.removeItem($P),M?(sessionStorage.setItem(Qb,M.id),Re.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(e==null?void 0:e.id)||"").eq("agent_id",M.id).single().then(({data:B})=>{p((B==null?void 0:B.permissions)||{})})):(sessionStorage.removeItem(Qb),p({}))},P=()=>{E(!0),s(null),p({}),sessionStorage.setItem($P,"true"),sessionStorage.removeItem(Qb)},R=M=>!r||T?!0:f[M]===!0,D=r&&c&&!T?c.id:(e==null?void 0:e.id)||null;return a.jsx(jge.Provider,{value:{isAssistant:r,assignedAgents:i,actingAsAgent:c,setActingAsAgent:k,effectiveUserId:D,permissions:f,hasPermission:R,isLoading:y,isActingAsSelf:T,setActingAsSelf:P},children:t})},a3=()=>{const t=I.useContext(jge);if(t===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return t},Gi=()=>{const{effectiveUserId:t}=a3();return t};var kge={exports:{}},Cge={};/** * @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 F1=I;function g$e(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var y$e=typeof Object.is=="function"?Object.is:g$e,x$e=F1.useState,_$e=F1.useEffect,v$e=F1.useLayoutEffect,b$e=F1.useDebugValue;function w$e(t,e){var r=e(),n=x$e({inst:{value:r,getSnapshot:e}}),i=n[0].inst,o=n[1];return v$e(function(){i.value=r,i.getSnapshot=e,dz(i)&&o({inst:i})},[t,r,e]),_$e(function(){return dz(i)&&o({inst:i}),t(function(){dz(i)&&o({inst:i})})},[t]),b$e(r),r}function dz(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!y$e(t,r)}catch{return!0}}function S$e(t,e){return e()}var T$e=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?S$e:w$e;Cge.useSyncExternalStore=F1.useSyncExternalStore!==void 0?F1.useSyncExternalStore:T$e;kge.exports=Cge;var E$e=kge.exports;function A$e(){return E$e.useSyncExternalStore(j$e,()=>!0,()=>!1)}function j$e(){return()=>{}}var q9="Avatar",[k$e,FVt]=Yo(q9),[C$e,Ige]=k$e(q9),Nge=I.forwardRef((t,e)=>{const{__scopeAvatar:r,...n}=t,[i,o]=I.useState("idle");return a.jsx(C$e,{scope:r,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:a.jsx(rn.span,{...n,ref:e})})});Nge.displayName=q9;var Pge="AvatarImage",Rge=I.forwardRef((t,e)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:i=()=>{},...o}=t,c=Ige(Pge,r),s=I$e(n,o),f=po(p=>{i(p),c.onImageLoadingStatusChange(p)});return Po(()=>{s!=="idle"&&f(s)},[s,f]),s==="loaded"?a.jsx(rn.img,{...o,ref:e,src:n}):null});Rge.displayName=Pge;var Lge="AvatarFallback",Dge=I.forwardRef((t,e)=>{const{__scopeAvatar:r,delayMs:n,...i}=t,o=Ige(Lge,r),[c,s]=I.useState(n===void 0);return I.useEffect(()=>{if(n!==void 0){const f=window.setTimeout(()=>s(!0),n);return()=>window.clearTimeout(f)}},[n]),c&&o.imageLoadingStatus!=="loaded"?a.jsx(rn.span,{...i,ref:e}):null});Dge.displayName=Lge;function Ete(t,e){return t?e?(t.src!==e&&(t.src=e),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function I$e(t,{referrerPolicy:e,crossOrigin:r}){const n=A$e(),i=I.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[c,s]=I.useState(()=>Ete(o,t));return Po(()=>{s(Ete(o,t))},[o,t]),Po(()=>{const f=_=>()=>{s(_)};if(!o)return;const p=f("loaded"),y=f("error");return o.addEventListener("load",p),o.addEventListener("error",y),e&&(o.referrerPolicy=e),typeof r=="string"&&(o.crossOrigin=r),()=>{o.removeEventListener("load",p),o.removeEventListener("error",y)}},[o,r,e]),c}var Mge=Nge,Oge=Rge,Fge=Dge;const fd=I.forwardRef(({className:t,...e},r)=>a.jsx(Mge,{ref:r,className:sr("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));fd.displayName=Mge.displayName;const md=I.forwardRef(({className:t,...e},r)=>a.jsx(Oge,{ref:r,className:sr("aspect-square h-full w-full",t),...e}));md.displayName=Oge.displayName;const pd=I.forwardRef(({className:t,...e},r)=>a.jsx(Fge,{ref:r,className:sr("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));pd.displayName=Fge.displayName;const N$e=kS("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 a.jsx("div",{className:sr(N$e({variant:e}),t),...r})}var P$e=I.createContext(void 0);function av(t){const e=I.useContext(P$e);return t||e||"ltr"}var hz="rovingFocusGroup.onEntryFocus",R$e={bubbles:!1,cancelable:!0},dC="RovingFocusGroup",[sV,Bge,L$e]=Zk(dC),[D$e,VS]=Yo(dC,[L$e]),[M$e,O$e]=D$e(dC),zge=I.forwardRef((t,e)=>a.jsx(sV.Provider,{scope:t.__scopeRovingFocusGroup,children:a.jsx(sV.Slot,{scope:t.__scopeRovingFocusGroup,children:a.jsx(F$e,{...t,ref:e})})}));zge.displayName=dC;var F$e=I.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:i=!1,dir:o,currentTabStopId:c,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:f,onEntryFocus:p,preventScrollOnEntryFocus:y=!1,..._}=t,T=I.useRef(null),E=Kn(e,T),k=av(o),[P,R]=dd({prop:c,defaultProp:s??null,onChange:f,caller:dC}),[D,M]=I.useState(!1),B=po(p),V=Bge(r),G=I.useRef(!1),[W,Z]=I.useState(0);return I.useEffect(()=>{const Q=T.current;if(Q)return Q.addEventListener(hz,B),()=>Q.removeEventListener(hz,B)},[B]),a.jsx(M$e,{scope:r,orientation:n,dir:k,loop:i,currentTabStopId:P,onItemFocus:I.useCallback(Q=>R(Q),[R]),onItemShiftTab:I.useCallback(()=>M(!0),[]),onFocusableItemAdd:I.useCallback(()=>Z(Q=>Q+1),[]),onFocusableItemRemove:I.useCallback(()=>Z(Q=>Q-1),[]),children:a.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(hz,R$e);if(Q.currentTarget.dispatchEvent(se),!se.defaultPrevented){const ue=V().filter(Ae=>Ae.focusable),_e=ue.find(Ae=>Ae.active),we=ue.find(Ae=>Ae.id===P),Me=[_e,we,...ue].filter(Boolean).map(Ae=>Ae.ref.current);Vge(Me,y)}}G.current=!1}),onBlur:Or(t.onBlur,()=>M(!1))})})}),$ge="RovingFocusGroupItem",Uge=I.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:i=!1,tabStopId:o,children:c,...s}=t,f=Dl(),p=o||f,y=O$e($ge,r),_=y.currentTabStopId===p,T=Bge(r),{onFocusableItemAdd:E,onFocusableItemRemove:k,currentTabStopId:P}=y;return I.useEffect(()=>{if(n)return E(),()=>k()},[n,E,k]),a.jsx(sV.ItemSlot,{scope:r,id:p,focusable:n,active:i,children:a.jsx(rn.span,{tabIndex:_?0:-1,"data-orientation":y.orientation,...s,ref:e,onMouseDown:Or(t.onMouseDown,R=>{n?y.onItemFocus(p):R.preventDefault()}),onFocus:Or(t.onFocus,()=>y.onItemFocus(p)),onKeyDown:Or(t.onKeyDown,R=>{if(R.key==="Tab"&&R.shiftKey){y.onItemShiftTab();return}if(R.target!==R.currentTarget)return;const D=$$e(R,y.orientation,y.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=y.loop?U$e(B,V+1):B.slice(V+1)}setTimeout(()=>Vge(B))}}),children:typeof c=="function"?c({isCurrentTabStop:_,hasTabStop:P!=null}):c})})});Uge.displayName=$ge;var B$e={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function z$e(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function $$e(t,e,r){const n=z$e(t.key,r);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return B$e[n]}function Vge(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}function U$e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var G9=zge,H9=Uge,aV=["Enter"," "],V$e=["ArrowDown","PageUp","Home"],qge=["ArrowUp","PageDown","End"],q$e=[...V$e,...qge],G$e={ltr:[...aV,"ArrowRight"],rtl:[...aV,"ArrowLeft"]},H$e={ltr:["ArrowLeft"],rtl:["ArrowRight"]},hC="Menu",[Rj,W$e,K$e]=Zk(hC),[ov,Gge]=Yo(hC,[K$e,mx,VS]),o3=mx(),Hge=VS(),[Y$e,lv]=ov(hC),[Z$e,fC]=ov(hC),Wge=t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:o,modal:c=!0}=t,s=o3(e),[f,p]=I.useState(null),y=I.useRef(!1),_=po(o),T=av(i);return I.useEffect(()=>{const E=()=>{y.current=!0,document.addEventListener("pointerdown",k,{capture:!0,once:!0}),document.addEventListener("pointermove",k,{capture:!0,once:!0})},k=()=>y.current=!1;return document.addEventListener("keydown",E,{capture:!0}),()=>{document.removeEventListener("keydown",E,{capture:!0}),document.removeEventListener("pointerdown",k,{capture:!0}),document.removeEventListener("pointermove",k,{capture:!0})}},[]),a.jsx(qO,{...s,children:a.jsx(Y$e,{scope:e,open:r,onOpenChange:_,content:f,onContentChange:p,children:a.jsx(Z$e,{scope:e,onClose:I.useCallback(()=>_(!1),[_]),isUsingKeyboardRef:y,dir:T,modal:c,children:n})})})};Wge.displayName=hC;var X$e="MenuAnchor",W9=I.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=o3(r);return a.jsx(lC,{...i,...n,ref:e})});W9.displayName=X$e;var K9="MenuPortal",[Q$e,Kge]=ov(K9,{forceMount:void 0}),Yge=t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,o=lv(K9,e);return a.jsx(Q$e,{scope:e,forceMount:r,children:a.jsx(pl,{present:r||o.open,children:a.jsx(jS,{asChild:!0,container:i,children:n})})})};Yge.displayName=K9;var eh="MenuContent",[J$e,Y9]=ov(eh),Zge=I.forwardRef((t,e)=>{const r=Kge(eh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=lv(eh,t.__scopeMenu),c=fC(eh,t.__scopeMenu);return a.jsx(Rj.Provider,{scope:t.__scopeMenu,children:a.jsx(pl,{present:n||o.open,children:a.jsx(Rj.Slot,{scope:t.__scopeMenu,children:c.modal?a.jsx(e6e,{...i,ref:e}):a.jsx(t6e,{...i,ref:e})})})})}),e6e=I.forwardRef((t,e)=>{const r=lv(eh,t.__scopeMenu),n=I.useRef(null),i=Kn(e,n);return I.useEffect(()=>{const o=n.current;if(o)return OO(o)},[]),a.jsx(Z9,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Or(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),t6e=I.forwardRef((t,e)=>{const r=lv(eh,t.__scopeMenu);return a.jsx(Z9,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),r6e=Ky("MenuContent.ScrollLock"),Z9=I.forwardRef((t,e)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:c,disableOutsidePointerEvents:s,onEntryFocus:f,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:_,onInteractOutside:T,onDismiss:E,disableOutsideScroll:k,...P}=t,R=lv(eh,r),D=fC(eh,r),M=o3(r),B=Hge(r),V=W$e(r),[G,W]=I.useState(null),Z=I.useRef(null),Q=Kn(e,Z,R.onContentChange),re=I.useRef(0),se=I.useRef(""),ue=I.useRef(0),_e=I.useRef(null),we=I.useRef("right"),Ce=I.useRef(0),Me=k?rC:I.Fragment,Ae=k?{as:r6e,allowPinchZoom:!0}:void 0,be=Pe=>{var _t,Vt;const Ie=se.current+Pe,Se=V().filter(pt=>!pt.disabled),ve=document.activeElement,We=(_t=Se.find(pt=>pt.ref.current===ve))==null?void 0:_t.textValue,rt=Se.map(pt=>pt.textValue),at=m6e(rt,Ie,We),Et=(Vt=Se.find(pt=>pt.textValue===at))==null?void 0:Vt.ref.current;(function pt(Nt){se.current=Nt,window.clearTimeout(re.current),Nt!==""&&(re.current=window.setTimeout(()=>pt(""),1e3))})(Ie),Et&&setTimeout(()=>Et.focus())};I.useEffect(()=>()=>window.clearTimeout(re.current),[]),DO();const me=I.useCallback(Pe=>{var Se,ve;return we.current===((Se=_e.current)==null?void 0:Se.side)&&g6e(Pe,(ve=_e.current)==null?void 0:ve.area)},[]);return a.jsx(J$e,{scope:r,searchRef:se,onItemEnter:I.useCallback(Pe=>{me(Pe)&&Pe.preventDefault()},[me]),onItemLeave:I.useCallback(Pe=>{var Ie;me(Pe)||((Ie=Z.current)==null||Ie.focus(),W(null))},[me]),onTriggerLeave:I.useCallback(Pe=>{me(Pe)&&Pe.preventDefault()},[me]),pointerGraceTimerRef:ue,onPointerGraceIntentChange:I.useCallback(Pe=>{_e.current=Pe},[]),children:a.jsx(Me,{...Ae,children:a.jsx(tC,{asChild:!0,trapped:i,onMountAutoFocus:Or(o,Pe=>{var Ie;Pe.preventDefault(),(Ie=Z.current)==null||Ie.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:a.jsx(rv,{asChild:!0,disableOutsidePointerEvents:s,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:_,onInteractOutside:T,onDismiss:E,children:a.jsx(G9,{asChild:!0,...B,dir:D.dir,orientation:"vertical",loop:n,currentTabStopId:G,onCurrentTabStopIdChange:W,onEntryFocus:Or(f,Pe=>{D.isUsingKeyboardRef.current||Pe.preventDefault()}),preventScrollOnEntryFocus:!0,children:a.jsx(GO,{role:"menu","aria-orientation":"vertical","data-state":hye(R.open),"data-radix-menu-content":"",dir:D.dir,...M,...P,ref:Q,style:{outline:"none",...P.style},onKeyDown:Or(P.onKeyDown,Pe=>{const Se=Pe.target.closest("[data-radix-menu-content]")===Pe.currentTarget,ve=Pe.ctrlKey||Pe.altKey||Pe.metaKey,We=Pe.key.length===1;Se&&(Pe.key==="Tab"&&Pe.preventDefault(),!ve&&We&&be(Pe.key));const rt=Z.current;if(Pe.target!==rt||!q$e.includes(Pe.key))return;Pe.preventDefault();const Et=V().filter(_t=>!_t.disabled).map(_t=>_t.ref.current);qge.includes(Pe.key)&&Et.reverse(),h6e(Et)}),onBlur:Or(t.onBlur,Pe=>{Pe.currentTarget.contains(Pe.target)||(window.clearTimeout(re.current),se.current="")}),onPointerMove:Or(t.onPointerMove,Lj(Pe=>{const Ie=Pe.target,Se=Ce.current!==Pe.clientX;if(Pe.currentTarget.contains(Ie)&&Se){const ve=Pe.clientX>Ce.current?"right":"left";we.current=ve,Ce.current=Pe.clientX}}))})})})})})})});Zge.displayName=eh;var n6e="MenuGroup",X9=I.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return a.jsx(rn.div,{role:"group",...n,ref:e})});X9.displayName=n6e;var i6e="MenuLabel",Xge=I.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return a.jsx(rn.div,{...n,ref:e})});Xge.displayName=i6e;var ED="MenuItem",Ate="menu.itemSelect",l3=I.forwardRef((t,e)=>{const{disabled:r=!1,onSelect:n,...i}=t,o=I.useRef(null),c=fC(ED,t.__scopeMenu),s=Y9(ED,t.__scopeMenu),f=Kn(e,o),p=I.useRef(!1),y=()=>{const _=o.current;if(!r&&_){const T=new CustomEvent(Ate,{bubbles:!0,cancelable:!0});_.addEventListener(Ate,E=>n==null?void 0:n(E),{once:!0}),XG(_,T),T.defaultPrevented?p.current=!1:c.onClose()}};return a.jsx(Qge,{...i,ref:f,disabled:r,onClick:Or(t.onClick,y),onPointerDown:_=>{var T;(T=t.onPointerDown)==null||T.call(t,_),p.current=!0},onPointerUp:Or(t.onPointerUp,_=>{var T;p.current||(T=_.currentTarget)==null||T.click()}),onKeyDown:Or(t.onKeyDown,_=>{const T=s.searchRef.current!=="";r||T&&_.key===" "||aV.includes(_.key)&&(_.currentTarget.click(),_.preventDefault())})})});l3.displayName=ED;var Qge=I.forwardRef((t,e)=>{const{__scopeMenu:r,disabled:n=!1,textValue:i,...o}=t,c=Y9(ED,r),s=Hge(r),f=I.useRef(null),p=Kn(e,f),[y,_]=I.useState(!1),[T,E]=I.useState("");return I.useEffect(()=>{const k=f.current;k&&E((k.textContent??"").trim())},[o.children]),a.jsx(Rj.ItemSlot,{scope:r,disabled:n,textValue:i??T,children:a.jsx(H9,{asChild:!0,...s,focusable:!n,children:a.jsx(rn.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:p,onPointerMove:Or(t.onPointerMove,Lj(k=>{n?c.onItemLeave(k):(c.onItemEnter(k),k.defaultPrevented||k.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Or(t.onPointerLeave,Lj(k=>c.onItemLeave(k))),onFocus:Or(t.onFocus,()=>_(!0)),onBlur:Or(t.onBlur,()=>_(!1))})})})}),s6e="MenuCheckboxItem",Jge=I.forwardRef((t,e)=>{const{checked:r=!1,onCheckedChange:n,...i}=t;return a.jsx(iye,{scope:t.__scopeMenu,checked:r,children:a.jsx(l3,{role:"menuitemcheckbox","aria-checked":AD(r)?"mixed":r,...i,ref:e,"data-state":J9(r),onSelect:Or(i.onSelect,()=>n==null?void 0:n(AD(r)?!0:!r),{checkForDefaultPrevented:!1})})})});Jge.displayName=s6e;var eye="MenuRadioGroup",[a6e,o6e]=ov(eye,{value:void 0,onValueChange:()=>{}}),tye=I.forwardRef((t,e)=>{const{value:r,onValueChange:n,...i}=t,o=po(n);return a.jsx(a6e,{scope:t.__scopeMenu,value:r,onValueChange:o,children:a.jsx(X9,{...i,ref:e})})});tye.displayName=eye;var rye="MenuRadioItem",nye=I.forwardRef((t,e)=>{const{value:r,...n}=t,i=o6e(rye,t.__scopeMenu),o=r===i.value;return a.jsx(iye,{scope:t.__scopeMenu,checked:o,children:a.jsx(l3,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":J9(o),onSelect:Or(n.onSelect,()=>{var c;return(c=i.onValueChange)==null?void 0:c.call(i,r)},{checkForDefaultPrevented:!1})})})});nye.displayName=rye;var Q9="MenuItemIndicator",[iye,l6e]=ov(Q9,{checked:!1}),sye=I.forwardRef((t,e)=>{const{__scopeMenu:r,forceMount:n,...i}=t,o=l6e(Q9,r);return a.jsx(pl,{present:n||AD(o.checked)||o.checked===!0,children:a.jsx(rn.span,{...i,ref:e,"data-state":J9(o.checked)})})});sye.displayName=Q9;var c6e="MenuSeparator",aye=I.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return a.jsx(rn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});aye.displayName=c6e;var u6e="MenuArrow",oye=I.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=o3(r);return a.jsx(HO,{...i,...n,ref:e})});oye.displayName=u6e;var d6e="MenuSub",[BVt,lye]=ov(d6e),gA="MenuSubTrigger",cye=I.forwardRef((t,e)=>{const r=lv(gA,t.__scopeMenu),n=fC(gA,t.__scopeMenu),i=lye(gA,t.__scopeMenu),o=Y9(gA,t.__scopeMenu),c=I.useRef(null),{pointerGraceTimerRef:s,onPointerGraceIntentChange:f}=o,p={__scopeMenu:t.__scopeMenu},y=I.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return I.useEffect(()=>y,[y]),I.useEffect(()=>{const _=s.current;return()=>{window.clearTimeout(_),f(null)}},[s,f]),a.jsx(W9,{asChild:!0,...p,children:a.jsx(Qge,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":hye(r.open),...t,ref:Fp(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,Lj(_=>{o.onItemEnter(_),!_.defaultPrevented&&!t.disabled&&!r.open&&!c.current&&(o.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{r.onOpenChange(!0),y()},100))})),onPointerLeave:Or(t.onPointerLeave,Lj(_=>{var E,k;y();const T=(E=r.content)==null?void 0:E.getBoundingClientRect();if(T){const P=(k=r.content)==null?void 0:k.dataset.side,R=P==="right",D=R?-5:5,M=T[R?"left":"right"],B=T[R?"right":"left"];o.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:P}),window.clearTimeout(s.current),s.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(_),_.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Or(t.onKeyDown,_=>{var E;const T=o.searchRef.current!=="";t.disabled||T&&_.key===" "||G$e[n.dir].includes(_.key)&&(r.onOpenChange(!0),(E=r.content)==null||E.focus(),_.preventDefault())})})})});cye.displayName=gA;var uye="MenuSubContent",dye=I.forwardRef((t,e)=>{const r=Kge(eh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=lv(eh,t.__scopeMenu),c=fC(eh,t.__scopeMenu),s=lye(uye,t.__scopeMenu),f=I.useRef(null),p=Kn(e,f);return a.jsx(Rj.Provider,{scope:t.__scopeMenu,children:a.jsx(pl,{present:n||o.open,children:a.jsx(Rj.Slot,{scope:t.__scopeMenu,children:a.jsx(Z9,{id:s.contentId,"aria-labelledby":s.triggerId,...i,ref:p,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:y=>{var _;c.isUsingKeyboardRef.current&&((_=f.current)==null||_.focus()),y.preventDefault()},onCloseAutoFocus:y=>y.preventDefault(),onFocusOutside:Or(t.onFocusOutside,y=>{y.target!==s.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Or(t.onEscapeKeyDown,y=>{c.onClose(),y.preventDefault()}),onKeyDown:Or(t.onKeyDown,y=>{var E;const _=y.currentTarget.contains(y.target),T=H$e[c.dir].includes(y.key);_&&T&&(o.onOpenChange(!1),(E=s.trigger)==null||E.focus(),y.preventDefault())})})})})})});dye.displayName=uye;function hye(t){return t?"open":"closed"}function AD(t){return t==="indeterminate"}function J9(t){return AD(t)?"indeterminate":t?"checked":"unchecked"}function h6e(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}function f6e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}function m6e(t,e,r){const i=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=f6e(t,Math.max(o,0));i.length===1&&(c=c.filter(p=>p!==r));const f=c.find(p=>p.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function p6e(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=T>n&&r<(_-p)*(n-y)/(T-y)+p&&(i=!i)}return i}function g6e(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return p6e(r,e)}function Lj(t){return e=>e.pointerType==="mouse"?t(e):void 0}var y6e=Wge,x6e=W9,_6e=Yge,v6e=Zge,b6e=X9,w6e=Xge,S6e=l3,T6e=Jge,E6e=tye,A6e=nye,j6e=sye,k6e=aye,C6e=oye,I6e=cye,N6e=dye,c3="DropdownMenu",[P6e,zVt]=Yo(c3,[Gge]),su=Gge(),[R6e,fye]=P6e(c3),mye=t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:o,onOpenChange:c,modal:s=!0}=t,f=su(e),p=I.useRef(null),[y,_]=dd({prop:i,defaultProp:o??!1,onChange:c,caller:c3});return a.jsx(R6e,{scope:e,triggerId:Dl(),triggerRef:p,contentId:Dl(),open:y,onOpenChange:_,onOpenToggle:I.useCallback(()=>_(T=>!T),[_]),modal:s,children:a.jsx(y6e,{...f,open:y,onOpenChange:_,dir:n,modal:s,children:r})})};mye.displayName=c3;var pye="DropdownMenuTrigger",gye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...i}=t,o=fye(pye,r),c=su(r);return a.jsx(x6e,{asChild:!0,...c,children:a.jsx(rn.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...i,ref:Fp(e,o.triggerRef),onPointerDown:Or(t.onPointerDown,s=>{!n&&s.button===0&&s.ctrlKey===!1&&(o.onOpenToggle(),o.open||s.preventDefault())}),onKeyDown:Or(t.onKeyDown,s=>{n||(["Enter"," "].includes(s.key)&&o.onOpenToggle(),s.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(s.key)&&s.preventDefault())})})})});gye.displayName=pye;var L6e="DropdownMenuPortal",yye=t=>{const{__scopeDropdownMenu:e,...r}=t,n=su(e);return a.jsx(_6e,{...n,...r})};yye.displayName=L6e;var xye="DropdownMenuContent",_ye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=fye(xye,r),o=su(r),c=I.useRef(!1);return a.jsx(v6e,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...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,p=f.button===0&&f.ctrlKey===!0,y=f.button===2||p;(!i.modal||y)&&(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)"}})});_ye.displayName=xye;var D6e="DropdownMenuGroup",M6e=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(b6e,{...i,...n,ref:e})});M6e.displayName=D6e;var O6e="DropdownMenuLabel",vye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(w6e,{...i,...n,ref:e})});vye.displayName=O6e;var F6e="DropdownMenuItem",bye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(S6e,{...i,...n,ref:e})});bye.displayName=F6e;var B6e="DropdownMenuCheckboxItem",wye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(T6e,{...i,...n,ref:e})});wye.displayName=B6e;var z6e="DropdownMenuRadioGroup",$6e=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(E6e,{...i,...n,ref:e})});$6e.displayName=z6e;var U6e="DropdownMenuRadioItem",Sye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(A6e,{...i,...n,ref:e})});Sye.displayName=U6e;var V6e="DropdownMenuItemIndicator",Tye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(j6e,{...i,...n,ref:e})});Tye.displayName=V6e;var q6e="DropdownMenuSeparator",Eye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(k6e,{...i,...n,ref:e})});Eye.displayName=q6e;var G6e="DropdownMenuArrow",H6e=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(C6e,{...i,...n,ref:e})});H6e.displayName=G6e;var W6e="DropdownMenuSubTrigger",Aye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(I6e,{...i,...n,ref:e})});Aye.displayName=W6e;var K6e="DropdownMenuSubContent",jye=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=su(r);return a.jsx(N6e,{...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)"}})});jye.displayName=K6e;var Y6e=mye,Z6e=gye,X6e=yye,kye=_ye,Cye=vye,Iye=bye,Nye=wye,Pye=Sye,Rye=Tye,Lye=Eye,Dye=Aye,Mye=jye;const mC=Y6e,pC=Z6e,Q6e=I.forwardRef(({className:t,inset:e,children:r,...n},i)=>a.jsxs(Dye,{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,a.jsx(vd,{className:"ml-auto h-4 w-4"})]}));Q6e.displayName=Dye.displayName;const J6e=I.forwardRef(({className:t,...e},r)=>a.jsx(Mye,{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}));J6e.displayName=Mye.displayName;const qS=I.forwardRef(({className:t,sideOffset:e=4,...r},n)=>a.jsx(X6e,{children:a.jsx(kye,{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})}));qS.displayName=kye.displayName;const Eu=I.forwardRef(({className:t,inset:e,...r},n)=>a.jsx(Iye,{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}));Eu.displayName=Iye.displayName;const eUe=I.forwardRef(({className:t,children:e,checked:r,...n},i)=>a.jsxs(Nye,{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:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(Rye,{children:a.jsx(ko,{className:"h-4 w-4"})})}),e]}));eUe.displayName=Nye.displayName;const tUe=I.forwardRef(({className:t,children:e,...r},n)=>a.jsxs(Pye,{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:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(Rye,{children:a.jsx(F_,{className:"h-2 w-2 fill-current"})})}),e]}));tUe.displayName=Pye.displayName;const Oye=I.forwardRef(({className:t,inset:e,...r},n)=>a.jsx(Cye,{ref:n,className:sr("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));Oye.displayName=Cye.displayName;const Dj=I.forwardRef(({className:t,...e},r)=>a.jsx(Lye,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...e}));Dj.displayName=Lye.displayName;const rUe=()=>{const{isAssistant:t,actingAsAgent:e,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:i,setActingAsSelf:o}=a3();if(!t)return null;const c=s=>s.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return a.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:a.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4 h-full",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[i?a.jsxs(a.Fragment,{children:[a.jsx(vc,{className:"h-4 w-4 flex-shrink-0"}),a.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):a.jsxs(a.Fragment,{children:[a.jsx(ul,{className:"h-4 w-4 flex-shrink-0"}),a.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),a.jsxs(mC,{children:[a.jsx(pC,{asChild:!0,children:a.jsxs(zt,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[i?a.jsxs(a.Fragment,{children:[a.jsx(vc,{className:"h-4 w-4"}),a.jsx("strong",{children:"My Account"})]}):e?a.jsxs(a.Fragment,{children:[a.jsxs(fd,{className:"h-5 w-5",children:[a.jsx(md,{src:e.avatar_url||void 0}),a.jsx(pd,{className:"text-[10px] bg-primary-foreground/30",children:c(e.name)})]}),a.jsx("strong",{children:e.name})]}):a.jsx("strong",{children:"Select..."}),a.jsx(wc,{className:"h-3 w-3"})]})}),a.jsxs(qS,{align:"start",className:"z-[2147483647]",children:[a.jsxs(Eu,{onClick:o,className:"gap-2",children:[a.jsx(vc,{className:"h-4 w-4"}),a.jsx("span",{children:"My Account"}),i&&a.jsx(us,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),a.jsx(Dj,{}),r.map(s=>a.jsxs(Eu,{onClick:()=>n(s),className:"gap-2",children:[a.jsxs(fd,{className:"h-6 w-6",children:[a.jsx(md,{src:s.avatar_url||void 0}),a.jsx(pd,{className:"text-[10px]",children:c(s.name)})]}),a.jsx("span",{children:s.name}),!i&&s.id===(e==null?void 0:e.id)&&a.jsx(us,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},s.id))]})]})]}),a.jsx(us,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:i?"Personal Mode":"Assistant Mode"})]})})};function Fye(){var f,p;const{user:t,isAdmin:e}=Gn(),{data:r,isLoading:n}=gr({queryKey:["partnership-membership",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:y}=await Re.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",t.id).eq("status","active").maybeSingle();if(!y)return null;const[{data:_},{data:T}]=await Promise.all([Re.from("partnership_packages").select("*").eq("id",y.package_id).maybeSingle(),Re.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",y.program_id).maybeSingle()]);return!_||!(T!=null&&T.enabled)?null:{membership:y,pkg:_,program:T}}}),i=I.useMemo(()=>{var y;return new Set(((y=r==null?void 0:r.pkg)==null?void 0:y.included_features)||[])},[r]),o=!!r,c=y=>e||!o?!0:i.has(y),s=y=>{var E,k;const _=((E=r==null?void 0:r.pkg)==null?void 0:E.feature_limits)||{},T=(k=_==null?void 0:_[y])==null?void 0:k.monthly_limit;return typeof T=="number"?T:null};return{isLoading:n,isMember:o,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:((p=r==null?void 0:r.pkg)==null?void 0:p.name)??null,features:i,hasFeature:c,limitFor:s,isRestricted:o&&!e}}const e7={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"},$Vt=Object.keys(e7),nUe={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},jte={"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"},iUe={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 sUe(t){return t.id in jte?jte[t.id]:nUe[t.primaryCategory]??null}function UVt(t){return iUe[t]??null}const aUe=[["/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 oUe(t){let e=null;for(const r of aUe){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 Wn=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{ref:r,className:sr("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Wn.displayName="Card";const id=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{ref:r,className:sr("flex flex-col space-y-1.5 p-6",t),...e}));id.displayName="CardHeader";const sd=I.forwardRef(({className:t,...e},r)=>a.jsx("h3",{ref:r,className:sr("text-2xl font-semibold leading-none tracking-tight",t),...e}));sd.displayName="CardTitle";const Mj=I.forwardRef(({className:t,...e},r)=>a.jsx("p",{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));Mj.displayName="CardDescription";const si=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{ref:r,className:sr("p-6 pt-0",t),...e}));si.displayName="CardContent";const oV=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{ref:r,className:sr("flex items-center p-6 pt-0",t),...e}));oV.displayName="CardFooter";const bd=I.forwardRef(({className:t,...e},r)=>a.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}));bd.displayName="Textarea";const io=BO,Bye=p9,lUe=zO,VVt=sC,zye=I.forwardRef(({className:t,...e},r)=>a.jsx(LS,{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}));zye.displayName=LS.displayName;const Ua=I.forwardRef(({className:t,children:e,overlayClassName:r,...n},i)=>a.jsxs(lUe,{children:[a.jsx(zye,{className:r}),a.jsxs(DS,{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,a.jsxs(sC,{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:[a.jsx(Ds,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ua.displayName=DS.displayName;const ml=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});ml.displayName="DialogHeader";const $ye=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});$ye.displayName="DialogFooter";const Ko=I.forwardRef(({className:t,...e},r)=>a.jsx(nC,{ref:r,className:sr("text-lg font-semibold leading-none tracking-tight",t),...e}));Ko.displayName=nC.displayName;const gd=I.forwardRef(({className:t,...e},r)=>a.jsx(iC,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));gd.displayName=iC.displayName;function cUe({featureKey:t,open:e,onOpenChange:r}){const{user:n}=Gn(),i=Nr(),[o,c]=I.useState(""),{data:s}=gr({queryKey:["partnership-upgrade-requests",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&e,queryFn:async()=>{const{data:_}=await Re.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")),p=kr({mutationFn:async()=>{const{error:_}=await Re.from("lead_site_upgrade_requests").insert({user_id:n.id,feature_key:t,notes:o||null});if(_)throw _},onSuccess:()=>{i.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),Gt.success("Request sent — we'll be in touch shortly."),c(""),r(!1)},onError:_=>Gt.error((_==null?void 0:_.message)||"Could not send your request")}),y=e7[t]||t;return a.jsx(io,{open:e,onOpenChange:r,children:a.jsxs(Ua,{className:"sm:max-w-md",children:[a.jsxs(ml,{children:[a.jsxs(Ko,{className:"flex items-center gap-2",children:[a.jsx(xs,{className:"h-5 w-5 text-primary"}),"Request ",y]}),a.jsxs(gd,{children:[y," is included with the Signature package. Send a request and we'll get you set up."]})]}),f?a.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[a.jsx(ko,{className:"h-4 w-4 mt-0.5 text-primary"}),a.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):a.jsx(bd,{placeholder:"Anything we should know? (optional)",value:o,onChange:_=>c(_.target.value),rows:4}),a.jsxs($ye,{children:[a.jsx(zt,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!f&&a.jsx(zt,{onClick:()=>p.mutate(),disabled:p.isPending,children:p.isPending?"Sending…":"Send request"})]})]})})}function uUe({featureKey:t}){const[e,r]=I.useState(!1),n=e7[t]||t;return a.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[a.jsx(Wn,{className:"max-w-lg w-full border-border/60",children:a.jsxs(si,{className:"p-8 text-center space-y-4",children:[a.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:a.jsx(Zy,{className:"h-6 w-6 text-primary"})}),a.jsxs("h2",{className:"text-2xl font-semibold",children:[n," is a Signature feature"]}),a.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",n,". Request access and our team will upgrade your account."]}),a.jsxs(zt,{onClick:()=>r(!0),className:"gap-2",children:[a.jsx(xs,{className:"h-4 w-4"})," Request access"]})]})}),a.jsx(cUe,{featureKey:t,open:e,onOpenChange:r})]})}const dUe=t=>{const[e,r]=I.useState(null),[n,i]=I.useState(!0);return I.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:s}=await Re.storage.from("avatars").list(`${t}`);if(s&&s.length>0){const{data:f}=Re.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 Re.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:s}=Re.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${s.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},qVt=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await Re.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=Re.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},hUe=t=>{const[e,r]=I.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return I.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:o}=await Re.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",t).single();if(o){console.error("Error fetching trial status:",o),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",p=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)&&!!p&&p){const _=new Date().getTime(),T=new Date(p).getTime(),E=Math.ceil((T-_)/(1e3*60*60*24)),k=E<=0;r({isTrial:!0,isExpired:k,expiresAt:p,daysLeft:k?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(o=>({...o,loading:!1}))}})()},[t]),e},u3=()=>{const{data:t,isLoading:e}=gr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await Re.from("feature_flags").select("*");if(i)throw i;return n}}),r=n=>{if(!t)return!1;const i=t.find(o=>o.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")}},kte="community_last_seen_post_at";function fUe(){const{user:t}=Gn(),e=Bi(),[r,n]=I.useState(0),[i,o]=I.useState(null);I.useEffect(()=>{if(!t)return;const s=localStorage.getItem(`${kte}_${t.id}`);o(s)},[t]),I.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 k=JSON.parse(E);if(k.ts&&Date.now()-k.ts{if(!t)return;const s=Re.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async f=>{const p=f.new;if(p.user_id===t.id)return;const y=e.pathname==="/community";y||n(P=>P+1);const{data:_}=await Re.from("profiles").select("name").eq("id",p.user_id).single(),T=(_==null?void 0:_.name)||"Someone",E=p.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),k=E.length>50?E.substring(0,50)+"...":E;y||Gt("New Community Post",{description:`${T}: ${k}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{Re.removeChannel(s)}},[t,e.pathname]);const c=I.useCallback(()=>{if(!t)return;const s=new Date().toISOString();localStorage.setItem(`${kte}_${t.id}`,s),o(s),n(0)},[t]);return I.useEffect(()=>{e.pathname==="/community"&&r>0&&c()},[e.pathname,r,c]),{unreadCount:r,markAsRead:c}}function mUe(){const{isAdmin:t}=Gn(),{data:e=0}=gr({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await Re.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 fz=t=>`levelup:activeTeam:${t}`,pUe=()=>{const t=Gi();return gr({queryKey:["user-teams",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 Re.from("teams").select("*").in("id",e.map(c=>c.team_id));if(i)throw i;const o=new Map((n||[]).map(c=>[c.id,c]));return e.filter(c=>o.has(c.team_id)).map(c=>({membershipId:c.id,teamId:c.team_id,role:c.role,team:o.get(c.team_id)})).sort((c,s)=>{var f,p;return c.role!==s.role?c.role==="team_leader"?-1:1:(((f=c.team)==null?void 0:f.name)||"").localeCompare(((p=s.team)==null?void 0:p.name)||"")})},enabled:!!t,staleTime:5*60*1e3})},GS=()=>{const t=Gi(),e=pUe(),r=I.useMemo(()=>e.data||[],[e.data]),[n,i]=I.useState(()=>!t||typeof window>"u"?null:window.localStorage.getItem(fz(t)));I.useEffect(()=>{!t||typeof window>"u"||i(window.localStorage.getItem(fz(t)))},[t]);const o=I.useCallback(s=>{i(s),t&&typeof window<"u"&&window.localStorage.setItem(fz(t),s)},[t]),c=I.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:o}},Cte="weekly_reels";function t7(){const{user:t,loading:e,isAdmin:r}=Gn(),{data:n,isLoading:i}=gr({queryKey:["feature-entitlement",Cte,t==null?void 0:t.id],enabled:!!t&&!r,staleTime:5*60*1e3,queryFn:async()=>{const{data:o,error:c}=await Re.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key",Cte).maybeSingle();if(c)throw c;return o?{hasAccess:o.enabled&&(!o.expires_at||new Date(o.expires_at).getTime()>Date.now()),tier:o.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 Uye=BO,gUe=p9,yUe=zO,Vye=I.forwardRef(({className:t,...e},r)=>a.jsx(LS,{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}));Vye.displayName=LS.displayName;const xUe=kS("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"}}),r7=I.forwardRef(({side:t="right",className:e,children:r,...n},i)=>a.jsxs(yUe,{children:[a.jsx(Vye,{}),a.jsxs(DS,{ref:i,className:sr(xUe({side:t}),e),...n,children:[r,a.jsxs(sC,{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:[a.jsx(Ds,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));r7.displayName=DS.displayName;const qye=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col space-y-2 text-center sm:text-left",t),...e});qye.displayName="SheetHeader";const _Ue=({className:t,...e})=>a.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});_Ue.displayName="SheetFooter";const Gye=I.forwardRef(({className:t,...e},r)=>a.jsx(nC,{ref:r,className:sr("text-lg font-semibold text-foreground",t),...e}));Gye.displayName=nC.displayName;const Hye=I.forwardRef(({className:t,...e},r)=>a.jsx(iC,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));Hye.displayName=iC.displayName;function Oj(t,[e,r]){return Math.min(r,Math.max(e,t))}function vUe(t,e){return I.useReducer((r,n)=>e[r][n]??r,t)}var n7="ScrollArea",[Wye,GVt]=Yo(n7),[bUe,lh]=Wye(n7),Kye=I.forwardRef((t,e)=>{const{__scopeScrollArea:r,type:n="hover",dir:i,scrollHideDelay:o=600,...c}=t,[s,f]=I.useState(null),[p,y]=I.useState(null),[_,T]=I.useState(null),[E,k]=I.useState(null),[P,R]=I.useState(null),[D,M]=I.useState(0),[B,V]=I.useState(0),[G,W]=I.useState(!1),[Z,Q]=I.useState(!1),re=Kn(e,ue=>f(ue)),se=av(i);return a.jsx(bUe,{scope:r,type:n,dir:se,scrollHideDelay:o,scrollArea:s,viewport:p,onViewportChange:y,content:_,onContentChange:T,scrollbarX:E,onScrollbarXChange:k,scrollbarXEnabled:G,onScrollbarXEnabledChange:W,scrollbarY:P,onScrollbarYChange:R,scrollbarYEnabled:Z,onScrollbarYEnabledChange:Q,onCornerWidthChange:M,onCornerHeightChange:V,children:a.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}})})});Kye.displayName=n7;var Yye="ScrollAreaViewport",Zye=I.forwardRef((t,e)=>{const{__scopeScrollArea:r,children:n,nonce:i,...o}=t,c=lh(Yye,r),s=I.useRef(null),f=Kn(e,s,c.onViewportChange);return a.jsxs(a.Fragment,{children:[a.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}),a.jsx(rn.div,{"data-radix-scroll-area-viewport":"",...o,ref:f,style:{overflowX:c.scrollbarXEnabled?"scroll":"hidden",overflowY:c.scrollbarYEnabled?"scroll":"hidden",...t.style},children:a.jsx("div",{ref:c.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});Zye.displayName=Yye;var wm="ScrollAreaScrollbar",i7=I.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=lh(wm,t.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:c}=i,s=t.orientation==="horizontal";return I.useEffect(()=>(s?o(!0):c(!0),()=>{s?o(!1):c(!1)}),[s,o,c]),i.type==="hover"?a.jsx(wUe,{...n,ref:e,forceMount:r}):i.type==="scroll"?a.jsx(SUe,{...n,ref:e,forceMount:r}):i.type==="auto"?a.jsx(Xye,{...n,ref:e,forceMount:r}):i.type==="always"?a.jsx(s7,{...n,ref:e}):null});i7.displayName=wm;var wUe=I.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=lh(wm,t.__scopeScrollArea),[o,c]=I.useState(!1);return I.useEffect(()=>{const s=i.scrollArea;let f=0;if(s){const p=()=>{window.clearTimeout(f),c(!0)},y=()=>{f=window.setTimeout(()=>c(!1),i.scrollHideDelay)};return s.addEventListener("pointerenter",p),s.addEventListener("pointerleave",y),()=>{window.clearTimeout(f),s.removeEventListener("pointerenter",p),s.removeEventListener("pointerleave",y)}}},[i.scrollArea,i.scrollHideDelay]),a.jsx(pl,{present:r||o,children:a.jsx(Xye,{"data-state":o?"visible":"hidden",...n,ref:e})})}),SUe=I.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=lh(wm,t.__scopeScrollArea),o=t.orientation==="horizontal",c=h3(()=>f("SCROLL_END"),100),[s,f]=vUe("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 I.useEffect(()=>{if(s==="idle"){const p=window.setTimeout(()=>f("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(p)}},[s,i.scrollHideDelay,f]),I.useEffect(()=>{const p=i.viewport,y=o?"scrollLeft":"scrollTop";if(p){let _=p[y];const T=()=>{const E=p[y];_!==E&&(f("SCROLL"),c()),_=E};return p.addEventListener("scroll",T),()=>p.removeEventListener("scroll",T)}},[i.viewport,o,f,c]),a.jsx(pl,{present:r||s!=="hidden",children:a.jsx(s7,{"data-state":s==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Or(t.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:Or(t.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),Xye=I.forwardRef((t,e)=>{const r=lh(wm,t.__scopeScrollArea),{forceMount:n,...i}=t,[o,c]=I.useState(!1),s=t.orientation==="horizontal",f=h3(()=>{if(r.viewport){const p=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=t,i=lh(wm,t.__scopeScrollArea),o=I.useRef(null),c=I.useRef(0),[s,f]=I.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),p=rxe(s.viewport,s.content),y={...n,sizes:s,onSizesChange:f,hasThumb:p>0&&p<1,onThumbChange:T=>o.current=T,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:T=>c.current=T};function _(T,E){return CUe(T,c.current,s,E)}return r==="horizontal"?a.jsx(TUe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const T=i.viewport.scrollLeft,E=Ite(T,s,i.dir);o.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"?a.jsx(EUe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const T=i.viewport.scrollTop,E=Ite(T,s);o.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}),TUe=I.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=lh(wm,t.__scopeScrollArea),[c,s]=I.useState(),f=I.useRef(null),p=Kn(e,f,o.onScrollbarXChange);return I.useEffect(()=>{f.current&&s(getComputedStyle(f.current))},[f]),a.jsx(Jye,{"data-orientation":"horizontal",...i,ref:p,sizes:r,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":d3(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.x),onDragScroll:y=>t.onDragScroll(y.x),onWheelScroll:(y,_)=>{if(o.viewport){const T=o.viewport.scrollLeft+y.deltaX;t.onWheelScroll(T),ixe(T,_)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:kD(c.paddingLeft),paddingEnd:kD(c.paddingRight)}})}})}),EUe=I.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=lh(wm,t.__scopeScrollArea),[c,s]=I.useState(),f=I.useRef(null),p=Kn(e,f,o.onScrollbarYChange);return I.useEffect(()=>{f.current&&s(getComputedStyle(f.current))},[f]),a.jsx(Jye,{"data-orientation":"vertical",...i,ref:p,sizes:r,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":d3(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.y),onDragScroll:y=>t.onDragScroll(y.y),onWheelScroll:(y,_)=>{if(o.viewport){const T=o.viewport.scrollTop+y.deltaY;t.onWheelScroll(T),ixe(T,_)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:kD(c.paddingTop),paddingEnd:kD(c.paddingBottom)}})}})}),[AUe,Qye]=Wye(wm),Jye=I.forwardRef((t,e)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:c,onThumbPointerDown:s,onThumbPositionChange:f,onDragScroll:p,onWheelScroll:y,onResize:_,...T}=t,E=lh(wm,r),[k,P]=I.useState(null),R=Kn(e,re=>P(re)),D=I.useRef(null),M=I.useRef(""),B=E.viewport,V=n.content-n.viewport,G=po(y),W=po(f),Z=h3(_,10);function Q(re){if(D.current){const se=re.clientX-D.current.left,ue=re.clientY-D.current.top;p({x:se,y:ue})}}return I.useEffect(()=>{const re=se=>{const ue=se.target;(k==null?void 0:k.contains(ue))&&G(se,V)};return document.addEventListener("wheel",re,{passive:!1}),()=>document.removeEventListener("wheel",re,{passive:!1})},[B,k,V,G]),I.useEffect(W,[n,W]),B1(k,Z),B1(E.content,Z),a.jsx(AUe,{scope:r,scrollbar:k,hasThumb:i,onThumbChange:po(o),onThumbPointerUp:po(c),onThumbPositionChange:W,onThumbPointerDown:po(s),children:a.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=k.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})})})}),jD="ScrollAreaThumb",exe=I.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=Qye(jD,t.__scopeScrollArea);return a.jsx(pl,{present:r||i.hasThumb,children:a.jsx(jUe,{ref:e,...n})})}),jUe=I.forwardRef((t,e)=>{const{__scopeScrollArea:r,style:n,...i}=t,o=lh(jD,r),c=Qye(jD,r),{onThumbPositionChange:s}=c,f=Kn(e,_=>c.onThumbChange(_)),p=I.useRef(void 0),y=h3(()=>{p.current&&(p.current(),p.current=void 0)},100);return I.useEffect(()=>{const _=o.viewport;if(_){const T=()=>{if(y(),!p.current){const E=IUe(_,s);p.current=E,s()}};return s(),_.addEventListener("scroll",T),()=>_.removeEventListener("scroll",T)}},[o.viewport,y,s]),a.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(),k=_.clientX-E.left,P=_.clientY-E.top;c.onThumbPointerDown({x:k,y:P})}),onPointerUp:Or(t.onPointerUp,c.onThumbPointerUp)})});exe.displayName=jD;var a7="ScrollAreaCorner",txe=I.forwardRef((t,e)=>{const r=lh(a7,t.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?a.jsx(kUe,{...t,ref:e}):null});txe.displayName=a7;var kUe=I.forwardRef((t,e)=>{const{__scopeScrollArea:r,...n}=t,i=lh(a7,r),[o,c]=I.useState(0),[s,f]=I.useState(0),p=!!(o&&s);return B1(i.scrollbarX,()=>{var _;const y=((_=i.scrollbarX)==null?void 0:_.offsetHeight)||0;i.onCornerHeightChange(y),f(y)}),B1(i.scrollbarY,()=>{var _;const y=((_=i.scrollbarY)==null?void 0:_.offsetWidth)||0;i.onCornerWidthChange(y),c(y)}),p?a.jsx(rn.div,{...n,ref:e,style:{width:o,height:s,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function kD(t){return t?parseInt(t,10):0}function rxe(t,e){const r=t/e;return isNaN(r)?0:r}function d3(t){const e=rxe(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}function CUe(t,e,r,n="ltr"){const i=d3(r),o=i/2,c=e||o,s=i-c,f=r.scrollbar.paddingStart+c,p=r.scrollbar.size-r.scrollbar.paddingEnd-s,y=r.content-r.viewport,_=n==="ltr"?[0,y]:[y*-1,0];return nxe([f,p],_)(t)}function Ite(t,e,r="ltr"){const n=d3(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=e.scrollbar.size-i,c=e.content-e.viewport,s=o-n,f=r==="ltr"?[0,c]:[c*-1,0],p=Oj(t,f);return nxe([0,c],[0,s])(p)}function nxe(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 ixe(t,e){return t>0&&t{})=>{let r={left:t.scrollLeft,top:t.scrollTop},n=0;return function i(){const o={left:t.scrollLeft,top:t.scrollTop},c=r.left!==o.left,s=r.top!==o.top;(c||s)&&e(),r=o,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function h3(t,e){const r=po(t),n=I.useRef(0);return I.useEffect(()=>()=>window.clearTimeout(n.current),[]),I.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}function B1(t,e){const r=po(e);Po(()=>{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 sxe=Kye,NUe=Zye,PUe=txe;const Sm=I.forwardRef(({className:t,children:e,...r},n)=>a.jsxs(sxe,{ref:n,className:sr("relative overflow-hidden",t),...r,children:[a.jsx(NUe,{className:"h-full w-full rounded-[inherit]",children:e}),a.jsx(axe,{}),a.jsx(PUe,{})]}));Sm.displayName=sxe.displayName;const axe=I.forwardRef(({className:t,orientation:e="vertical",...r},n)=>a.jsx(i7,{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:a.jsx(exe,{className:"relative flex-1 rounded-full bg-border"})}));axe.displayName=i7.displayName;const RUe="/assets/levelup-logo-Eif24dqY.png",LUe="/assets/levelup-logo-icon-C-7iromj.png",DUe="/assets/levelup-logo-mobile-B9skSjUG.png";var gC=t=>t.type==="checkbox",c_=t=>t instanceof Date,Gc=t=>t==null;const oxe=t=>typeof t=="object";var No=t=>!Gc(t)&&!Array.isArray(t)&&oxe(t)&&!c_(t),lxe=t=>No(t)&&t.target?gC(t.target)?t.target.checked:t.target.value:t,MUe=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,cxe=(t,e)=>t.has(MUe(e)),OUe=t=>{const e=t.constructor&&t.constructor.prototype;return No(e)&&e.hasOwnProperty("isPrototypeOf")},o7=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function nl(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(!(o7&&(t instanceof Blob||n))&&(r||No(t)))if(e=r?[]:{},!r&&!OUe(t))e=t;else for(const i in t)t.hasOwnProperty(i)&&(e[i]=nl(t[i]));else return t;return e}var f3=t=>/^\w*$/.test(t),Eo=t=>t===void 0,l7=t=>Array.isArray(t)?t.filter(Boolean):[],c7=t=>l7(t.replace(/["|']|\]/g,"").split(/\.|\[/)),dn=(t,e,r)=>{if(!e||!No(t))return r;const n=(f3(e)?[e]:c7(e)).reduce((i,o)=>Gc(i)?i:i[o],t);return Eo(n)||n===t?Eo(t[e])?r:t[e]:n},Ju=t=>typeof t=="boolean",Fs=(t,e,r)=>{let n=-1;const i=f3(e)?[e]:c7(e),o=i.length,c=o-1;for(;++nXe.useContext(u7),FUe=t=>{const{children:e,...r}=t;return Xe.createElement(u7.Provider,{value:r},e)};var uxe=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const o in t)Object.defineProperty(i,o,{get:()=>{const c=o;return e._proxyFormState[c]!==Wh.all&&(e._proxyFormState[c]=!n||Wh.all),r&&(r[c]=!0),t[c]}});return i};const d7=typeof window<"u"?Xe.useLayoutEffect:Xe.useEffect;function BUe(t){const e=m3(),{control:r=e.control,disabled:n,name:i,exact:o}=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 d7(()=>r._subscribe({name:i,formState:f.current,exact:o,callback:p=>{!n&&s({...r._formState,...p})}}),[i,n,o]),Xe.useEffect(()=>{f.current.isValid&&r._setValid(!0)},[r]),Xe.useMemo(()=>uxe(c,r,f.current,!1),[c,r])}var Qf=t=>typeof t=="string",dxe=(t,e,r,n,i)=>Qf(t)?(n&&e.watch.add(t),dn(r,t,i)):Array.isArray(t)?t.map(o=>(n&&e.watch.add(o),dn(r,o))):(n&&(e.watchAll=!0),r),lV=t=>Gc(t)||!oxe(t);function vp(t,e,r=new WeakSet){if(lV(t)||lV(e))return t===e;if(c_(t)&&c_(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 o of n){const c=t[o];if(!i.includes(o))return!1;if(o!=="ref"){const s=e[o];if(c_(c)&&c_(s)||No(c)&&No(s)||Array.isArray(c)&&Array.isArray(s)?!vp(c,s,r):c!==s)return!1}}return!0}function zUe(t){const e=m3(),{control:r=e.control,name:n,defaultValue:i,disabled:o,exact:c,compute:s}=t||{},f=Xe.useRef(i),p=Xe.useRef(s),y=Xe.useRef(void 0);p.current=s;const _=Xe.useMemo(()=>r._getWatch(n,f.current),[r,n]),[T,E]=Xe.useState(p.current?p.current(_):_);return d7(()=>r._subscribe({name:n,formState:{values:!0},exact:c,callback:k=>{if(!o){const P=dxe(n,r._names,k.values||r._formValues,!1,f.current);if(p.current){const R=p.current(P);vp(R,y.current)||(E(R),y.current=R)}else E(P)}}}),[r,o,n,c]),Xe.useEffect(()=>r._removeUnmounted()),T}function $Ue(t){const e=m3(),{name:r,disabled:n,control:i=e.control,shouldUnregister:o,defaultValue:c}=t,s=cxe(i._names.array,r),f=Xe.useMemo(()=>dn(i._formValues,r,dn(i._defaultValues,r,c)),[i,r,c]),p=zUe({control:i,name:r,defaultValue:f,exact:!0}),y=BUe({control:i,name:r,exact:!0}),_=Xe.useRef(t),T=Xe.useRef(i.register(r,{...t.rules,value:p,...Ju(t.disabled)?{disabled:t.disabled}:{}}));_.current=t;const E=Xe.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!dn(y.errors,r)},isDirty:{enumerable:!0,get:()=>!!dn(y.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!dn(y.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!dn(y.validatingFields,r)},error:{enumerable:!0,get:()=>dn(y.errors,r)}}),[y,r]),k=Xe.useCallback(M=>T.current.onChange({target:{value:lxe(M),name:r},type:CD.CHANGE}),[r]),P=Xe.useCallback(()=>T.current.onBlur({target:{value:dn(i._formValues,r),name:r},type:CD.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:p,...Ju(n)||y.disabled?{disabled:y.disabled||n}:{},onChange:k,onBlur:P,ref:R}),[r,n,y.disabled,k,P,R,p]);return Xe.useEffect(()=>{const M=i._options.shouldUnregister||o;i.register(r,{..._.current.rules,...Ju(_.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=nl(dn(i._options.defaultValues,r));Fs(i._defaultValues,r,V),Eo(dn(i._formValues,r))&&Fs(i._formValues,r,V)}return!s&&i.register(r),()=>{(s?M&&!i._state.action:M)?i.unregister(r):B(r,!1)}},[r,i,s,o]),Xe.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),Xe.useMemo(()=>({field:D,formState:y,fieldState:E}),[D,y,E])}const UUe=t=>t.render($Ue(t));var hxe=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},BA=t=>Array.isArray(t)?t:[t],Nte=()=>{let t=[];return{get observers(){return t},next:i=>{for(const o of t)o.next&&o.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(o=>o!==i)}}),unsubscribe:()=>{t=[]}}},bu=t=>No(t)&&!Object.keys(t).length,h7=t=>t.type==="file",Kh=t=>typeof t=="function",ID=t=>{if(!o7)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},fxe=t=>t.type==="select-multiple",f7=t=>t.type==="radio",VUe=t=>f7(t)||gC(t),mz=t=>ID(t)&&t.isConnected;function qUe(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if(Kh(t[e]))return!0;return!1};function ND(t,e={}){const r=Array.isArray(t);if(No(t)||r)for(const n in t)Array.isArray(t[n])||No(t[n])&&!mxe(t[n])?(e[n]=Array.isArray(t[n])?[]:{},ND(t[n],e[n])):Gc(t[n])||(e[n]=!0);return e}function pxe(t,e,r){const n=Array.isArray(t);if(No(t)||n)for(const i in t)Array.isArray(t[i])||No(t[i])&&!mxe(t[i])?Eo(e)||lV(r[i])?r[i]=Array.isArray(t[i])?ND(t[i],[]):{...ND(t[i])}:pxe(t[i],Gc(e)?{}:e[i],r[i]):r[i]=!vp(t[i],e[i]);return r}var B2=(t,e)=>pxe(t,e,ND(e));const Pte={value:!1,isValid:!1},Rte={value:!0,isValid:!0};var gxe=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&&!Eo(t[0].attributes.value)?Eo(t[0].value)||t[0].value===""?Rte:{value:t[0].value,isValid:!0}:Rte:Pte}return Pte},yxe=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>Eo(t)?t:e?t===""?NaN:t&&+t:r&&Qf(t)?new Date(t):n?n(t):t;const Lte={isValid:!1,value:null};var xxe=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,Lte):Lte;function Dte(t){const e=t.ref;return h7(e)?e.files:f7(e)?xxe(t.refs).value:fxe(e)?[...e.selectedOptions].map(({value:r})=>r):gC(e)?gxe(t.refs).value:yxe(Eo(e.value)?t.ref.value:e.value,t)}var HUe=(t,e,r,n)=>{const i={};for(const o of t){const c=dn(e,o);c&&Fs(i,o,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},PD=t=>t instanceof RegExp,z2=t=>Eo(t)?t:PD(t)?t.source:No(t)?PD(t.value)?t.value.source:t.value:t,Mte=t=>({isOnSubmit:!t||t===Wh.onSubmit,isOnBlur:t===Wh.onBlur,isOnChange:t===Wh.onChange,isOnAll:t===Wh.all,isOnTouch:t===Wh.onTouched});const Ote="AsyncFunction";var WUe=t=>!!t&&!!t.validate&&!!(Kh(t.validate)&&t.validate.constructor.name===Ote||No(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===Ote)),KUe=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),Fte=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const zA=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const o=dn(t,i);if(o){const{_f:c,...s}=o;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(zA(s,e))break}else if(No(s)&&zA(s,e))break}}};function Bte(t,e,r){const n=dn(t,r);if(n||f3(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const o=i.join("."),c=dn(e,o),s=dn(t,o);if(c&&!Array.isArray(c)&&r!==o)return{name:r};if(s&&s.type)return{name:o,error:s};if(s&&s.root&&s.root.type)return{name:`${o}.root`,error:s.root};i.pop()}return{name:r}}var YUe=(t,e,r,n)=>{r(t);const{name:i,...o}=t;return bu(o)||Object.keys(o).length>=Object.keys(e).length||Object.keys(o).find(c=>e[c]===(!n||Wh.all))},ZUe=(t,e,r)=>!t||!e||t===e||BA(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n))),XUe=(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,QUe=(t,e)=>!l7(dn(t,e)).length&&Fo(t,e),JUe=(t,e,r)=>{const n=BA(dn(t,r));return Fs(n,"root",e[r]),Fs(t,r,n),t},lL=t=>Qf(t);function zte(t,e,r="validate"){if(lL(t)||Array.isArray(t)&&t.every(lL)||Ju(t)&&!t)return{type:r,message:lL(t)?t:"",ref:e}}var Jb=t=>No(t)&&!PD(t)?t:{value:t,message:""},$te=async(t,e,r,n,i,o)=>{const{ref:c,refs:s,required:f,maxLength:p,minLength:y,min:_,max:T,pattern:E,validate:k,name:P,valueAsNumber:R,mount:D}=t._f,M=dn(r,P);if(!D||e.has(P))return{};const B=s?s[0]:c,V=_e=>{i&&B.reportValidity&&(B.setCustomValidity(Ju(_e)?"":_e||""),B.reportValidity())},G={},W=f7(c),Z=gC(c),Q=W||Z,re=(R||h7(c))&&Eo(c.value)&&Eo(M)||ID(c)&&c.value===""||M===""||Array.isArray(M)&&!M.length,se=hxe.bind(null,P,n,G),ue=(_e,we,Ce,Me=sp.maxLength,Ae=sp.minLength)=>{const be=_e?we:Ce;G[P]={type:_e?Me:Ae,message:be,ref:c,...se(_e?Me:Ae,be)}};if(o?!Array.isArray(M)||!M.length:f&&(!Q&&(re||Gc(M))||Ju(M)&&!M||Z&&!gxe(s).isValid||W&&!xxe(s).isValid)){const{value:_e,message:we}=lL(f)?{value:!!f,message:f}:Jb(f);if(_e&&(G[P]={type:sp.required,message:we,ref:B,...se(sp.required,we)},!n))return V(we),G}if(!re&&(!Gc(_)||!Gc(T))){let _e,we;const Ce=Jb(T),Me=Jb(_);if(!Gc(M)&&!isNaN(M)){const Ae=c.valueAsNumber||M&&+M;Gc(Ce.value)||(_e=Ae>Ce.value),Gc(Me.value)||(we=Aenew Date(new Date().toDateString()+" "+Ie),me=c.type=="time",Pe=c.type=="week";Qf(Ce.value)&&M&&(_e=me?be(M)>be(Ce.value):Pe?M>Ce.value:Ae>new Date(Ce.value)),Qf(Me.value)&&M&&(we=me?be(M)+_e.value,Me=!Gc(we.value)&&M.length<+we.value;if((Ce||Me)&&(ue(Ce,_e.message,we.message),!n))return V(G[P].message),G}if(E&&!re&&Qf(M)){const{value:_e,message:we}=Jb(E);if(PD(_e)&&!M.match(_e)&&(G[P]={type:sp.pattern,message:we,ref:c,...se(sp.pattern,we)},!n))return V(we),G}if(k){if(Kh(k)){const _e=await k(M,r),we=zte(_e,B);if(we&&(G[P]={...we,...se(sp.validate,we.message)},!n))return V(we.message),G}else if(No(k)){let _e={};for(const we in k){if(!bu(_e)&&!n)break;const Ce=zte(await k[we](M,r),B,we);Ce&&(_e={...Ce,...se(we,Ce.message)},V(Ce.message),n&&(G[P]=_e))}if(!bu(_e)&&(G[P]={ref:B,..._e},!n))return G}}return V(!0),G};const eVe={mode:Wh.onSubmit,reValidateMode:Wh.onChange,shouldFocusError:!0};function tVe(t={}){let e={...eVe,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:Kh(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=No(e.defaultValues)||No(e.values)?nl(e.defaultValues||e.values)||{}:{},o=e.shouldUnregister?{}:nl(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,p=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let _={...y};const T={array:Nte(),state:Nte()},E=e.criteriaMode===Wh.all,k=lt=>At=>{clearTimeout(p),p=setTimeout(lt,At)},P=async lt=>{if(!e.disabled&&(y.isValid||_.isValid||lt)){const At=e.resolver?bu((await Z()).errors):await re(n,!0);At!==r.isValid&&T.state.next({isValid:At})}},R=(lt,At)=>{!e.disabled&&(y.isValidating||y.validatingFields||_.isValidating||_.validatingFields)&&((lt||Array.from(s.mount)).forEach(Mt=>{Mt&&(At?Fs(r.validatingFields,Mt,At):Fo(r.validatingFields,Mt))}),T.state.next({validatingFields:r.validatingFields,isValidating:!bu(r.validatingFields)}))},D=(lt,At=[],Mt,dr,ur=!0,hr=!0)=>{if(dr&&Mt&&!e.disabled){if(c.action=!0,hr&&Array.isArray(dn(n,lt))){const Xt=Mt(dn(n,lt),dr.argA,dr.argB);ur&&Fs(n,lt,Xt)}if(hr&&Array.isArray(dn(r.errors,lt))){const Xt=Mt(dn(r.errors,lt),dr.argA,dr.argB);ur&&Fs(r.errors,lt,Xt),QUe(r.errors,lt)}if((y.touchedFields||_.touchedFields)&&hr&&Array.isArray(dn(r.touchedFields,lt))){const Xt=Mt(dn(r.touchedFields,lt),dr.argA,dr.argB);ur&&Fs(r.touchedFields,lt,Xt)}(y.dirtyFields||_.dirtyFields)&&(r.dirtyFields=B2(i,o)),T.state.next({name:lt,isDirty:ue(lt,At),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Fs(o,lt,At)},M=(lt,At)=>{Fs(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,Mt,dr)=>{const ur=dn(n,lt);if(ur){const hr=dn(o,lt,Eo(Mt)?dn(i,lt):Mt);Eo(hr)||dr&&dr.defaultChecked||At?Fs(o,lt,At?hr:Dte(ur._f)):Ce(lt,hr),c.mount&&P()}},G=(lt,At,Mt,dr,ur)=>{let hr=!1,Xt=!1;const Pr={name:lt};if(!e.disabled){if(!Mt||dr){(y.isDirty||_.isDirty)&&(Xt=r.isDirty,r.isDirty=Pr.isDirty=ue(),hr=Xt!==Pr.isDirty);const Rn=vp(dn(i,lt),At);Xt=!!dn(r.dirtyFields,lt),Rn?Fo(r.dirtyFields,lt):Fs(r.dirtyFields,lt,!0),Pr.dirtyFields=r.dirtyFields,hr=hr||(y.dirtyFields||_.dirtyFields)&&Xt!==!Rn}if(Mt){const Rn=dn(r.touchedFields,lt);Rn||(Fs(r.touchedFields,lt,Mt),Pr.touchedFields=r.touchedFields,hr=hr||(y.touchedFields||_.touchedFields)&&Rn!==Mt)}hr&&ur&&T.state.next(Pr)}return hr?Pr:{}},W=(lt,At,Mt,dr)=>{const ur=dn(r.errors,lt),hr=(y.isValid||_.isValid)&&Ju(At)&&r.isValid!==At;if(e.delayError&&Mt?(f=k(()=>M(lt,Mt)),f(e.delayError)):(clearTimeout(p),f=null,Mt?Fs(r.errors,lt,Mt):Fo(r.errors,lt)),(Mt?!vp(ur,Mt):ur)||!bu(dr)||hr){const Xt={...dr,...hr&&Ju(At)?{isValid:At}:{},errors:r.errors,name:lt};r={...r,...Xt},T.state.next(Xt)}},Z=async lt=>{R(lt,!0);const At=await e.resolver(o,e.context,HUe(lt||s.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return R(lt),At},Q=async lt=>{const{errors:At}=await Z(lt);if(lt)for(const Mt of lt){const dr=dn(At,Mt);dr?Fs(r.errors,Mt,dr):Fo(r.errors,Mt)}else r.errors=At;return At},re=async(lt,At,Mt={valid:!0})=>{for(const dr in lt){const ur=lt[dr];if(ur){const{_f:hr,...Xt}=ur;if(hr){const Pr=s.array.has(hr.name),Rn=ur._f&&WUe(ur._f);Rn&&y.validatingFields&&R([dr],!0);const ci=await $te(ur,s.disabled,o,E,e.shouldUseNativeValidation&&!At,Pr);if(Rn&&y.validatingFields&&R([dr]),ci[hr.name]&&(Mt.valid=!1,At))break;!At&&(dn(ci,hr.name)?Pr?JUe(r.errors,ci,hr.name):Fs(r.errors,hr.name,ci[hr.name]):Fo(r.errors,hr.name))}!bu(Xt)&&await re(Xt,At,Mt)}}return Mt.valid},se=()=>{for(const lt of s.unMount){const At=dn(n,lt);At&&(At._f.refs?At._f.refs.every(Mt=>!mz(Mt)):!mz(At._f.ref))&&_t(lt)}s.unMount=new Set},ue=(lt,At)=>!e.disabled&&(lt&&At&&Fs(o,lt,At),!vp(Ie(),i)),_e=(lt,At,Mt)=>dxe(lt,s,{...c.mount?o:Eo(At)?i:Qf(lt)?{[lt]:At}:At},Mt,At),we=lt=>l7(dn(c.mount?o:i,lt,e.shouldUnregister?dn(i,lt,[]):[])),Ce=(lt,At,Mt={})=>{const dr=dn(n,lt);let ur=At;if(dr){const hr=dr._f;hr&&(!hr.disabled&&Fs(o,lt,yxe(At,hr)),ur=ID(hr.ref)&&Gc(At)?"":At,fxe(hr.ref)?[...hr.ref.options].forEach(Xt=>Xt.selected=ur.includes(Xt.value)):hr.refs?gC(hr.ref)?hr.refs.forEach(Xt=>{(!Xt.defaultChecked||!Xt.disabled)&&(Array.isArray(ur)?Xt.checked=!!ur.find(Pr=>Pr===Xt.value):Xt.checked=ur===Xt.value||!!ur)}):hr.refs.forEach(Xt=>Xt.checked=Xt.value===ur):h7(hr.ref)?hr.ref.value="":(hr.ref.value=ur,hr.ref.type||T.state.next({name:lt,values:nl(o)})))}(Mt.shouldDirty||Mt.shouldTouch)&&G(lt,ur,Mt.shouldTouch,Mt.shouldDirty,!0),Mt.shouldValidate&&Pe(lt)},Me=(lt,At,Mt)=>{for(const dr in At){if(!At.hasOwnProperty(dr))return;const ur=At[dr],hr=lt+"."+dr,Xt=dn(n,hr);(s.array.has(lt)||No(ur)||Xt&&!Xt._f)&&!c_(ur)?Me(hr,ur,Mt):Ce(hr,ur,Mt)}},Ae=(lt,At,Mt={})=>{const dr=dn(n,lt),ur=s.array.has(lt),hr=nl(At);Fs(o,lt,hr),ur?(T.array.next({name:lt,values:nl(o)}),(y.isDirty||y.dirtyFields||_.isDirty||_.dirtyFields)&&Mt.shouldDirty&&T.state.next({name:lt,dirtyFields:B2(i,o),isDirty:ue(lt,hr)})):dr&&!dr._f&&!Gc(hr)?Me(lt,hr,Mt):Ce(lt,hr,Mt),Fte(lt,s)&&T.state.next({...r,name:lt}),T.state.next({name:c.mount?lt:void 0,values:nl(o)})},be=async lt=>{c.mount=!0;const At=lt.target;let Mt=At.name,dr=!0;const ur=dn(n,Mt),hr=Rn=>{dr=Number.isNaN(Rn)||c_(Rn)&&isNaN(Rn.getTime())||vp(Rn,dn(o,Mt,Rn))},Xt=Mte(e.mode),Pr=Mte(e.reValidateMode);if(ur){let Rn,ci;const ti=At.type?Dte(ur._f):lxe(lt),zi=lt.type===CD.BLUR||lt.type===CD.FOCUS_OUT,wa=!KUe(ur._f)&&!e.resolver&&!dn(r.errors,Mt)&&!ur._f.deps||XUe(zi,dn(r.touchedFields,Mt),r.isSubmitted,Pr,Xt),xi=Fte(Mt,s,zi);Fs(o,Mt,ti),zi?(ur._f.onBlur&&ur._f.onBlur(lt),f&&f(0)):ur._f.onChange&&ur._f.onChange(lt);const la=G(Mt,ti,zi),Cr=!bu(la)||xi;if(!zi&&T.state.next({name:Mt,type:lt.type,values:nl(o)}),wa)return(y.isValid||_.isValid)&&(e.mode==="onBlur"?zi&&P():zi||P()),Cr&&T.state.next({name:Mt,...xi?{}:la});if(!zi&&xi&&T.state.next({...r}),e.resolver){const{errors:Fn}=await Z([Mt]);if(hr(ti),dr){const As=Bte(r.errors,n,Mt),Sa=Bte(Fn,n,As.name||Mt);Rn=Sa.error,Mt=Sa.name,ci=bu(Fn)}}else R([Mt],!0),Rn=(await $te(ur,s.disabled,o,E,e.shouldUseNativeValidation))[Mt],R([Mt]),hr(ti),dr&&(Rn?ci=!1:(y.isValid||_.isValid)&&(ci=await re(n,!0)));dr&&(ur._f.deps&&Pe(ur._f.deps),W(Mt,ci,Rn,la))}},me=(lt,At)=>{if(dn(r.errors,At)&<.focus)return lt.focus(),1},Pe=async(lt,At={})=>{let Mt,dr;const ur=BA(lt);if(e.resolver){const hr=await Q(Eo(lt)?lt:ur);Mt=bu(hr),dr=lt?!ur.some(Xt=>dn(hr,Xt)):Mt}else lt?(dr=(await Promise.all(ur.map(async hr=>{const Xt=dn(n,hr);return await re(Xt&&Xt._f?{[hr]:Xt}:Xt)}))).every(Boolean),!(!dr&&!r.isValid)&&P()):dr=Mt=await re(n);return T.state.next({...!Qf(lt)||(y.isValid||_.isValid)&&Mt!==r.isValid?{}:{name:lt},...e.resolver||!lt?{isValid:Mt}:{},errors:r.errors}),At.shouldFocus&&!dr&&zA(n,me,lt?ur:s.mount),dr},Ie=lt=>{const At={...c.mount?o:i};return Eo(lt)?At:Qf(lt)?dn(At,lt):lt.map(Mt=>dn(At,Mt))},Se=(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)}),ve=lt=>{lt&&BA(lt).forEach(At=>Fo(r.errors,At)),T.state.next({errors:lt?r.errors:{}})},We=(lt,At,Mt)=>{const dr=(dn(n,lt,{_f:{}})._f||{}).ref,ur=dn(r.errors,lt)||{},{ref:hr,message:Xt,type:Pr,...Rn}=ur;Fs(r.errors,lt,{...Rn,...At,ref:dr}),T.state.next({name:lt,errors:r.errors,isValid:!1}),Mt&&Mt.shouldFocus&&dr&&dr.focus&&dr.focus()},rt=(lt,At)=>Kh(lt)?T.state.subscribe({next:Mt=>"values"in Mt&<(_e(void 0,At),Mt)}):_e(lt,At,!0),at=lt=>T.state.subscribe({next:At=>{ZUe(lt.name,At.name,lt.exact)&&YUe(At,lt.formState||y,xr,lt.reRenderRoot)&<.callback({values:{...o},...r,...At,defaultValues:i})}}).unsubscribe,Et=lt=>(c.mount=!0,_={..._,...lt.formState},at({...lt,formState:_})),_t=(lt,At={})=>{for(const Mt of lt?BA(lt):s.mount)s.mount.delete(Mt),s.array.delete(Mt),At.keepValue||(Fo(n,Mt),Fo(o,Mt)),!At.keepError&&Fo(r.errors,Mt),!At.keepDirty&&Fo(r.dirtyFields,Mt),!At.keepTouched&&Fo(r.touchedFields,Mt),!At.keepIsValidating&&Fo(r.validatingFields,Mt),!e.shouldUnregister&&!At.keepDefaultValue&&Fo(i,Mt);T.state.next({values:nl(o)}),T.state.next({...r,...At.keepDirty?{isDirty:ue()}:{}}),!At.keepIsValid&&P()},Vt=({disabled:lt,name:At})=>{(Ju(lt)&&c.mount||lt||s.disabled.has(At))&&(lt?s.disabled.add(At):s.disabled.delete(At))},pt=(lt,At={})=>{let Mt=dn(n,lt);const dr=Ju(At.disabled)||Ju(e.disabled);return Fs(n,lt,{...Mt||{},_f:{...Mt&&Mt._f?Mt._f:{ref:{name:lt}},name:lt,mount:!0,...At}}),s.mount.add(lt),Mt?Vt({disabled:Ju(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:z2(At.min),max:z2(At.max),minLength:z2(At.minLength),maxLength:z2(At.maxLength),pattern:z2(At.pattern)}:{},name:lt,onChange:be,onBlur:be,ref:ur=>{if(ur){pt(lt,At),Mt=dn(n,lt);const hr=Eo(ur.value)&&ur.querySelectorAll&&ur.querySelectorAll("input,select,textarea")[0]||ur,Xt=VUe(hr),Pr=Mt._f.refs||[];if(Xt?Pr.find(Rn=>Rn===hr):hr===Mt._f.ref)return;Fs(n,lt,{_f:{...Mt._f,...Xt?{refs:[...Pr.filter(mz),hr,...Array.isArray(dn(i,lt))?[{}]:[]],ref:{type:hr.type,name:lt}}:{ref:hr}}}),V(lt,!1,void 0,hr)}else Mt=dn(n,lt,{}),Mt._f&&(Mt._f.mount=!1),(e.shouldUnregister||At.shouldUnregister)&&!(cxe(s.array,lt)&&c.action)&&s.unMount.add(lt)}}},Nt=()=>e.shouldFocusError&&zA(n,me,s.mount),er=lt=>{Ju(lt)&&(T.state.next({disabled:lt}),zA(n,(At,Mt)=>{const dr=dn(n,Mt);dr&&(At.disabled=dr._f.disabled||lt,Array.isArray(dr._f.refs)&&dr._f.refs.forEach(ur=>{ur.disabled=dr._f.disabled||lt}))},0,!1))},vt=(lt,At)=>async Mt=>{let dr;Mt&&(Mt.preventDefault&&Mt.preventDefault(),Mt.persist&&Mt.persist());let ur=nl(o);if(T.state.next({isSubmitting:!0}),e.resolver){const{errors:hr,values:Xt}=await Z();r.errors=hr,ur=nl(Xt)}else await re(n);if(s.disabled.size)for(const hr of s.disabled)Fo(ur,hr);if(Fo(r.errors,"root"),bu(r.errors)){T.state.next({errors:{}});try{await lt(ur,Mt)}catch(hr){dr=hr}}else At&&await At({...r.errors},Mt),Nt(),setTimeout(Nt);if(T.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:bu(r.errors)&&!dr,submitCount:r.submitCount+1,errors:r.errors}),dr)throw dr},or=(lt,At={})=>{dn(n,lt)&&(Eo(At.defaultValue)?Ae(lt,nl(dn(i,lt))):(Ae(lt,At.defaultValue),Fs(i,lt,nl(At.defaultValue))),At.keepTouched||Fo(r.touchedFields,lt),At.keepDirty||(Fo(r.dirtyFields,lt),r.isDirty=At.defaultValue?ue(lt,nl(dn(i,lt))):ue()),At.keepError||(Fo(r.errors,lt),y.isValid&&P()),T.state.next({...r}))},Sr=(lt,At={})=>{const Mt=lt?nl(lt):i,dr=nl(Mt),ur=bu(lt),hr=ur?i:dr;if(At.keepDefaultValues||(i=Mt),!At.keepValues){if(At.keepDirtyValues){const Xt=new Set([...s.mount,...Object.keys(B2(i,o))]);for(const Pr of Array.from(Xt))dn(r.dirtyFields,Pr)?Fs(hr,Pr,dn(o,Pr)):Ae(Pr,dn(hr,Pr))}else{if(o7&&Eo(lt))for(const Xt of s.mount){const Pr=dn(n,Xt);if(Pr&&Pr._f){const Rn=Array.isArray(Pr._f.refs)?Pr._f.refs[0]:Pr._f.ref;if(ID(Rn)){const ci=Rn.closest("form");if(ci){ci.reset();break}}}}if(At.keepFieldsRef)for(const Xt of s.mount)Ae(Xt,dn(hr,Xt));else n={}}o=e.shouldUnregister?At.keepDefaultValues?nl(i):{}:nl(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=!y.isValid||!!At.keepIsValid||!!At.keepDirtyValues,c.watch=!!e.shouldUnregister,T.state.next({submitCount:At.keepSubmitCount?r.submitCount:0,isDirty:ur?!1:At.keepDirty?r.isDirty:!!(At.keepDefaultValues&&!vp(lt,i)),isSubmitted:At.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:ur?{}:At.keepDirtyValues?At.keepDefaultValues&&o?B2(i,o):r.dirtyFields:At.keepDefaultValues&<?B2(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(Kh(lt)?lt(o):lt,At),cr=(lt,At={})=>{const Mt=dn(n,lt),dr=Mt&&Mt._f;if(dr){const ur=dr.refs?dr.refs[0]:dr.ref;ur.focus&&(ur.focus(),At.shouldSelect&&Kh(ur.select)&&ur.select())}},xr=lt=>{r={...r,...lt}},_n={control:{register:pt,unregister:_t,getFieldState:Se,handleSubmit:vt,setError:We,_subscribe:at,_runSchema:Z,_focusError:Nt,_getWatch:_e,_getDirty:ue,_setValid:P,_setFieldArray:D,_setDisabledField:Vt,_setErrors:B,_getFieldArray:we,_reset:Sr,_resetDefaultValues:()=>Kh(e.defaultValues)&&e.defaultValues().then(lt=>{nn(lt,e.resetOptions),T.state.next({isLoading:!1})}),_removeUnmounted:se,_disableForm:er,_subjects:T,_proxyFormState:y,get _fields(){return n},get _formValues(){return o},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:Pe,register:pt,handleSubmit:vt,watch:rt,setValue:Ae,getValues:Ie,reset:nn,resetField:or,clearErrors:ve,unregister:_t,setError:We,setFocus:cr,getFieldState:Se};return{..._n,formControl:_n}}function m7(t={}){const e=Xe.useRef(void 0),r=Xe.useRef(void 0),[n,i]=Xe.useState({isDirty:!1,isValidating:!1,isLoading:Kh(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:Kh(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!Kh(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:c,...s}=tVe(t);e.current={...s,formState:n}}const o=e.current.control;return o._options=t,d7(()=>{const c=o._subscribe({formState:o._proxyFormState,callback:()=>i({...o._formState}),reRenderRoot:!0});return i(s=>({...s,isReady:!0})),o._formState.isReady=!0,c},[o]),Xe.useEffect(()=>o._disableForm(t.disabled),[o,t.disabled]),Xe.useEffect(()=>{t.mode&&(o._options.mode=t.mode),t.reValidateMode&&(o._options.reValidateMode=t.reValidateMode)},[o,t.mode,t.reValidateMode]),Xe.useEffect(()=>{t.errors&&(o._setErrors(t.errors),o._focusError())},[o,t.errors]),Xe.useEffect(()=>{t.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,t.shouldUnregister]),Xe.useEffect(()=>{if(o._proxyFormState.isDirty){const c=o._getDirty();c!==n.isDirty&&o._subjects.state.next({isDirty:c})}},[o,n.isDirty]),Xe.useEffect(()=>{t.values&&!vp(t.values,r.current)?(o._reset(t.values,{keepFieldsRef:!0,...o._options.resetOptions}),r.current=t.values,i(c=>({...c}))):o._resetDefaultValues()},[o,t.values]),Xe.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),e.current.formState=uxe(n,o),e.current}const Ute=(t,e,r)=>{if(t&&"reportValidity"in t){const n=dn(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},_xe=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?Ute(n.ref,r,t):n.refs&&n.refs.forEach(i=>Ute(i,r,t))}},rVe=(t,e)=>{e.shouldUseNativeValidation&&_xe(t,e);const r={};for(const n in t){const i=dn(e.fields,n),o=Object.assign(t[n]||{},{ref:i&&i.ref});if(nVe(e.names||Object.keys(t),n)){const c=Object.assign({},dn(r,n));Fs(c,"root",o),Fs(r,n,c)}else Fs(r,n,o)}return r},nVe=(t,e)=>t.some(r=>r.startsWith(e+"."));var iVe=function(t,e){for(var r={};t.length;){var n=t[0],i=n.code,o=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:o,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(y){return y.errors.forEach(function(_){return t.push(_)})}),e){var f=r[c].types,p=f&&f[n.code];r[c]=hxe(c,e,r,i,p?[].concat(p,n.message):n.message)}t.shift()}return r},p7=function(t,e,r){return r===void 0&&(r={}),function(n,i,o){try{return Promise.resolve(function(c,s){try{var f=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(p){return o.shouldUseNativeValidation&&_xe({},o),{errors:{},values:r.raw?n:p}})}catch(p){return s(p)}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:rVe(iVe(c.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw c}))}catch(c){return Promise.reject(c)}}},Vte;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 p=c.prototype,y=Object.keys(p);for(let _=0;_{var f,p;return r!=null&&r.Parent&&s instanceof r.Parent?!0:(p=(f=s==null?void 0:s._zod)==null?void 0:f.traits)==null?void 0:p.has(t)}}),Object.defineProperty(c,"name",{value:t}),c}class t1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class vxe extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Vte=globalThis).__zod_globalConfig??(Vte.__zod_globalConfig={});const g7=globalThis.__zod_globalConfig;function $p(t){return g7}function bxe(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 cV(t,e){return typeof e=="bigint"?e.toString():e}function y7(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function x7(t){return t==null}function _7(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function sVe(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 RD(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const oVe=y7(()=>{var t;if(g7.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 z1(t){if(RD(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const r=e.prototype;return!(RD(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Sxe(t){return z1(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const lVe=new Set(["string","number","symbol"]);function $1(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xx(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 Un(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 cVe(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const uVe={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 dVe(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 o=yx(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 cv(this,"shape",c),c},checks:[]});return xx(t,o)}function hVe(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 o=yx(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 cv(this,"shape",c),c},checks:[]});return xx(t,o)}function fVe(t,e){if(!z1(e))throw new Error("Invalid input to extend: expected a plain object");const r=t._zod.def.checks;if(r&&r.length>0){const o=t._zod.def.shape;for(const c in e)if(Object.getOwnPropertyDescriptor(o,c)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=yx(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return cv(this,"shape",o),o}});return xx(t,i)}function mVe(t,e){if(!z1(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yx(t._zod.def,{get shape(){const n={...t._zod.def.shape,...e};return cv(this,"shape",n),n}});return xx(t,r)}function pVe(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=yx(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return cv(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return xx(t,r)}function gVe(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=yx(e._zod.def,{get shape(){const s=e._zod.def.shape,f={...s};if(r)for(const p in r){if(!(p in s))throw new Error(`Unrecognized key: "${p}"`);r[p]&&(f[p]=t?new t({type:"optional",innerType:s[p]}):s[p])}else for(const p in s)f[p]=t?new t({type:"optional",innerType:s[p]}):s[p];return cv(this,"shape",f),f},checks:[]});return xx(e,c)}function yVe(t,e,r){const n=yx(e._zod.def,{get shape(){const i=e._zod.def.shape,o={...i};if(r)for(const c in r){if(!(c in o))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(o[c]=new t({type:"nonoptional",innerType:i[c]}))}else for(const c in i)o[c]=new t({type:"nonoptional",innerType:i[c]});return cv(this,"shape",o),o}});return xx(e,n)}function Iw(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 UP(t){return typeof t=="string"?t:t==null?void 0:t.message}function Up(t,e,r){var f,p,y,_,T,E;const n=t.message?t.message:UP((y=(p=(f=t.inst)==null?void 0:f._zod.def)==null?void 0:p.error)==null?void 0:y.call(p,t))??UP((_=e==null?void 0:e.error)==null?void 0:_.call(e,t))??UP((T=r.customError)==null?void 0:T.call(r,t))??UP((E=r.localeError)==null?void 0:E.call(r,t))??"Invalid input",{inst:i,continue:o,input:c,...s}=t;return s.path??(s.path=[]),s.message=n,e!=null&&e.reportInput&&(s.input=c),s}function v7(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Fj(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const Txe=(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,cV,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Exe=Er("$ZodError",Txe),Axe=Er("$ZodError",Txe,{Parent:Error});function _Ve(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 vVe(t,e=r=>r.message){const r={_errors:[]},n=(i,o=[])=>{for(const c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(s=>n({issues:s},[...o,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...o,...c.path]);else{const s=[...o,...c.path];if(s.length===0)r._errors.push(e(c));else{let f=r,p=0;for(;p(e,r,n,i)=>{const o=n?{...n,async:!1}:{async:!1},c=e._zod.run({value:r,issues:[]},o);if(c instanceof Promise)throw new t1;if(c.issues.length){const s=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Up(f,o,$p())));throw wxe(s,i==null?void 0:i.callee),s}return c.value},w7=t=>async(e,r,n,i)=>{const o=n?{...n,async:!0}:{async:!0};let c=e._zod.run({value:r,issues:[]},o);if(c instanceof Promise&&(c=await c),c.issues.length){const s=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Up(f,o,$p())));throw wxe(s,i==null?void 0:i.callee),s}return c.value},p3=t=>(e,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new t1;return o.issues.length?{success:!1,error:new(t??Exe)(o.issues.map(c=>Up(c,i,$p())))}:{success:!0,data:o.value}},bVe=p3(Axe),g3=t=>async(e,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(c=>Up(c,i,$p())))}:{success:!0,data:o.value}},wVe=g3(Axe),SVe=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return b7(t)(e,r,i)},TVe=t=>(e,r,n)=>b7(t)(e,r,n),EVe=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return w7(t)(e,r,i)},AVe=t=>async(e,r,n)=>w7(t)(e,r,n),jVe=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return p3(t)(e,r,i)},kVe=t=>(e,r,n)=>p3(t)(e,r,n),CVe=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return g3(t)(e,r,i)},IVe=t=>async(e,r,n)=>g3(t)(e,r,n),NVe=/^[cC][0-9a-z]{6,}$/,PVe=/^[0-9a-z]+$/,RVe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,LVe=/^[0-9a-vA-V]{20}$/,DVe=/^[A-Za-z0-9]{27}$/,MVe=/^[a-zA-Z0-9_-]{21}$/,OVe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,FVe=/^([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})$/,Hte=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)$/,BVe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zVe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $Ve(){return new RegExp(zVe,"u")}const UVe=/^(?:(?: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])$/,VVe=/^(([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}|:))$/,qVe=/^((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])$/,GVe=/^(([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])$/,HVe=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jxe=/^[A-Za-z0-9_-]*$/,WVe=/^https?$/,KVe=/^\+[1-9]\d{6,14}$/,kxe="(?:(?:\\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])))",YVe=new RegExp(`^${kxe}$`);function Cxe(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 ZVe(t){return new RegExp(`^${Cxe(t)}$`)}function XVe(t){const e=Cxe({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(`^${kxe}T(?:${n})$`)}const QVe=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}$`)},JVe=/^-?\d+$/,Ixe=/^-?\d+(?:\.\d+)?$/,e8e=/^(?:true|false)$/i,t8e=/^[^A-Z]*$/,r8e=/^[^a-z]*$/,Lu=Er("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Nxe={number:"number",bigint:"bigint",object:"date"},Pxe=Er("$ZodCheckLessThan",(t,e)=>{Lu.init(t,e);const r=Nxe[typeof e.value];t._zod.onattach.push(n=>{const i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{Lu.init(t,e);const r=Nxe[typeof e.value];t._zod.onattach.push(n=>{const i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(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})}}),n8e=Er("$ZodCheckMultipleOf",(t,e)=>{Lu.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):sVe(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})}}),i8e=Er("$ZodCheckNumberFormat",(t,e)=>{var c;Lu.init(t,e),e.format=e.format||"float64";const r=(c=e.format)==null?void 0:c.includes("int"),n=r?"int":"number",[i,o]=uVe[e.format];t._zod.onattach.push(s=>{const f=s._zod.bag;f.format=e.format,f.minimum=i,f.maximum=o,r&&(f.pattern=JVe)}),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}}fo&&s.issues.push({origin:"number",input:f,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}}),s8e=Er("$ZodCheckMaxLength",(t,e)=>{var r;Lu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!x7(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=v7(i);n.issues.push({origin:c,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),a8e=Er("$ZodCheckMinLength",(t,e)=>{var r;Lu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!x7(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=v7(i);n.issues.push({origin:c,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),o8e=Er("$ZodCheckLengthEquals",(t,e)=>{var r;Lu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!x7(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,o=i.length;if(o===e.length)return;const c=v7(i),s=o>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})}}),y3=Er("$ZodCheckStringFormat",(t,e)=>{var r,n;Lu.init(t,e),t._zod.onattach.push(i=>{const o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.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=()=>{})}),l8e=Er("$ZodCheckRegex",(t,e)=>{y3.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})}}),c8e=Er("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=t8e),y3.init(t,e)}),u8e=Er("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=r8e),y3.init(t,e)}),d8e=Er("$ZodCheckIncludes",(t,e)=>{Lu.init(t,e);const r=$1(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.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})}}),h8e=Er("$ZodCheckStartsWith",(t,e)=>{Lu.init(t,e);const r=new RegExp(`^${$1(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})}}),f8e=Er("$ZodCheckEndsWith",(t,e)=>{Lu.init(t,e);const r=new RegExp(`.*${$1(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})}}),m8e=Er("$ZodCheckOverwrite",(t,e)=>{Lu.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class p8e{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)),o=n.map(c=>c.slice(i)).map(c=>" ".repeat(this.indent*2)+c);for(const c of o)this.content.push(c)}compile(){const e=Function,r=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(o=>` ${o}`)];return new e(...r,i.join(` `))}}const g8e={major:4,minor:4,patch:3},so=Er("$ZodType",(t,e)=>{var i;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=g8e;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const o of n)for(const c of o._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 o=(s,f,p)=>{let y=Iw(s),_;for(const T of f){if(T._zod.def.when){if(xVe(s)||!T._zod.def.when(s))continue}else if(y)continue;const E=s.issues.length,k=T._zod.check(s);if(k instanceof Promise&&(p==null?void 0:p.async)===!1)throw new t1;if(_||k instanceof Promise)_=(_??Promise.resolve()).then(async()=>{await k,s.issues.length!==E&&(y||(y=Iw(s,E)))});else{if(s.issues.length===E)continue;y||(y=Iw(s,E))}}return _?_.then(()=>s):s},c=(s,f,p)=>{if(Iw(s))return s.aborted=!0,s;const y=o(f,n,p);if(y instanceof Promise){if(p.async===!1)throw new t1;return y.then(_=>t._zod.parse(_,p))}return t._zod.parse(y,p)};t._zod.run=(s,f)=>{if(f.skipChecks)return t._zod.parse(s,f);if(f.direction==="backward"){const y=t._zod.parse({value:s.value,issues:[]},{...f,skipChecks:!0});return y instanceof Promise?y.then(_=>c(_,s,f)):c(y,s,f)}const p=t._zod.parse(s,f);if(p instanceof Promise){if(f.async===!1)throw new t1;return p.then(y=>o(y,n,f))}return o(p,n,f)}}Zs(t,"~standard",()=>({validate:o=>{var c;try{const s=bVe(t,o);return s.success?{value:s.data}:{issues:(c=s.error)==null?void 0:c.issues}}catch{return wVe(t,o).then(f=>{var p;return f.success?{value:f.data}:{issues:(p=f.error)==null?void 0:p.issues}})}},vendor:"zod",version:1}))}),S7=Er("$ZodString",(t,e)=>{var r;so.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??QVe(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}}),Va=Er("$ZodStringFormat",(t,e)=>{y3.init(t,e),S7.init(t,e)}),y8e=Er("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=FVe),Va.init(t,e)}),x8e=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=Hte(n))}else e.pattern??(e.pattern=Hte());Va.init(t,e)}),_8e=Er("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=BVe),Va.init(t,e)}),v8e=Er("$ZodURL",(t,e)=>{Va.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)===WVe.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 o=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.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(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.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=o.href:r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),b8e=Er("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=$Ve()),Va.init(t,e)}),w8e=Er("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=MVe),Va.init(t,e)}),S8e=Er("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=NVe),Va.init(t,e)}),T8e=Er("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=PVe),Va.init(t,e)}),E8e=Er("$ZodULID",(t,e)=>{e.pattern??(e.pattern=RVe),Va.init(t,e)}),A8e=Er("$ZodXID",(t,e)=>{e.pattern??(e.pattern=LVe),Va.init(t,e)}),j8e=Er("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=DVe),Va.init(t,e)}),k8e=Er("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=XVe(e)),Va.init(t,e)}),C8e=Er("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=YVe),Va.init(t,e)}),I8e=Er("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ZVe(e)),Va.init(t,e)}),N8e=Er("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=OVe),Va.init(t,e)}),P8e=Er("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=UVe),Va.init(t,e),t._zod.bag.format="ipv4"}),R8e=Er("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=VVe),Va.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})}}}),L8e=Er("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=qVe),Va.init(t,e)}),D8e=Er("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=GVe),Va.init(t,e),t._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[i,o]=n;if(!o)throw new Error;const c=Number(o);if(`${c}`!==o)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 Lxe(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const M8e=Er("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=HVe),Va.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Lxe(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function O8e(t){if(!jxe.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Lxe(r)}const F8e=Er("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=jxe),Va.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{O8e(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),B8e=Er("$ZodE164",(t,e)=>{e.pattern??(e.pattern=KVe),Va.init(t,e)});function z8e(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 $8e=Er("$ZodJWT",(t,e)=>{Va.init(t,e),t._zod.check=r=>{z8e(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Dxe=Er("$ZodNumber",(t,e)=>{so.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ixe,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 o=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,...o?{received:o}:{}}),r}}),U8e=Er("$ZodNumberFormat",(t,e)=>{i8e.init(t,e),Dxe.init(t,e)}),V8e=Er("$ZodBoolean",(t,e)=>{so.init(t,e),t._zod.pattern=e8e,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}}),q8e=Er("$ZodUnknown",(t,e)=>{so.init(t,e),t._zod.parse=r=>r}),G8e=Er("$ZodNever",(t,e)=>{so.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Wte(t,e,r){t.issues.length&&e.issues.push(...Nw(r,t.issues)),e.value[r]=t.value}const H8e=Er("$ZodArray",(t,e)=>{so.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 o=[];for(let c=0;cWte(p,r,c))):Wte(f,r,c)}return o.length?Promise.all(o).then(()=>r):r}});function LD(t,e,r,n,i,o){const c=r in n;if(t.issues.length){if(i&&o&&!c)return;e.issues.push(...Nw(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 Mxe(t){var n,i,o,c;const e=Object.keys(t.shape);for(const s of e)if(!((c=(o=(i=(n=t.shape)==null?void 0:n[s])==null?void 0:i._zod)==null?void 0:o.traits)!=null&&c.has("$ZodType")))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=cVe(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Oxe(t,e,r,n,i,o){const c=[],s=i.keySet,f=i.catchall._zod,p=f.def.type,y=f.optin==="optional",_=f.optout==="optional";for(const T in e){if(T==="__proto__"||s.has(T))continue;if(p==="never"){c.push(T);continue}const E=f.run({value:e[T],issues:[]},n);E instanceof Promise?t.push(E.then(k=>LD(k,r,T,e,y,_))):LD(E,r,T,e,y,_)}return c.length&&r.issues.push({code:"unrecognized_keys",keys:c,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}const W8e=Er("$ZodObject",(t,e)=>{so.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=y7(()=>Mxe(e));Zs(t._zod,"propValues",()=>{const s=e.shape,f={};for(const p in s){const y=s[p]._zod;if(y.values){f[p]??(f[p]=new Set);for(const _ of y.values)f[p].add(_)}}return f});const i=RD,o=e.catchall;let c;t._zod.parse=(s,f)=>{c??(c=n.value);const p=s.value;if(!i(p))return s.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),s;s.value={};const y=[],_=c.shape;for(const T of c.keys){const E=_[T],k=E._zod.optin==="optional",P=E._zod.optout==="optional",R=E._zod.run({value:p[T],issues:[]},f);R instanceof Promise?y.push(R.then(D=>LD(D,s,T,p,k,P))):LD(R,s,T,p,k,P)}return o?Oxe(y,p,s,f,n.value,t):y.length?Promise.all(y).then(()=>s):s}}),K8e=Er("$ZodObjectJIT",(t,e)=>{W8e.init(t,e);const r=t._zod.parse,n=y7(()=>Mxe(e)),i=T=>{var B,V;const E=new p8e(["shape","payload","ctx"]),k=n.value,P=G=>{const W=Gte(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 k.keys)R[G]=`key_${D++}`;E.write("const newResult = {};");for(const G of k.keys){const W=R[G],Z=Gte(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} = ${P(G)};`),re&&se?E.write(` if (${W}.issues.length) { if (${Z} in input) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Z}, ...iss.path] : [${Z}] }))); } } if (${W}.value === undefined) { if (${Z} in input) { newResult[${Z}] = undefined; } } else { newResult[${Z}] = ${W}.value; } `):re?E.write(` if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Z}, ...iss.path] : [${Z}] }))); } if (${W}.value === undefined) { if (${Z} in input) { newResult[${Z}] = undefined; } } else { newResult[${Z}] = ${W}.value; } `):E.write(` const ${W}_present = ${Z} in input; if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Z}, ...iss.path] : [${Z}] }))); } if (!${W}_present && !${W}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${Z}] }); } if (${W}_present) { if (${W}.value === undefined) { newResult[${Z}] = undefined; } else { newResult[${Z}] = ${W}.value; } } `)}E.write("payload.value = newResult;"),E.write("return payload;");const M=E.compile();return(G,W)=>M(T,G,W)};let o;const c=RD,s=!g7.jitless,p=s&&oVe.value,y=e.catchall;let _;t._zod.parse=(T,E)=>{_??(_=n.value);const k=T.value;return c(k)?s&&p&&(E==null?void 0:E.async)===!1&&E.jitless!==!0?(o||(o=i(e.shape)),T=o(T,E),y?Oxe([],k,T,E,_,t):T):r(T,E):(T.issues.push({expected:"object",code:"invalid_type",input:k,inst:t}),T)}});function Kte(t,e,r,n){for(const o of t)if(o.issues.length===0)return e.value=o.value,e;const i=t.filter(o=>!Iw(o));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(o=>o.issues.map(c=>Up(c,n,$p())))}),e)}const Y8e=Er("$ZodUnion",(t,e)=>{so.init(t,e),Zs(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Zs(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Zs(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Zs(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=>_7(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 o=!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),o=!0;else{if(f.issues.length===0)return f;c.push(f)}}return o?Promise.all(c).then(s=>Kte(s,n,t,i)):Kte(c,n,t,i)}}),Z8e=Er("$ZodIntersection",(t,e)=>{so.init(t,e),t._zod.parse=(r,n)=>{const i=r.value,o=e.left._zod.run({value:i,issues:[]},n),c=e.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||c instanceof Promise?Promise.all([o,c]).then(([f,p])=>Yte(r,f,p)):Yte(r,o,c)}});function uV(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(z1(t)&&z1(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),i={...t,...e};for(const o of n){const c=uV(t[o],e[o]);if(!c.valid)return{valid:!1,mergeErrorPath:[o,...c.mergeErrorPath]};i[o]=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(o.length&&i&&t.issues.push({...i,keys:o}),Iw(t))return t;const c=uV(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 X8e=Er("$ZodRecord",(t,e)=>{so.init(t,e),t._zod.parse=(r,n)=>{const i=r.value;if(!z1(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;const o=[],c=e.keyType._zod.values;if(c){r.value={};const s=new Set;for(const p of c)if(typeof p=="string"||typeof p=="number"||typeof p=="symbol"){s.add(typeof p=="number"?p.toString():p);const y=e.keyType._zod.run({value:p,issues:[]},n);if(y instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(y.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:y.issues.map(E=>Up(E,n,$p())),input:p,path:[p],inst:t});continue}const _=y.value,T=e.valueType._zod.run({value:i[p],issues:[]},n);T instanceof Promise?o.push(T.then(E=>{E.issues.length&&r.issues.push(...Nw(p,E.issues)),r.value[_]=E.value})):(T.issues.length&&r.issues.push(...Nw(p,T.issues)),r.value[_]=T.value)}let f;for(const p in i)s.has(p)||(f=f??[],f.push(p));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"&&Ixe.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(_=>Up(_,n,$p())),input:s,path:[s],inst:t});continue}const y=e.valueType._zod.run({value:i[s],issues:[]},n);y instanceof Promise?o.push(y.then(_=>{_.issues.length&&r.issues.push(...Nw(s,_.issues)),r.value[f.value]=_.value})):(y.issues.length&&r.issues.push(...Nw(s,y.issues)),r.value[f.value]=y.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Q8e=Er("$ZodEnum",(t,e)=>{so.init(t,e);const r=bxe(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>lVe.has(typeof i)).map(i=>typeof i=="string"?$1(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{const c=i.value;return n.has(c)||i.issues.push({code:"invalid_value",values:r,input:c,inst:t}),i}}),J8e=Er("$ZodLiteral",(t,e)=>{if(so.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"?$1(n):n?$1(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{const o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),eqe=Er("$ZodTransform",(t,e)=>{so.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new vxe(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 t1;return r.value=i,r.fallback=!0,r}});function Zte(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const Fxe=Er("$ZodOptional",(t,e)=>{so.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Zs(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Zs(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${_7(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){const i=r.value,o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(c=>Zte(c,i)):Zte(o,i)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),tqe=Er("$ZodExactOptional",(t,e)=>{Fxe.init(t,e),Zs(t._zod,"values",()=>e.innerType._zod.values),Zs(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),rqe=Er("$ZodNullable",(t,e)=>{so.init(t,e),Zs(t._zod,"optin",()=>e.innerType._zod.optin),Zs(t._zod,"optout",()=>e.innerType._zod.optout),Zs(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${_7(r.source)}|null)$`):void 0}),Zs(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)}),nqe=Er("$ZodDefault",(t,e)=>{so.init(t,e),t._zod.optin="optional",Zs(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(o=>Xte(o,e)):Xte(i,e)}});function Xte(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const iqe=Er("$ZodPrefault",(t,e)=>{so.init(t,e),t._zod.optin="optional",Zs(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))}),sqe=Er("$ZodNonOptional",(t,e)=>{so.init(t,e),Zs(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(o=>Qte(o,t)):Qte(i,t)}});function Qte(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 aqe=Er("$ZodCatch",(t,e)=>{so.init(t,e),t._zod.optin="optional",Zs(t._zod,"optout",()=>e.innerType._zod.optout),Zs(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(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(c=>Up(c,n,$p()))},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(o=>Up(o,n,$p()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),oqe=Er("$ZodPipe",(t,e)=>{so.init(t,e),Zs(t._zod,"values",()=>e.in._zod.values),Zs(t._zod,"optin",()=>e.in._zod.optin),Zs(t._zod,"optout",()=>e.out._zod.optout),Zs(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){const o=e.out._zod.run(r,n);return o instanceof Promise?o.then(c=>VP(c,e.in,n)):VP(o,e.in,n)}const i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>VP(o,e.out,n)):VP(i,e.out,n)}});function VP(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 lqe=Er("$ZodReadonly",(t,e)=>{so.init(t,e),Zs(t._zod,"propValues",()=>e.innerType._zod.propValues),Zs(t._zod,"values",()=>e.innerType._zod.values),Zs(t._zod,"optin",()=>{var r,n;return(n=(r=e.innerType)==null?void 0:r._zod)==null?void 0:n.optin}),Zs(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(Jte):Jte(i)}});function Jte(t){return t.value=Object.freeze(t.value),t}const cqe=Er("$ZodCustom",(t,e)=>{Lu.init(t,e),so.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(o=>ere(o,r,n,t));ere(i,r,n,t)}});function ere(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(Fj(i))}}var tre;class uqe{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 dqe(){return new uqe}(tre=globalThis).__zod_globalRegistry??(tre.__zod_globalRegistry=dqe());const yA=globalThis.__zod_globalRegistry;function hqe(t,e){return new t({type:"string",...Un(e)})}function fqe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Un(e)})}function rre(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Un(e)})}function mqe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Un(e)})}function pqe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Un(e)})}function gqe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Un(e)})}function yqe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Un(e)})}function xqe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Un(e)})}function _qe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Un(e)})}function vqe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Un(e)})}function bqe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Un(e)})}function wqe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Un(e)})}function Sqe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Un(e)})}function Tqe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Un(e)})}function Eqe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Un(e)})}function Aqe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Un(e)})}function jqe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Un(e)})}function kqe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Un(e)})}function Cqe(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Un(e)})}function Iqe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Un(e)})}function Nqe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Un(e)})}function Pqe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Un(e)})}function Rqe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Un(e)})}function Lqe(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Un(e)})}function Dqe(t,e){return new t({type:"string",format:"date",check:"string_format",...Un(e)})}function Mqe(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Un(e)})}function Oqe(t,e){return new t({type:"string",format:"duration",check:"string_format",...Un(e)})}function Fqe(t,e){return new t({type:"number",checks:[],...Un(e)})}function Bqe(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Un(e)})}function zqe(t,e){return new t({type:"boolean",...Un(e)})}function $qe(t){return new t({type:"unknown"})}function Uqe(t,e){return new t({type:"never",...Un(e)})}function nre(t,e){return new Pxe({check:"less_than",...Un(e),value:t,inclusive:!1})}function pz(t,e){return new Pxe({check:"less_than",...Un(e),value:t,inclusive:!0})}function ire(t,e){return new Rxe({check:"greater_than",...Un(e),value:t,inclusive:!1})}function gz(t,e){return new Rxe({check:"greater_than",...Un(e),value:t,inclusive:!0})}function sre(t,e){return new n8e({check:"multiple_of",...Un(e),value:t})}function Bxe(t,e){return new s8e({check:"max_length",...Un(e),maximum:t})}function DD(t,e){return new a8e({check:"min_length",...Un(e),minimum:t})}function zxe(t,e){return new o8e({check:"length_equals",...Un(e),length:t})}function Vqe(t,e){return new l8e({check:"string_format",format:"regex",...Un(e),pattern:t})}function qqe(t){return new c8e({check:"string_format",format:"lowercase",...Un(t)})}function Gqe(t){return new u8e({check:"string_format",format:"uppercase",...Un(t)})}function Hqe(t,e){return new d8e({check:"string_format",format:"includes",...Un(e),includes:t})}function Wqe(t,e){return new h8e({check:"string_format",format:"starts_with",...Un(e),prefix:t})}function Kqe(t,e){return new f8e({check:"string_format",format:"ends_with",...Un(e),suffix:t})}function HS(t){return new m8e({check:"overwrite",tx:t})}function Yqe(t){return HS(e=>e.normalize(t))}function Zqe(){return HS(t=>t.trim())}function Xqe(){return HS(t=>t.toLowerCase())}function Qqe(){return HS(t=>t.toUpperCase())}function Jqe(){return HS(t=>aVe(t))}function eGe(t,e,r){return new t({type:"array",element:e,...Un(r)})}function tGe(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Un(r)})}function rGe(t,e){const r=nGe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(Fj(i,n.value,r._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(Fj(o))}},t(n.value,n)),e);return r}function nGe(t,e){const r=new Lu({check:"custom",...Un(e)});return r._zod.check=t,r}function $xe(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)??yA,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 Go(t,e,r={path:[],schemaPath:[]}){var y,_;var n;const i=t._zod.def,o=e.seen.get(t);if(o)return o.count++,r.schemaPath.includes(t)&&(o.cycle=r.path),o.schema;const c={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,c);const s=(_=(y=t._zod).toJSONSchema)==null?void 0:_.call(y);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 k=c.schema,P=e.processors[i.type];if(!P)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);P(t,e,k,T)}const E=t._zod.parent;E&&(c.ref||(c.ref=E),Go(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"&&Bc(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 Uxe(t,e){var c,s,f,p;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 y of t.seen.entries()){const _=(c=t.metadataRegistry.get(y[0]))==null?void 0:c.id;if(_){const T=n.get(_);if(T&&T!==y[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(_,y[0])}}const i=y=>{var P;const _=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const R=(P=t.external.registry.get(y[0]))==null?void 0:P.id,D=t.external.uri??(B=>B);if(R)return{ref:D(R)};const M=y[1].defId??y[1].schema.id??`schema${t.counter++}`;return y[1].defId=M,{defId:M,ref:`${D("__shared")}#/${_}/${M}`}}if(y[1]===r)return{ref:"#"};const E=`#/${_}/`,k=y[1].schema.id??`__schema${t.counter++}`;return{defId:k,ref:E+k}},o=y=>{if(y[1].schema.$ref)return;const _=y[1],{ref:T,defId:E}=i(y);_.def={..._.schema},E&&(_.defId=E);const k=_.schema;for(const P in k)delete k[P];k.$ref=T};if(t.cycles==="throw")for(const y of t.seen.entries()){const _=y[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 y of t.seen.entries()){const _=y[1];if(e===y[0]){o(y);continue}if(t.external){const E=(f=t.external.registry.get(y[0]))==null?void 0:f.id;if(e!==y[0]&&E){o(y);continue}}if((p=t.metadataRegistry.get(y[0]))==null?void 0:p.id){o(y);continue}if(_.cycle){o(y);continue}if(_.count>1&&t.reused==="ref"){o(y);continue}}}function Vxe(t,e){var s,f,p,y;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,k={...E},P=T.ref;if(T.ref=null,P){n(P);const D=t.seen.get(P),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,k),_._zod.parent===P)for(const V in E)V==="$ref"||V==="allOf"||V in k||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!==P){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 o=(p=t.metadataRegistry.get(e))==null?void 0:p.id;o!==void 0&&i.id===o&&delete i.id;const c=((y=t.external)==null?void 0:y.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:MD(e,"input",t.processors),output:MD(e,"output",t.processors)}},enumerable:!1,writable:!1}),_}catch{throw new Error("Error converting schema to JSON.")}}function Bc(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 Bc(n.element,r);if(n.type==="set")return Bc(n.valueType,r);if(n.type==="lazy")return Bc(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 Bc(n.innerType,r);if(n.type==="intersection")return Bc(n.left,r)||Bc(n.right,r);if(n.type==="record"||n.type==="map")return Bc(n.keyType,r)||Bc(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Bc(n.in,r)||Bc(n.out,r);if(n.type==="object"){for(const i in n.shape)if(Bc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(Bc(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(Bc(i,r))return!0;return!!(n.rest&&Bc(n.rest,r))}return!1}const iGe=(t,e={})=>r=>{const n=$xe({...r,processors:e});return Go(t,n),Uxe(n,t),Vxe(n,t)},MD=(t,e,r={})=>n=>{const{libraryOptions:i,target:o}=n??{},c=$xe({...i??{},target:o,io:e,processors:r});return Go(t,c),Uxe(c,t),Vxe(c,t)},sGe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},aGe=(t,e,r,n)=>{const i=r;i.type="string";const{minimum:o,maximum:c,format:s,patterns:f,contentEncoding:p}=t._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof c=="number"&&(i.maxLength=c),s&&(i.format=sGe[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),p&&(i.contentEncoding=p),f&&f.size>0){const y=[...f];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(_=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))])}},oGe=(t,e,r,n)=>{const i=r,{minimum:o,maximum:c,format:s,multipleOf:f,exclusiveMaximum:p,exclusiveMinimum:y}=t._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number";const _=typeof y=="number"&&y>=(o??Number.NEGATIVE_INFINITY),T=typeof p=="number"&&p<=(c??Number.POSITIVE_INFINITY),E=e.target==="draft-04"||e.target==="openapi-3.0";_?E?(i.minimum=y,i.exclusiveMinimum=!0):i.exclusiveMinimum=y:typeof o=="number"&&(i.minimum=o),T?E?(i.maximum=p,i.exclusiveMaximum=!0):i.exclusiveMaximum=p:typeof c=="number"&&(i.maximum=c),typeof f=="number"&&(i.multipleOf=f)},lGe=(t,e,r,n)=>{r.type="boolean"},cGe=(t,e,r,n)=>{r.not={}},uGe=(t,e,r,n)=>{},dGe=(t,e,r,n)=>{const i=t._zod.def,o=bxe(i.entries);o.every(c=>typeof c=="number")&&(r.type="number"),o.every(c=>typeof c=="string")&&(r.type="string"),r.enum=o},hGe=(t,e,r,n)=>{const i=t._zod.def,o=[];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");o.push(Number(c))}else o.push(c);if(o.length!==0)if(o.length===1){const c=o[0];r.type=c===null?"null":typeof c,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[c]:r.const=c}else o.every(c=>typeof c=="number")&&(r.type="number"),o.every(c=>typeof c=="string")&&(r.type="string"),o.every(c=>typeof c=="boolean")&&(r.type="boolean"),o.every(c=>c===null)&&(r.type="null"),r.enum=o},fGe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},mGe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},pGe=(t,e,r,n)=>{const i=r,o=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=Go(o.element,e,{...n,path:[...n.path,"items"]})},gGe=(t,e,r,n)=>{var p;const i=r,o=t._zod.def;i.type="object",i.properties={};const c=o.shape;for(const y in c)i.properties[y]=Go(c[y],e,{...n,path:[...n.path,"properties",y]});const s=new Set(Object.keys(c)),f=new Set([...s].filter(y=>{const _=o.shape[y]._zod;return e.io==="input"?_.optin===void 0:_.optout===void 0}));f.size>0&&(i.required=Array.from(f)),((p=o.catchall)==null?void 0:p._zod.def.type)==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Go(o.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},yGe=(t,e,r,n)=>{const i=t._zod.def,o=i.inclusive===!1,c=i.options.map((s,f)=>Go(s,e,{...n,path:[...n.path,o?"oneOf":"anyOf",f]}));o?r.oneOf=c:r.anyOf=c},xGe=(t,e,r,n)=>{const i=t._zod.def,o=Go(i.left,e,{...n,path:[...n.path,"allOf",0]}),c=Go(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=p=>"allOf"in p&&Object.keys(p).length===1,f=[...s(o)?o.allOf:[o],...s(c)?c.allOf:[c]];r.allOf=f},_Ge=(t,e,r,n)=>{const i=r,o=t._zod.def;i.type="object";const c=o.keyType,s=c._zod.bag,f=s==null?void 0:s.patterns;if(o.mode==="loose"&&f&&f.size>0){const y=Go(o.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const _ of f)i.patternProperties[_.source]=y}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Go(o.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Go(o.valueType,e,{...n,path:[...n.path,"additionalProperties"]});const p=c._zod.values;if(p){const y=[...p].filter(_=>typeof _=="string"||typeof _=="number");y.length>0&&(i.required=y)}},vGe=(t,e,r,n)=>{const i=t._zod.def,o=Go(i.innerType,e,n),c=e.seen.get(t);e.target==="openapi-3.0"?(c.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},bGe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},wGe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},SGe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},TGe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.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},EGe=(t,e,r,n)=>{const i=t._zod.def,o=i.in._zod.traits.has("$ZodTransform"),c=e.io==="input"?o?i.out:i.in:i.out;Go(c,e,n);const s=e.seen.get(t);s.ref=c},AGe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.readOnly=!0},qxe=(t,e,r,n)=>{const i=t._zod.def;Go(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},jGe=Er("ZodISODateTime",(t,e)=>{k8e.init(t,e),oo.init(t,e)});function kGe(t){return Lqe(jGe,t)}const CGe=Er("ZodISODate",(t,e)=>{C8e.init(t,e),oo.init(t,e)});function IGe(t){return Dqe(CGe,t)}const NGe=Er("ZodISOTime",(t,e)=>{I8e.init(t,e),oo.init(t,e)});function PGe(t){return Mqe(NGe,t)}const RGe=Er("ZodISODuration",(t,e)=>{N8e.init(t,e),oo.init(t,e)});function LGe(t){return Oqe(RGe,t)}const Gxe=(t,e)=>{Exe.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>vVe(t,r)},flatten:{value:r=>_Ve(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,cV,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,cV,2)}},isEmpty:{get(){return t.issues.length===0}}})},DGe=Er("ZodError",Gxe),ch=Er("ZodError",Gxe,{Parent:Error}),MGe=b7(ch),OGe=w7(ch),FGe=p3(ch),BGe=g3(ch),zGe=SVe(ch),$Ge=TVe(ch),UGe=EVe(ch),VGe=AVe(ch),qGe=jVe(ch),GGe=kVe(ch),HGe=CVe(ch),WGe=IVe(ch),are=new WeakMap;function yC(t,e,r){const n=Object.getPrototypeOf(t);let i=are.get(n);if(i||(i=new Set,are.set(n,i)),!i.has(e)){i.add(e);for(const o in r){const c=r[o];Object.defineProperty(n,o,{configurable:!0,enumerable:!1,get(){const s=c.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}const ao=Er("ZodType",(t,e)=>(so.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:MD(t,"input"),output:MD(t,"output")}}),t.toJSONSchema=iGe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>MGe(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>FGe(t,r,n),t.parseAsync=async(r,n)=>OGe(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>BGe(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>zGe(t,r,n),t.decode=(r,n)=>$Ge(t,r,n),t.encodeAsync=async(r,n)=>UGe(t,r,n),t.decodeAsync=async(r,n)=>VGe(t,r,n),t.safeEncode=(r,n)=>qGe(t,r,n),t.safeDecode=(r,n)=>GGe(t,r,n),t.safeEncodeAsync=async(r,n)=>HGe(t,r,n),t.safeDecodeAsync=async(r,n)=>WGe(t,r,n),yC(t,"ZodType",{check(...r){const n=this.def;return this.clone(yx(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 xx(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(V9e(r,n))},superRefine(r,n){return this.check(q9e(r,n))},overwrite(r){return this.check(HS(r))},optional(){return ure(this)},exactOptional(){return I9e(this)},nullable(){return dre(this)},nullish(){return ure(dre(this))},nonoptional(r){return M9e(this,r)},array(){return _9e(this)},or(r){return w9e([this,r])},and(r){return T9e(this,r)},transform(r){return hre(this,k9e(r))},default(r){return R9e(this,r)},prefault(r){return D9e(this,r)},catch(r){return F9e(this,r)},pipe(r){return hre(this,r)},readonly(){return $9e(this)},describe(r){const n=this.clone();return yA.add(n,{description:r}),n},meta(...r){if(r.length===0)return yA.get(this);const n=this.clone();return yA.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=yA.get(t))==null?void 0:r.description},configurable:!0}),t)),Hxe=Er("_ZodString",(t,e)=>{S7.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(n,i,o)=>aGe(t,n,i);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,yC(t,"_ZodString",{regex(...n){return this.check(Vqe(...n))},includes(...n){return this.check(Hqe(...n))},startsWith(...n){return this.check(Wqe(...n))},endsWith(...n){return this.check(Kqe(...n))},min(...n){return this.check(DD(...n))},max(...n){return this.check(Bxe(...n))},length(...n){return this.check(zxe(...n))},nonempty(...n){return this.check(DD(1,...n))},lowercase(n){return this.check(qqe(n))},uppercase(n){return this.check(Gqe(n))},trim(){return this.check(Zqe())},normalize(...n){return this.check(Yqe(...n))},toLowerCase(){return this.check(Xqe())},toUpperCase(){return this.check(Qqe())},slugify(){return this.check(Jqe())}})}),KGe=Er("ZodString",(t,e)=>{S7.init(t,e),Hxe.init(t,e),t.email=r=>t.check(fqe(YGe,r)),t.url=r=>t.check(xqe(ZGe,r)),t.jwt=r=>t.check(Rqe(d9e,r)),t.emoji=r=>t.check(_qe(XGe,r)),t.guid=r=>t.check(rre(ore,r)),t.uuid=r=>t.check(mqe(qP,r)),t.uuidv4=r=>t.check(pqe(qP,r)),t.uuidv6=r=>t.check(gqe(qP,r)),t.uuidv7=r=>t.check(yqe(qP,r)),t.nanoid=r=>t.check(vqe(QGe,r)),t.guid=r=>t.check(rre(ore,r)),t.cuid=r=>t.check(bqe(JGe,r)),t.cuid2=r=>t.check(wqe(e9e,r)),t.ulid=r=>t.check(Sqe(t9e,r)),t.base64=r=>t.check(Iqe(l9e,r)),t.base64url=r=>t.check(Nqe(c9e,r)),t.xid=r=>t.check(Tqe(r9e,r)),t.ksuid=r=>t.check(Eqe(n9e,r)),t.ipv4=r=>t.check(Aqe(i9e,r)),t.ipv6=r=>t.check(jqe(s9e,r)),t.cidrv4=r=>t.check(kqe(a9e,r)),t.cidrv6=r=>t.check(Cqe(o9e,r)),t.e164=r=>t.check(Pqe(u9e,r)),t.datetime=r=>t.check(kGe(r)),t.date=r=>t.check(IGe(r)),t.time=r=>t.check(PGe(r)),t.duration=r=>t.check(LGe(r))});function Ji(t){return hqe(KGe,t)}const oo=Er("ZodStringFormat",(t,e)=>{Va.init(t,e),Hxe.init(t,e)}),YGe=Er("ZodEmail",(t,e)=>{_8e.init(t,e),oo.init(t,e)}),ore=Er("ZodGUID",(t,e)=>{y8e.init(t,e),oo.init(t,e)}),qP=Er("ZodUUID",(t,e)=>{x8e.init(t,e),oo.init(t,e)}),ZGe=Er("ZodURL",(t,e)=>{v8e.init(t,e),oo.init(t,e)}),XGe=Er("ZodEmoji",(t,e)=>{b8e.init(t,e),oo.init(t,e)}),QGe=Er("ZodNanoID",(t,e)=>{w8e.init(t,e),oo.init(t,e)}),JGe=Er("ZodCUID",(t,e)=>{S8e.init(t,e),oo.init(t,e)}),e9e=Er("ZodCUID2",(t,e)=>{T8e.init(t,e),oo.init(t,e)}),t9e=Er("ZodULID",(t,e)=>{E8e.init(t,e),oo.init(t,e)}),r9e=Er("ZodXID",(t,e)=>{A8e.init(t,e),oo.init(t,e)}),n9e=Er("ZodKSUID",(t,e)=>{j8e.init(t,e),oo.init(t,e)}),i9e=Er("ZodIPv4",(t,e)=>{P8e.init(t,e),oo.init(t,e)}),s9e=Er("ZodIPv6",(t,e)=>{R8e.init(t,e),oo.init(t,e)}),a9e=Er("ZodCIDRv4",(t,e)=>{L8e.init(t,e),oo.init(t,e)}),o9e=Er("ZodCIDRv6",(t,e)=>{D8e.init(t,e),oo.init(t,e)}),l9e=Er("ZodBase64",(t,e)=>{M8e.init(t,e),oo.init(t,e)}),c9e=Er("ZodBase64URL",(t,e)=>{F8e.init(t,e),oo.init(t,e)}),u9e=Er("ZodE164",(t,e)=>{B8e.init(t,e),oo.init(t,e)}),d9e=Er("ZodJWT",(t,e)=>{$8e.init(t,e),oo.init(t,e)}),Wxe=Er("ZodNumber",(t,e)=>{Dxe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(n,i,o)=>oGe(t,n,i),yC(t,"ZodNumber",{gt(n,i){return this.check(ire(n,i))},gte(n,i){return this.check(gz(n,i))},min(n,i){return this.check(gz(n,i))},lt(n,i){return this.check(nre(n,i))},lte(n,i){return this.check(pz(n,i))},max(n,i){return this.check(pz(n,i))},int(n){return this.check(lre(n))},safe(n){return this.check(lre(n))},positive(n){return this.check(ire(0,n))},nonnegative(n){return this.check(gz(0,n))},negative(n){return this.check(nre(0,n))},nonpositive(n){return this.check(pz(0,n))},multipleOf(n,i){return this.check(sre(n,i))},step(n,i){return this.check(sre(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 $A(t){return Fqe(Wxe,t)}const h9e=Er("ZodNumberFormat",(t,e)=>{U8e.init(t,e),Wxe.init(t,e)});function lre(t){return Bqe(h9e,t)}const f9e=Er("ZodBoolean",(t,e)=>{V8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lGe(t,r,n)});function m9e(t){return zqe(f9e,t)}const p9e=Er("ZodUnknown",(t,e)=>{q8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uGe()});function dV(){return $qe(p9e)}const g9e=Er("ZodNever",(t,e)=>{G8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cGe(t,r,n)});function y9e(t){return Uqe(g9e,t)}const x9e=Er("ZodArray",(t,e)=>{H8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>pGe(t,r,n,i),t.element=e.element,yC(t,"ZodArray",{min(r,n){return this.check(DD(r,n))},nonempty(r){return this.check(DD(1,r))},max(r,n){return this.check(Bxe(r,n))},length(r,n){return this.check(zxe(r,n))},unwrap(){return this.element}})});function _9e(t,e){return eGe(x9e,t,e)}const v9e=Er("ZodObject",(t,e)=>{K8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gGe(t,r,n,i),Zs(t,"shape",()=>e.shape),yC(t,"ZodObject",{keyof(){return x3(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:dV()})},loose(){return this.clone({...this._zod.def,catchall:dV()})},strict(){return this.clone({...this._zod.def,catchall:y9e()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return fVe(this,r)},safeExtend(r){return mVe(this,r)},merge(r){return pVe(this,r)},pick(r){return dVe(this,r)},omit(r){return hVe(this,r)},partial(...r){return gVe(Kxe,this,r[0])},required(...r){return yVe(Yxe,this,r[0])}})});function _x(t,e){const r={type:"object",shape:t??{},...Un(e)};return new v9e(r)}const b9e=Er("ZodUnion",(t,e)=>{Y8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yGe(t,r,n,i),t.options=e.options});function w9e(t,e){return new b9e({type:"union",options:t,...Un(e)})}const S9e=Er("ZodIntersection",(t,e)=>{Z8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xGe(t,r,n,i)});function T9e(t,e){return new S9e({type:"intersection",left:t,right:e})}const cre=Er("ZodRecord",(t,e)=>{X8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_Ge(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function E9e(t,e,r){return!e||!e._zod?new cre({type:"record",keyType:Ji(),valueType:t,...Un(e)}):new cre({type:"record",keyType:t,valueType:e,...Un(r)})}const hV=Er("ZodEnum",(t,e)=>{Q8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(n,i,o)=>dGe(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 o={};for(const c of n)if(r.has(c))o[c]=e.entries[c];else throw new Error(`Key ${c} not found in enum`);return new hV({...e,checks:[],...Un(i),entries:o})},t.exclude=(n,i)=>{const o={...e.entries};for(const c of n)if(r.has(c))delete o[c];else throw new Error(`Key ${c} not found in enum`);return new hV({...e,checks:[],...Un(i),entries:o})}});function x3(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new hV({type:"enum",entries:r,...Un(e)})}const A9e=Er("ZodLiteral",(t,e)=>{J8e.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hGe(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 OD(t,e){return new A9e({type:"literal",values:Array.isArray(t)?t:[t],...Un(e)})}const j9e=Er("ZodTransform",(t,e)=>{eqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mGe(t,r),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new vxe(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(Fj(o,r.value,e));else{const c=o;c.fatal&&(c.continue=!1),c.code??(c.code="custom"),c.input??(c.input=r.value),c.inst??(c.inst=t),r.issues.push(Fj(c))}};const i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function k9e(t){return new j9e({type:"transform",transform:t})}const Kxe=Er("ZodOptional",(t,e)=>{Fxe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qxe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function ure(t){return new Kxe({type:"optional",innerType:t})}const C9e=Er("ZodExactOptional",(t,e)=>{tqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qxe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function I9e(t){return new C9e({type:"optional",innerType:t})}const N9e=Er("ZodNullable",(t,e)=>{rqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function dre(t){return new N9e({type:"nullable",innerType:t})}const P9e=Er("ZodDefault",(t,e)=>{nqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function R9e(t,e){return new P9e({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Sxe(e)}})}const L9e=Er("ZodPrefault",(t,e)=>{iqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>SGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function D9e(t,e){return new L9e({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Sxe(e)}})}const Yxe=Er("ZodNonOptional",(t,e)=>{sqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function M9e(t,e){return new Yxe({type:"nonoptional",innerType:t,...Un(e)})}const O9e=Er("ZodCatch",(t,e)=>{aqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>TGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function F9e(t,e){return new O9e({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const B9e=Er("ZodPipe",(t,e)=>{oqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>EGe(t,r,n,i),t.in=e.in,t.out=e.out});function hre(t,e){return new B9e({type:"pipe",in:t,out:e})}const z9e=Er("ZodReadonly",(t,e)=>{lqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AGe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function $9e(t){return new z9e({type:"readonly",innerType:t})}const U9e=Er("ZodCustom",(t,e)=>{cqe.init(t,e),ao.init(t,e),t._zod.processJSONSchema=(r,n,i)=>fGe(t,r)});function V9e(t,e={}){return tGe(U9e,t,e)}function q9e(t,e){return rGe(t,e)}var G9e="Label",Zxe=I.forwardRef((t,e)=>a.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())}}));Zxe.displayName=G9e;var Xxe=Zxe;const H9e=kS("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Mr=I.forwardRef(({className:t,...e},r)=>a.jsx(Xxe,{ref:r,className:sr(H9e(),t),...e}));Mr.displayName=Xxe.displayName;const T7=FUe,Qxe=I.createContext({}),sl=({...t})=>a.jsx(Qxe.Provider,{value:{name:t.name},children:a.jsx(UUe,{...t})}),_3=()=>{const t=I.useContext(Qxe),e=I.useContext(Jxe),{getFieldState:r,formState:n}=m3(),i=r(t.name,n);if(!t)throw new Error("useFormField should be used within ");const{id:o}=e;return{id:o,name:t.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},Jxe=I.createContext({}),zo=I.forwardRef(({className:t,...e},r)=>{const n=I.useId();return a.jsx(Jxe.Provider,{value:{id:n},children:a.jsx("div",{ref:r,className:sr("space-y-2",t),...e})})});zo.displayName="FormItem";const $o=I.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=_3();return a.jsx(Mr,{ref:r,className:sr(n&&"text-destructive",t),htmlFor:i,...e})});$o.displayName="FormLabel";const Uo=I.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=_3();return a.jsx(efe,{ref:e,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});Uo.displayName="FormControl";const cL=I.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=_3();return a.jsx("p",{ref:r,id:n,className:sr("text-sm text-muted-foreground",t),...e})});cL.displayName="FormDescription";const Qh=I.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:o}=_3(),c=i?String(i==null?void 0:i.message):e;return c?a.jsx("p",{ref:n,id:o,className:sr("text-sm font-medium text-destructive",t),...r,children:c}):null});Qh.displayName="FormMessage";const $r=I.forwardRef(({className:t,type:e,...r},n)=>a.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}));$r.displayName="Input";function xC(t){const e=I.useRef({value:t,previous:t});return I.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var W9e=[" ","Enter","ArrowUp","ArrowDown"],K9e=[" ","Enter"],V_="Select",[v3,b3,Y9e]=Zk(V_),[WS,HVt]=Yo(V_,[Y9e,mx]),w3=mx(),[Z9e,vx]=WS(V_),[X9e,Q9e]=WS(V_),e0e=t=>{const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:o,value:c,defaultValue:s,onValueChange:f,dir:p,name:y,autoComplete:_,disabled:T,required:E,form:k}=t,P=w3(e),[R,D]=I.useState(null),[M,B]=I.useState(null),[V,G]=I.useState(!1),W=av(p),[Z,Q]=dd({prop:n,defaultProp:i??!1,onChange:o,caller:V_}),[re,se]=dd({prop:c,defaultProp:s,onChange:f,caller:V_}),ue=I.useRef(null),_e=R?k||!!R.closest("form"):!0,[we,Ce]=I.useState(new Set),Me=Array.from(we).map(Ae=>Ae.props.value).join(";");return a.jsx(qO,{...P,children:a.jsxs(Z9e,{required:E,scope:e,trigger:R,onTriggerChange:D,valueNode:M,onValueNodeChange:B,valueNodeHasChildren:V,onValueNodeHasChildrenChange:G,contentId:Dl(),value:re,onValueChange:se,open:Z,onOpenChange:Q,dir:W,triggerPointerDownPosRef:ue,disabled:T,children:[a.jsx(v3.Provider,{scope:e,children:a.jsx(X9e,{scope:t.__scopeSelect,onNativeOptionAdd:I.useCallback(Ae=>{Ce(be=>new Set(be).add(Ae))},[]),onNativeOptionRemove:I.useCallback(Ae=>{Ce(be=>{const me=new Set(be);return me.delete(Ae),me})},[]),children:r})}),_e?a.jsxs(E0e,{"aria-hidden":!0,required:E,tabIndex:-1,name:y,autoComplete:_,value:re,onChange:Ae=>se(Ae.target.value),disabled:T,form:k,children:[re===void 0?a.jsx("option",{value:""}):null,Array.from(we)]},Me):null]})})};e0e.displayName=V_;var t0e="SelectTrigger",r0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,disabled:n=!1,...i}=t,o=w3(r),c=vx(t0e,r),s=c.disabled||n,f=Kn(e,c.onTriggerChange),p=b3(r),y=I.useRef("touch"),[_,T,E]=j0e(P=>{const R=p().filter(B=>!B.disabled),D=R.find(B=>B.value===c.value),M=k0e(R,P,D);M!==void 0&&c.onValueChange(M.value)}),k=P=>{s||(c.onOpenChange(!0),E()),P&&(c.triggerPointerDownPosRef.current={x:Math.round(P.pageX),y:Math.round(P.pageY)})};return a.jsx(lC,{asChild:!0,...o,children:a.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":A0e(c.value)?"":void 0,...i,ref:f,onClick:Or(i.onClick,P=>{P.currentTarget.focus(),y.current!=="mouse"&&k(P)}),onPointerDown:Or(i.onPointerDown,P=>{y.current=P.pointerType;const R=P.target;R.hasPointerCapture(P.pointerId)&&R.releasePointerCapture(P.pointerId),P.button===0&&P.ctrlKey===!1&&P.pointerType==="mouse"&&(k(P),P.preventDefault())}),onKeyDown:Or(i.onKeyDown,P=>{const R=_.current!=="";!(P.ctrlKey||P.altKey||P.metaKey)&&P.key.length===1&&T(P.key),!(R&&P.key===" ")&&W9e.includes(P.key)&&(k(),P.preventDefault())})})})});r0e.displayName=t0e;var n0e="SelectValue",i0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,children:o,placeholder:c="",...s}=t,f=vx(n0e,r),{onValueNodeHasChildrenChange:p}=f,y=o!==void 0,_=Kn(e,f.onValueNodeChange);return Po(()=>{p(y)},[p,y]),a.jsx(rn.span,{...s,ref:_,style:{pointerEvents:"none"},children:A0e(f.value)?a.jsx(a.Fragment,{children:c}):o})});i0e.displayName=n0e;var J9e="SelectIcon",s0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,children:n,...i}=t;return a.jsx(rn.span,{"aria-hidden":!0,...i,ref:e,children:n||"▼"})});s0e.displayName=J9e;var e7e="SelectPortal",a0e=t=>a.jsx(jS,{asChild:!0,...t});a0e.displayName=e7e;var q_="SelectContent",o0e=I.forwardRef((t,e)=>{const r=vx(q_,t.__scopeSelect),[n,i]=I.useState();if(Po(()=>{i(new DocumentFragment)},[]),!r.open){const o=n;return o?Yp.createPortal(a.jsx(l0e,{scope:t.__scopeSelect,children:a.jsx(v3.Slot,{scope:t.__scopeSelect,children:a.jsx("div",{children:t.children})})}),o):null}return a.jsx(c0e,{...t,ref:e})});o0e.displayName=q_;var Dh=10,[l0e,bx]=WS(q_),t7e="SelectContentImpl",r7e=Ky("SelectContent.RemoveScroll"),c0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:c,side:s,sideOffset:f,align:p,alignOffset:y,arrowPadding:_,collisionBoundary:T,collisionPadding:E,sticky:k,hideWhenDetached:P,avoidCollisions:R,...D}=t,M=vx(q_,r),[B,V]=I.useState(null),[G,W]=I.useState(null),Z=Kn(e,_t=>V(_t)),[Q,re]=I.useState(null),[se,ue]=I.useState(null),_e=b3(r),[we,Ce]=I.useState(!1),Me=I.useRef(!1);I.useEffect(()=>{if(B)return OO(B)},[B]),DO();const Ae=I.useCallback(_t=>{const[Vt,...pt]=_e().map(vt=>vt.ref.current),[Nt]=pt.slice(-1),er=document.activeElement;for(const vt of _t)if(vt===er||(vt==null||vt.scrollIntoView({block:"nearest"}),vt===Vt&&G&&(G.scrollTop=0),vt===Nt&&G&&(G.scrollTop=G.scrollHeight),vt==null||vt.focus(),document.activeElement!==er))return},[_e,G]),be=I.useCallback(()=>Ae([Q,B]),[Ae,Q,B]);I.useEffect(()=>{we&&be()},[we,be]);const{onOpenChange:me,triggerPointerDownPosRef:Pe}=M;I.useEffect(()=>{if(B){let _t={x:0,y:0};const Vt=Nt=>{var er,vt;_t={x:Math.abs(Math.round(Nt.pageX)-(((er=Pe.current)==null?void 0:er.x)??0)),y:Math.abs(Math.round(Nt.pageY)-(((vt=Pe.current)==null?void 0:vt.y)??0))}},pt=Nt=>{_t.x<=10&&_t.y<=10?Nt.preventDefault():B.contains(Nt.target)||me(!1),document.removeEventListener("pointermove",Vt),Pe.current=null};return Pe.current!==null&&(document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",pt,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",pt,{capture:!0})}}},[B,me,Pe]),I.useEffect(()=>{const _t=()=>me(!1);return window.addEventListener("blur",_t),window.addEventListener("resize",_t),()=>{window.removeEventListener("blur",_t),window.removeEventListener("resize",_t)}},[me]);const[Ie,Se]=j0e(_t=>{const Vt=_e().filter(er=>!er.disabled),pt=Vt.find(er=>er.ref.current===document.activeElement),Nt=k0e(Vt,_t,pt);Nt&&setTimeout(()=>Nt.ref.current.focus())}),ve=I.useCallback((_t,Vt,pt)=>{const Nt=!Me.current&&!pt;(M.value!==void 0&&M.value===Vt||Nt)&&(re(_t),Nt&&(Me.current=!0))},[M.value]),We=I.useCallback(()=>B==null?void 0:B.focus(),[B]),rt=I.useCallback((_t,Vt,pt)=>{const Nt=!Me.current&&!pt;(M.value!==void 0&&M.value===Vt||Nt)&&ue(_t)},[M.value]),at=n==="popper"?fV:u0e,Et=at===fV?{side:s,sideOffset:f,align:p,alignOffset:y,arrowPadding:_,collisionBoundary:T,collisionPadding:E,sticky:k,hideWhenDetached:P,avoidCollisions:R}:{};return a.jsx(l0e,{scope:r,content:B,viewport:G,onViewportChange:W,itemRefCallback:ve,selectedItem:Q,onItemLeave:We,itemTextRefCallback:rt,focusSelectedItem:be,selectedItemText:se,position:n,isPositioned:we,searchRef:Ie,children:a.jsx(rC,{as:r7e,allowPinchZoom:!0,children:a.jsx(tC,{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:a.jsx(rv,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:_t=>_t.preventDefault(),onDismiss:()=>M.onOpenChange(!1),children:a.jsx(at,{role:"listbox",id:M.contentId,"data-state":M.open?"open":"closed",dir:M.dir,onContextMenu:_t=>_t.preventDefault(),...D,...Et,onPlaced:()=>Ce(!0),ref:Z,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&&Se(_t.key),["ArrowUp","ArrowDown","Home","End"].includes(_t.key)){let Nt=_e().filter(er=>!er.disabled).map(er=>er.ref.current);if(["ArrowUp","End"].includes(_t.key)&&(Nt=Nt.slice().reverse()),["ArrowUp","ArrowDown"].includes(_t.key)){const er=_t.target,vt=Nt.indexOf(er);Nt=Nt.slice(vt+1)}setTimeout(()=>Ae(Nt)),_t.preventDefault()}})})})})})})});c0e.displayName=t7e;var n7e="SelectItemAlignedPosition",u0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,onPlaced:n,...i}=t,o=vx(q_,r),c=bx(q_,r),[s,f]=I.useState(null),[p,y]=I.useState(null),_=Kn(e,Z=>y(Z)),T=b3(r),E=I.useRef(!1),k=I.useRef(!0),{viewport:P,selectedItem:R,selectedItemText:D,focusSelectedItem:M}=c,B=I.useCallback(()=>{if(o.trigger&&o.valueNode&&s&&p&&P&&R&&D){const Z=o.trigger.getBoundingClientRect(),Q=p.getBoundingClientRect(),re=o.valueNode.getBoundingClientRect(),se=D.getBoundingClientRect();if(o.dir!=="rtl"){const er=se.left-Q.left,vt=re.left-er,or=Z.left-vt,Sr=Z.width+or,nn=Math.max(Sr,Q.width),cr=window.innerWidth-Dh,xr=Oj(vt,[Dh,Math.max(Dh,cr-nn)]);s.style.minWidth=Sr+"px",s.style.left=xr+"px"}else{const er=Q.right-se.right,vt=window.innerWidth-re.right-er,or=window.innerWidth-Z.right-vt,Sr=Z.width+or,nn=Math.max(Sr,Q.width),cr=window.innerWidth-Dh,xr=Oj(vt,[Dh,Math.max(Dh,cr-nn)]);s.style.minWidth=Sr+"px",s.style.right=xr+"px"}const ue=T(),_e=window.innerHeight-Dh*2,we=P.scrollHeight,Ce=window.getComputedStyle(p),Me=parseInt(Ce.borderTopWidth,10),Ae=parseInt(Ce.paddingTop,10),be=parseInt(Ce.borderBottomWidth,10),me=parseInt(Ce.paddingBottom,10),Pe=Me+Ae+we+me+be,Ie=Math.min(R.offsetHeight*5,Pe),Se=window.getComputedStyle(P),ve=parseInt(Se.paddingTop,10),We=parseInt(Se.paddingBottom,10),rt=Z.top+Z.height/2-Dh,at=_e-rt,Et=R.offsetHeight/2,_t=R.offsetTop+Et,Vt=Me+Ae+_t,pt=Pe-Vt;if(Vt<=rt){const er=ue.length>0&&R===ue[ue.length-1].ref.current;s.style.bottom="0px";const vt=p.clientHeight-P.offsetTop-P.offsetHeight,or=Math.max(at,Et+(er?We:0)+vt+be),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,Me+P.offsetTop+(er?ve:0)+Et)+pt;s.style.height=or+"px",P.scrollTop=Vt-rt+P.offsetTop}s.style.margin=`${Dh}px 0`,s.style.minHeight=Ie+"px",s.style.maxHeight=_e+"px",n==null||n(),requestAnimationFrame(()=>E.current=!0)}},[T,o.trigger,o.valueNode,s,p,P,R,D,o.dir,n]);Po(()=>B(),[B]);const[V,G]=I.useState();Po(()=>{p&&G(window.getComputedStyle(p).zIndex)},[p]);const W=I.useCallback(Z=>{Z&&k.current===!0&&(B(),M==null||M(),k.current=!1)},[B,M]);return a.jsx(s7e,{scope:r,contentWrapper:s,shouldExpandOnScrollRef:E,onScrollButtonChange:W,children:a.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:V},children:a.jsx(rn.div,{...i,ref:_,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});u0e.displayName=n7e;var i7e="SelectPopperPosition",fV=I.forwardRef((t,e)=>{const{__scopeSelect:r,align:n="start",collisionPadding:i=Dh,...o}=t,c=w3(r);return a.jsx(GO,{...c,...o,ref:e,align:n,collisionPadding:i,style:{boxSizing:"border-box",...o.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)"}})});fV.displayName=i7e;var[s7e,E7]=WS(q_,{}),mV="SelectViewport",d0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,nonce:n,...i}=t,o=bx(mV,r),c=E7(mV,r),s=Kn(e,o.onViewportChange),f=I.useRef(0);return a.jsxs(a.Fragment,{children:[a.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}),a.jsx(v3.Slot,{scope:r,children:a.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,p=>{const y=p.currentTarget,{contentWrapper:_,shouldExpandOnScrollRef:T}=c;if(T!=null&&T.current&&_){const E=Math.abs(f.current-y.scrollTop);if(E>0){const k=window.innerHeight-Dh*2,P=parseFloat(_.style.minHeight),R=parseFloat(_.style.height),D=Math.max(P,R);if(D0?V:0,_.style.justifyContent="flex-end")}}}f.current=y.scrollTop})})})]})});d0e.displayName=mV;var h0e="SelectGroup",[a7e,o7e]=WS(h0e),f0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=Dl();return a.jsx(a7e,{scope:r,id:i,children:a.jsx(rn.div,{role:"group","aria-labelledby":i,...n,ref:e})})});f0e.displayName=h0e;var m0e="SelectLabel",p0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=o7e(m0e,r);return a.jsx(rn.div,{id:i.id,...n,ref:e})});p0e.displayName=m0e;var FD="SelectItem",[l7e,g0e]=WS(FD),y0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,value:n,disabled:i=!1,textValue:o,...c}=t,s=vx(FD,r),f=bx(FD,r),p=s.value===n,[y,_]=I.useState(o??""),[T,E]=I.useState(!1),k=Kn(e,M=>{var B;return(B=f.itemRefCallback)==null?void 0:B.call(f,M,n,i)}),P=Dl(),R=I.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 a.jsx(l7e,{scope:r,value:n,disabled:i,textId:P,isSelected:p,onItemTextChange:I.useCallback(M=>{_(B=>B||((M==null?void 0:M.textContent)??"").trim())},[]),children:a.jsx(v3.ItemSlot,{scope:r,value:n,disabled:i,textValue:y,children:a.jsx(rn.div,{role:"option","aria-labelledby":P,"data-highlighted":T?"":void 0,"aria-selected":p&&T,"data-state":p?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...c,ref:k,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===" "||(K9e.includes(M.key)&&D(),M.key===" "&&M.preventDefault())})})})})});y0e.displayName=FD;var xA="SelectItemText",x0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,...o}=t,c=vx(xA,r),s=bx(xA,r),f=g0e(xA,r),p=Q9e(xA,r),[y,_]=I.useState(null),T=Kn(e,D=>_(D),f.onItemTextChange,D=>{var M;return(M=s.itemTextRefCallback)==null?void 0:M.call(s,D,f.value,f.disabled)}),E=y==null?void 0:y.textContent,k=I.useMemo(()=>a.jsx("option",{value:f.value,disabled:f.disabled,children:E},f.value),[f.disabled,f.value,E]),{onNativeOptionAdd:P,onNativeOptionRemove:R}=p;return Po(()=>(P(k),()=>R(k)),[P,R,k]),a.jsxs(a.Fragment,{children:[a.jsx(rn.span,{id:f.textId,...o,ref:T}),f.isSelected&&c.valueNode&&!c.valueNodeHasChildren?Yp.createPortal(o.children,c.valueNode):null]})});x0e.displayName=xA;var _0e="SelectItemIndicator",v0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return g0e(_0e,r).isSelected?a.jsx(rn.span,{"aria-hidden":!0,...n,ref:e}):null});v0e.displayName=_0e;var pV="SelectScrollUpButton",b0e=I.forwardRef((t,e)=>{const r=bx(pV,t.__scopeSelect),n=E7(pV,t.__scopeSelect),[i,o]=I.useState(!1),c=Kn(e,n.onScrollButtonChange);return Po(()=>{if(r.viewport&&r.isPositioned){let s=function(){const p=f.scrollTop>0;o(p)};const f=r.viewport;return s(),f.addEventListener("scroll",s),()=>f.removeEventListener("scroll",s)}},[r.viewport,r.isPositioned]),i?a.jsx(S0e,{...t,ref:c,onAutoScroll:()=>{const{viewport:s,selectedItem:f}=r;s&&f&&(s.scrollTop=s.scrollTop-f.offsetHeight)}}):null});b0e.displayName=pV;var gV="SelectScrollDownButton",w0e=I.forwardRef((t,e)=>{const r=bx(gV,t.__scopeSelect),n=E7(gV,t.__scopeSelect),[i,o]=I.useState(!1),c=Kn(e,n.onScrollButtonChange);return Po(()=>{if(r.viewport&&r.isPositioned){let s=function(){const p=f.scrollHeight-f.clientHeight,y=Math.ceil(f.scrollTop)f.removeEventListener("scroll",s)}},[r.viewport,r.isPositioned]),i?a.jsx(S0e,{...t,ref:c,onAutoScroll:()=>{const{viewport:s,selectedItem:f}=r;s&&f&&(s.scrollTop=s.scrollTop+f.offsetHeight)}}):null});w0e.displayName=gV;var S0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,onAutoScroll:n,...i}=t,o=bx("SelectScrollButton",r),c=I.useRef(null),s=b3(r),f=I.useCallback(()=>{c.current!==null&&(window.clearInterval(c.current),c.current=null)},[]);return I.useEffect(()=>()=>f(),[f]),Po(()=>{var y;const p=s().find(_=>_.ref.current===document.activeElement);(y=p==null?void 0:p.ref.current)==null||y.scrollIntoView({block:"nearest"})},[s]),a.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 p;(p=o.onItemLeave)==null||p.call(o),c.current===null&&(c.current=window.setInterval(n,50))}),onPointerLeave:Or(i.onPointerLeave,()=>{f()})})}),c7e="SelectSeparator",T0e=I.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return a.jsx(rn.div,{"aria-hidden":!0,...n,ref:e})});T0e.displayName=c7e;var yV="SelectArrow",u7e=I.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=w3(r),o=vx(yV,r),c=bx(yV,r);return o.open&&c.position==="popper"?a.jsx(HO,{...i,...n,ref:e}):null});u7e.displayName=yV;var d7e="SelectBubbleInput",E0e=I.forwardRef(({__scopeSelect:t,value:e,...r},n)=>{const i=I.useRef(null),o=Kn(n,i),c=xC(e);return I.useEffect(()=>{const s=i.current;if(!s)return;const f=window.HTMLSelectElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&y){const _=new Event("change",{bubbles:!0});y.call(s,e),s.dispatchEvent(_)}},[c,e]),a.jsx(rn.select,{...r,style:{...afe,...r.style},ref:o,defaultValue:e})});E0e.displayName=d7e;function A0e(t){return t===""||t===void 0}function j0e(t){const e=po(t),r=I.useRef(""),n=I.useRef(0),i=I.useCallback(c=>{const s=r.current+c;e(s),function f(p){r.current=p,window.clearTimeout(n.current),p!==""&&(n.current=window.setTimeout(()=>f(""),1e3))}(s)},[e]),o=I.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return I.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,o]}function k0e(t,e,r){const i=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=h7e(t,Math.max(o,0));i.length===1&&(c=c.filter(p=>p!==r));const f=c.find(p=>p.textValue.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function h7e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var f7e=e0e,C0e=r0e,m7e=i0e,p7e=s0e,g7e=a0e,I0e=o0e,y7e=d0e,x7e=f0e,N0e=p0e,P0e=y0e,_7e=x0e,v7e=v0e,R0e=b0e,L0e=w0e,D0e=T0e;const _a=f7e,WVt=x7e,va=m7e,aa=I.forwardRef(({className:t,children:e,...r},n)=>a.jsxs(C0e,{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,a.jsx(p7e,{asChild:!0,children:a.jsx(wc,{className:"h-4 w-4 opacity-50"})})]}));aa.displayName=C0e.displayName;const M0e=I.forwardRef(({className:t,...e},r)=>a.jsx(R0e,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...e,children:a.jsx(HLe,{className:"h-4 w-4"})}));M0e.displayName=R0e.displayName;const O0e=I.forwardRef(({className:t,...e},r)=>a.jsx(L0e,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...e,children:a.jsx(wc,{className:"h-4 w-4"})}));O0e.displayName=L0e.displayName;const oa=I.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>a.jsx(g7e,{children:a.jsxs(I0e,{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:[a.jsx(M0e,{}),a.jsx(y7e,{className:sr("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),a.jsx(O0e,{})]})}));oa.displayName=I0e.displayName;const b7e=I.forwardRef(({className:t,...e},r)=>a.jsx(N0e,{ref:r,className:sr("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));b7e.displayName=N0e.displayName;const fn=I.forwardRef(({className:t,children:e,...r},n)=>a.jsxs(P0e,{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:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(v7e,{children:a.jsx(ko,{className:"h-4 w-4"})})}),a.jsx(_7e,{children:e})]}));fn.displayName=P0e.displayName;const w7e=I.forwardRef(({className:t,...e},r)=>a.jsx(D0e,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...e}));w7e.displayName=D0e.displayName;const S7e=_x({category:x3(["general","technology","crm","marketing"]),subject:Ji().min(5,"Subject must be at least 5 characters").max(200),description:Ji().min(20,"Please provide more details (at least 20 characters)").max(1e4,"Please keep the description under 10,000 characters")}),T7e={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function E7e({trigger:t}){const[e,r]=I.useState(!1),[n,i]=I.useState(!1),{user:o}=Gn(),c=m7({resolver:p7(S7e),defaultValues:{category:"general",subject:"",description:""}}),s=async f=>{if(!o){Gt.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:p}=await Re.from("support_tickets").insert({user_id:o.id,category:f.category,subject:f.subject,description:f.description});if(p)throw p;try{await Re.functions.invoke("support-ticket-notify",{body:{category:T7e[f.category],subject:f.subject}})}catch(y){console.log("Notification send attempted:",y)}Gt.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(p){console.error("Error submitting ticket:",p),Gt.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return a.jsxs(io,{open:e,onOpenChange:r,children:[a.jsx(Bye,{asChild:!0,children:t||a.jsxs(zt,{variant:"ghost",size:"icon",className:"relative",children:[a.jsx(cDe,{className:"h-5 w-5"}),a.jsx("span",{className:"sr-only",children:"Support"})]})}),a.jsxs(Ua,{className:"sm:max-w-[500px]",children:[a.jsxs(ml,{children:[a.jsx(Ko,{children:"Need Help?"}),a.jsx(gd,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),a.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[a.jsx(ai,{className:"h-4 w-4 text-muted-foreground"}),a.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",a.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),a.jsx(T7,{...c,children:a.jsxs("form",{onSubmit:c.handleSubmit(s),className:"space-y-4",children:[a.jsx(sl,{control:c.control,name:"category",render:({field:f})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Category"}),a.jsxs(_a,{onValueChange:f.onChange,defaultValue:f.value,children:[a.jsx(Uo,{children:a.jsx(aa,{children:a.jsx(va,{placeholder:"Select a category"})})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"general",children:"General Support"}),a.jsx(fn,{value:"technology",children:"Technology Support"}),a.jsx(fn,{value:"crm",children:"CRM Support"}),a.jsx(fn,{value:"marketing",children:"Marketing Support"})]})]}),a.jsx(Qh,{})]})}),a.jsx(sl,{control:c.control,name:"subject",render:({field:f})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Subject"}),a.jsx(Uo,{children:a.jsx($r,{placeholder:"Brief description of your issue",...f})}),a.jsx(Qh,{})]})}),a.jsx(sl,{control:c.control,name:"description",render:({field:f})=>{var p;return a.jsxs(zo,{children:[a.jsx($o,{children:"Description"}),a.jsx(Uo,{children:a.jsx(bd,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...f})}),a.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[(((p=f.value)==null?void 0:p.length)??0).toLocaleString()," / 10,000"]}),a.jsx(Qh,{})]})}}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(zt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),a.jsx(zt,{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 Ys(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function Cl(t,e){const r=On(t);return isNaN(e)?Ys(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function yd(t,e){const r=On(t);if(isNaN(e))return Ys(t,NaN);if(!e)return r;const n=r.getDate(),i=Ys(t,r.getTime());i.setMonth(r.getMonth()+e+1,0);const o=i.getDate();return n>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),n),r)}const A7=6048e5,A7e=864e5,j7=6e4,k7=36e5,j7e=1e3,GP=43200,fre=1440;let k7e={};function wx(){return k7e}function Sc(t,e){var s,f,p,y;const r=wx(),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??((y=(p=r.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,i=On(t),o=i.getDay(),c=(o=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function tx(t){const e=On(t);return e.setHours(0,0,0,0),e}function rx(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 Jh(t,e){const r=tx(t),n=tx(e),i=+r-rx(r),o=+n-rx(n);return Math.round((i-o)/A7e)}function C7e(t){const e=F0e(t),r=Ys(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),Vp(r)}function xV(t,e){const r=e*7;return Cl(t,r)}function I7e(t,e){return yd(t,e*12)}function N7e(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 uL(t,e){const r=On(t),n=On(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function C7(t){return Ys(t,Date.now())}function Jl(t,e){const r=tx(t),n=tx(e);return+r==+n}function I7(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function _V(t){if(!I7(t)&&typeof t!="number")return!1;const e=On(t);return!isNaN(Number(e))}function U1(t,e){const r=On(t),n=On(e),i=r.getFullYear()-n.getFullYear(),o=r.getMonth()-n.getMonth();return i*12+o}function R7e(t,e,r){const n=Sc(t,r),i=Sc(e,r),o=+n-rx(n),c=+i-rx(i);return Math.round((o-c)/A7)}function L7e(t,e){const r=On(t),n=On(e),i=mre(r,n),o=Math.abs(Jh(r,n));r.setDate(r.getDate()-i*o);const c=+(mre(r,n)===-i),s=i*(o-c);return s===0?0:s}function mre(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 D7e(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function M7e(t,e){return+On(t)-+On(e)}function O7e(t){const e=On(t);return e.setHours(23,59,59,999),e}function _C(t){const e=On(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function F7e(t){const e=On(t);return+O7e(e)==+_C(e)}function B7e(t,e){const r=On(t),n=On(e),i=uL(r,n),o=Math.abs(U1(r,n));let c;if(o<1)c=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-i*o);let s=uL(r,n)===-i;F7e(On(t))&&o===1&&uL(t,n)===1&&(s=!1),c=i*(o-Number(s))}return c===0?0:c}function z7e(t,e,r){const n=M7e(t,e)/1e3;return D7e(r==null?void 0:r.roundingMethod)(n)}function $7e(t,e){const r=On(t.start),n=On(t.end);let i=+r>+n;const o=i?+r:+n,c=i?n:r;c.setHours(0,0,0,0);let s=1;const f=[];for(;+c<=o;)f.push(On(c)),c.setDate(c.getDate()+s),c.setHours(0,0,0,0);return i?f.reverse():f}function tu(t){const e=On(t);return e.setDate(1),e.setHours(0,0,0,0),e}function B0e(t){const e=On(t),r=Ys(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function S3(t,e){var s,f,p,y;const r=wx(),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??((y=(p=r.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,i=On(t),o=i.getDay(),c=(o{let n;const i=U7e[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 yz(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const q7e={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},G7e={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},H7e={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},W7e={date:yz({formats:q7e,defaultWidth:"full"}),time:yz({formats:G7e,defaultWidth:"full"}),dateTime:yz({formats:H7e,defaultWidth:"full"})},K7e={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Y7e=(t,e,r,n)=>K7e[t];function $2(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 o=t.argumentCallback?t.argumentCallback(e):e;return i[o]}}const Z7e={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},X7e={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Q7e={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"]},J7e={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"]},eHe={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"}},tHe={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"}},rHe=(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"},nHe={ordinalNumber:rHe,era:$2({values:Z7e,defaultWidth:"wide"}),quarter:$2({values:X7e,defaultWidth:"wide",argumentCallback:t=>t-1}),month:$2({values:Q7e,defaultWidth:"wide"}),day:$2({values:J7e,defaultWidth:"wide"}),dayPeriod:$2({values:eHe,defaultWidth:"wide",formattingValues:tHe,defaultFormattingWidth:"wide"})};function U2(t){return(e,r={})=>{const n=r.width,i=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],o=e.match(i);if(!o)return null;const c=o[0],s=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],f=Array.isArray(s)?sHe(s,_=>_.test(c)):iHe(s,_=>_.test(c));let p;p=t.valueCallback?t.valueCallback(f):f,p=r.valueCallback?r.valueCallback(p):p;const y=e.slice(c.length);return{value:p,rest:y}}}function iHe(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function sHe(t,e){for(let r=0;r{const n=e.match(t.matchPattern);if(!n)return null;const i=n[0],o=e.match(t.parsePattern);if(!o)return null;let c=t.valueCallback?t.valueCallback(o[0]):o[0];c=r.valueCallback?r.valueCallback(c):c;const s=e.slice(i.length);return{value:c,rest:s}}}const oHe=/^(\d+)(th|st|nd|rd)?/i,lHe=/\d+/i,cHe={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},uHe={any:[/^b/i,/^(a|c)/i]},dHe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},hHe={any:[/1/i,/2/i,/3/i,/4/i]},fHe={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},mHe={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]},pHe={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},gHe={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]},yHe={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},xHe={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}},_He={ordinalNumber:aHe({matchPattern:oHe,parsePattern:lHe,valueCallback:t=>parseInt(t,10)}),era:U2({matchPatterns:cHe,defaultMatchWidth:"wide",parsePatterns:uHe,defaultParseWidth:"any"}),quarter:U2({matchPatterns:dHe,defaultMatchWidth:"wide",parsePatterns:hHe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:U2({matchPatterns:fHe,defaultMatchWidth:"wide",parsePatterns:mHe,defaultParseWidth:"any"}),day:U2({matchPatterns:pHe,defaultMatchWidth:"wide",parsePatterns:gHe,defaultParseWidth:"any"}),dayPeriod:U2({matchPatterns:yHe,defaultMatchWidth:"any",parsePatterns:xHe,defaultParseWidth:"any"})},T3={code:"en-US",formatDistance:V7e,formatLong:W7e,formatRelative:Y7e,localize:nHe,match:_He,options:{weekStartsOn:0,firstWeekContainsDate:1}};function vHe(t){const e=On(t);return Jh(e,B0e(e))+1}function N7(t){const e=On(t),r=+Vp(e)-+C7e(e);return Math.round(r/A7)+1}function P7(t,e){var y,_,T,E;const r=On(t),n=r.getFullYear(),i=wx(),o=(e==null?void 0:e.firstWeekContainsDate)??((_=(y=e==null?void 0:e.locale)==null?void 0:y.options)==null?void 0:_.firstWeekContainsDate)??i.firstWeekContainsDate??((E=(T=i.locale)==null?void 0:T.options)==null?void 0:E.firstWeekContainsDate)??1,c=Ys(t,0);c.setFullYear(n+1,0,o),c.setHours(0,0,0,0);const s=Sc(c,e),f=Ys(t,0);f.setFullYear(n,0,o),f.setHours(0,0,0,0);const p=Sc(f,e);return r.getTime()>=s.getTime()?n+1:r.getTime()>=p.getTime()?n:n-1}function bHe(t,e){var s,f,p,y;const r=wx(),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??((y=(p=r.locale)==null?void 0:p.options)==null?void 0:y.firstWeekContainsDate)??1,i=P7(t,e),o=Ys(t,0);return o.setFullYear(i,0,n),o.setHours(0,0,0,0),Sc(o,e)}function R7(t,e){const r=On(t),n=+Sc(r,e)-+bHe(r,e);return Math.round(n/A7)+1}function Bs(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const Gg={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return Bs(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):Bs(r+1,2)},d(t,e){return Bs(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 Bs(t.getHours()%12||12,e.length)},H(t,e){return Bs(t.getHours(),e.length)},m(t,e){return Bs(t.getMinutes(),e.length)},s(t,e){return Bs(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return Bs(i,e.length)}},ew={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},pre={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 Gg.y(t,e)},Y:function(t,e,r,n){const i=P7(t,n),o=i>0?i:1-i;if(e==="YY"){const c=o%100;return Bs(c,2)}return e==="Yo"?r.ordinalNumber(o,{unit:"year"}):Bs(o,e.length)},R:function(t,e){const r=F0e(t);return Bs(r,e.length)},u:function(t,e){const r=t.getFullYear();return Bs(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 Bs(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 Bs(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 Gg.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 Bs(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=R7(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):Bs(i,e.length)},I:function(t,e,r){const n=N7(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):Bs(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Gg.d(t,e)},D:function(t,e,r){const n=vHe(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Bs(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(),o=(i-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return Bs(o,2);case"eo":return r.ordinalNumber(o,{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(),o=(i-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return Bs(o,e.length);case"co":return r.ordinalNumber(o,{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 Bs(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=ew.noon:n===0?i=ew.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=ew.evening:n>=12?i=ew.afternoon:n>=4?i=ew.morning:i=ew.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 Gg.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Gg.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Bs(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):Bs(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Gg.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Gg.s(t,e)},S:function(t,e){return Gg.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return yre(n);case"XXXX":case"XX":return X0(n);case"XXXXX":case"XXX":default:return X0(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return yre(n);case"xxxx":case"xx":return X0(n);case"xxxxx":case"xxx":default:return X0(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+gre(n,":");case"OOOO":default:return"GMT"+X0(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+gre(n,":");case"zzzz":default:return"GMT"+X0(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return Bs(n,e.length)},T:function(t,e,r){const n=t.getTime();return Bs(n,e.length)}};function gre(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Math.trunc(n/60),o=n%60;return o===0?r+String(i):r+String(i)+e+Bs(o,2)}function yre(t,e){return t%60===0?(t>0?"-":"+")+Bs(Math.abs(t)/60,2):X0(t,e)}function X0(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Bs(Math.trunc(n/60),2),o=Bs(n%60,2);return r+i+e+o}const xre=(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"})}},$0e=(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"})}},wHe=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return xre(t,e);let o;switch(n){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",xre(n,e)).replace("{{time}}",$0e(i,e))},vV={p:$0e,P:wHe},SHe=/^D+$/,THe=/^Y+$/,EHe=["D","DD","YY","YYYY"];function U0e(t){return SHe.test(t)}function V0e(t){return THe.test(t)}function bV(t,e,r){const n=AHe(t,e,r);if(console.warn(n),EHe.includes(t))throw new RangeError(n)}function AHe(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 jHe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,kHe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,CHe=/^'([^]*?)'?$/,IHe=/''/g,NHe=/[a-zA-Z]/;function Ni(t,e,r){var y,_,T,E,k,P,R,D;const n=wx(),i=(r==null?void 0:r.locale)??n.locale??T3,o=(r==null?void 0:r.firstWeekContainsDate)??((_=(y=r==null?void 0:r.locale)==null?void 0:y.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)??((P=(k=r==null?void 0:r.locale)==null?void 0:k.options)==null?void 0:P.weekStartsOn)??n.weekStartsOn??((D=(R=n.locale)==null?void 0:R.options)==null?void 0:D.weekStartsOn)??0,s=On(t);if(!_V(s))throw new RangeError("Invalid time value");let f=e.match(kHe).map(M=>{const B=M[0];if(B==="p"||B==="P"){const V=vV[B];return V(M,i.formatLong)}return M}).join("").match(jHe).map(M=>{if(M==="''")return{isToken:!1,value:"'"};const B=M[0];if(B==="'")return{isToken:!1,value:PHe(M)};if(pre[B])return{isToken:!0,value:M};if(B.match(NHe))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 p={firstWeekContainsDate:o,weekStartsOn:c,locale:i};return f.map(M=>{if(!M.isToken)return M.value;const B=M.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&V0e(B)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&U0e(B))&&bV(B,e,String(t));const V=pre[B[0]];return V(s,B,i.localize,p)}).join("")}function PHe(t){const e=t.match(CHe);return e?e[1].replace(IHe,"'"):t}function RHe(t,e,r){const n=wx(),i=(r==null?void 0:r.locale)??n.locale??T3,o=2520,c=uL(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,p;c>0?(f=On(e),p=On(t)):(f=On(t),p=On(e));const y=z7e(p,f),_=(rx(p)-rx(f))/1e3,T=Math.round((y-_)/60);let E;if(T<2)return r!=null&&r.includeSeconds?y<5?i.formatDistance("lessThanXSeconds",5,s):y<10?i.formatDistance("lessThanXSeconds",10,s):y<20?i.formatDistance("lessThanXSeconds",20,s):y<40?i.formatDistance("halfAMinute",0,s):y<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 L7(t,e){const r=On(t),n=On(e);return+r<+n}function zHe(t,e){const r=e instanceof Date?Ys(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 $He=10;class G0e{constructor(){un(this,"subPriority",0)}validate(e,r){return!0}}class UHe extends G0e{constructor(e,r,n,i,o){super(),this.value=e,this.validateValue=r,this.setValue=n,this.priority=i,o&&(this.subPriority=o)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,n){return this.setValue(e,r,this.value,n)}}class VHe extends G0e{constructor(){super(...arguments);un(this,"priority",$He);un(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:Ys(r,zHe(r,Date))}}class Es{run(e,r,n,i){const o=this.parse(e,r,n,i);return o?{setter:new UHe(o.value,this.validate,this.set,this.priority,this.subPriority),rest:o.rest}:null}validate(e,r,n){return!0}}class qHe 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 Co={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}/},Yf={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 Io(t,e){return t&&{value:e(t.value),rest:t.rest}}function eo(t,e){const r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function Zf(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,o=r[3]?parseInt(r[3],10):0,c=r[5]?parseInt(r[5],10):0;return{value:n*(i*k7+o*j7+c*j7e),rest:e.slice(r[0].length)}}function H0e(t){return eo(Co.anyDigitsSigned,t)}function xo(t,e){switch(t){case 1:return eo(Co.singleDigit,e);case 2:return eo(Co.twoDigits,e);case 3:return eo(Co.threeDigits,e);case 4:return eo(Co.fourDigits,e);default:return eo(new RegExp("^\\d{1,"+t+"}"),e)}}function BD(t,e){switch(t){case 1:return eo(Co.singleDigitSigned,e);case 2:return eo(Co.twoDigitsSigned,e);case 3:return eo(Co.threeDigitsSigned,e);case 4:return eo(Co.fourDigitsSigned,e);default:return eo(new RegExp("^-?\\d{1,"+t+"}"),e)}}function D7(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 W0e(t,e){const r=e>0,n=r?e:1-e;let i;if(n<=50)i=t||100;else{const o=n+50,c=Math.trunc(o/100)*100,s=t>=o%100;i=t+c-(s?100:0)}return r?i:1-i}function K0e(t){return t%400===0||t%4===0&&t%100!==0}class GHe 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 o=c=>({year:c,isTwoDigitYear:n==="yy"});switch(n){case"y":return Io(xo(4,r),o);case"yo":return Io(i.ordinalNumber(r,{unit:"year"}),o);default:return Io(xo(n.length,r),o)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i){const o=r.getFullYear();if(i.isTwoDigitYear){const s=W0e(i.year,o);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 HHe 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 o=c=>({year:c,isTwoDigitYear:n==="YY"});switch(n){case"Y":return Io(xo(4,r),o);case"Yo":return Io(i.ordinalNumber(r,{unit:"year"}),o);default:return Io(xo(n.length,r),o)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i,o){const c=P7(r,o);if(i.isTwoDigitYear){const f=W0e(i.year,c);return r.setFullYear(f,0,o.firstWeekContainsDate),r.setHours(0,0,0,0),Sc(r,o)}const s=!("era"in n)||n.era===1?i.year:1-i.year;return r.setFullYear(s,0,o.firstWeekContainsDate),r.setHours(0,0,0,0),Sc(r,o)}}class WHe 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 BD(n==="R"?4:n.length,r)}set(r,n,i){const o=Ys(r,0);return o.setFullYear(i,0,4),o.setHours(0,0,0,0),Vp(o)}}class KHe 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 BD(n==="u"?4:n.length,r)}set(r,n,i){return r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}class YHe 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 xo(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 ZHe 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 xo(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 XHe 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 o=c=>c-1;switch(n){case"M":return Io(eo(Co.month,r),o);case"MM":return Io(xo(2,r),o);case"Mo":return Io(i.ordinalNumber(r,{unit:"month"}),o);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 QHe 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 o=c=>c-1;switch(n){case"L":return Io(eo(Co.month,r),o);case"LL":return Io(xo(2,r),o);case"Lo":return Io(i.ordinalNumber(r,{unit:"month"}),o);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 JHe(t,e,r){const n=On(t),i=R7(n,r)-e;return n.setDate(n.getDate()-i*7),n}class eWe 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 eo(Co.week,r);case"wo":return i.ordinalNumber(r,{unit:"week"});default:return xo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i,o){return Sc(JHe(r,i,o),o)}}function tWe(t,e){const r=On(t),n=N7(r)-e;return r.setDate(r.getDate()-n*7),r}class rWe 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 eo(Co.week,r);case"Io":return i.ordinalNumber(r,{unit:"week"});default:return xo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i){return Vp(tWe(r,i))}}const nWe=[31,28,31,30,31,30,31,31,30,31,30,31],iWe=[31,29,31,30,31,30,31,31,30,31,30,31];class sWe 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 eo(Co.date,r);case"do":return i.ordinalNumber(r,{unit:"date"});default:return xo(n.length,r)}}validate(r,n){const i=r.getFullYear(),o=K0e(i),c=r.getMonth();return o?n>=1&&n<=iWe[c]:n>=1&&n<=nWe[c]}set(r,n,i){return r.setDate(i),r.setHours(0,0,0,0),r}}class aWe 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 eo(Co.dayOfYear,r);case"Do":return i.ordinalNumber(r,{unit:"date"});default:return xo(n.length,r)}}validate(r,n){const i=r.getFullYear();return K0e(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 M7(t,e,r){var _,T,E,k;const n=wx(),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??((k=(E=n.locale)==null?void 0:E.options)==null?void 0:k.weekStartsOn)??0,o=On(t),c=o.getDay(),f=(e%7+7)%7,p=7-i,y=e<0||e>6?e-(c+p)%7:(f+p)%7-(c+p)%7;return Cl(o,y)}class oWe 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,o){return r=M7(r,i,o),r.setHours(0,0,0,0),r}}class lWe 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,o){const c=s=>{const f=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+f};switch(n){case"e":case"ee":return Io(xo(n.length,r),c);case"eo":return Io(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,o){return r=M7(r,i,o),r.setHours(0,0,0,0),r}}class cWe 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,o){const c=s=>{const f=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+f};switch(n){case"c":case"cc":return Io(xo(n.length,r),c);case"co":return Io(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,o){return r=M7(r,i,o),r.setHours(0,0,0,0),r}}function uWe(t,e){const r=On(t),n=MHe(r),i=e-n;return Cl(r,i)}class dWe 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 o=c=>c===0?7:c;switch(n){case"i":case"ii":return xo(n.length,r);case"io":return i.ordinalNumber(r,{unit:"day"});case"iii":return Io(i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),o);case"iiiii":return Io(i.day(r,{width:"narrow",context:"formatting"}),o);case"iiiiii":return Io(i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),o);case"iiii":default:return Io(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"}),o)}}validate(r,n){return n>=1&&n<=7}set(r,n,i){return r=uWe(r,i),r.setHours(0,0,0,0),r}}class hWe 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(D7(i),0,0,0),r}}class fWe 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(D7(i),0,0,0),r}}class mWe 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(D7(i),0,0,0),r}}class pWe 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 eo(Co.hour12h,r);case"ho":return i.ordinalNumber(r,{unit:"hour"});default:return xo(n.length,r)}}validate(r,n){return n>=1&&n<=12}set(r,n,i){const o=r.getHours()>=12;return o&&i<12?r.setHours(i+12,0,0,0):!o&&i===12?r.setHours(0,0,0,0):r.setHours(i,0,0,0),r}}class gWe 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 eo(Co.hour23h,r);case"Ho":return i.ordinalNumber(r,{unit:"hour"});default:return xo(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,i){return r.setHours(i,0,0,0),r}}class yWe 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 eo(Co.hour11h,r);case"Ko":return i.ordinalNumber(r,{unit:"hour"});default:return xo(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 xWe 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 eo(Co.hour24h,r);case"ko":return i.ordinalNumber(r,{unit:"hour"});default:return xo(n.length,r)}}validate(r,n){return n>=1&&n<=24}set(r,n,i){const o=i<=24?i%24:i;return r.setHours(o,0,0,0),r}}class _We extends Es{constructor(){super(...arguments);un(this,"priority",60);un(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"m":return eo(Co.minute,r);case"mo":return i.ordinalNumber(r,{unit:"minute"});default:return xo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setMinutes(i,0,0),r}}class vWe extends Es{constructor(){super(...arguments);un(this,"priority",50);un(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"s":return eo(Co.second,r);case"so":return i.ordinalNumber(r,{unit:"second"});default:return xo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setSeconds(i,0),r}}class bWe extends Es{constructor(){super(...arguments);un(this,"priority",30);un(this,"incompatibleTokens",["t","T"])}parse(r,n){const i=o=>Math.trunc(o*Math.pow(10,-n.length+3));return Io(xo(n.length,r),i)}set(r,n,i){return r.setMilliseconds(i),r}}class wWe extends Es{constructor(){super(...arguments);un(this,"priority",10);un(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Zf(Yf.basicOptionalMinutes,r);case"XX":return Zf(Yf.basic,r);case"XXXX":return Zf(Yf.basicOptionalSeconds,r);case"XXXXX":return Zf(Yf.extendedOptionalSeconds,r);case"XXX":default:return Zf(Yf.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Ys(r,r.getTime()-rx(r)-i)}}class SWe extends Es{constructor(){super(...arguments);un(this,"priority",10);un(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Zf(Yf.basicOptionalMinutes,r);case"xx":return Zf(Yf.basic,r);case"xxxx":return Zf(Yf.basicOptionalSeconds,r);case"xxxxx":return Zf(Yf.extendedOptionalSeconds,r);case"xxx":default:return Zf(Yf.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Ys(r,r.getTime()-rx(r)-i)}}class TWe extends Es{constructor(){super(...arguments);un(this,"priority",40);un(this,"incompatibleTokens","*")}parse(r){return H0e(r)}set(r,n,i){return[Ys(r,i*1e3),{timestampIsSet:!0}]}}class EWe extends Es{constructor(){super(...arguments);un(this,"priority",20);un(this,"incompatibleTokens","*")}parse(r){return H0e(r)}set(r,n,i){return[Ys(r,i),{timestampIsSet:!0}]}}const AWe={G:new qHe,y:new GHe,Y:new HHe,R:new WHe,u:new KHe,Q:new YHe,q:new ZHe,M:new XHe,L:new QHe,w:new eWe,I:new rWe,d:new sWe,D:new aWe,E:new oWe,e:new lWe,c:new cWe,i:new dWe,a:new hWe,b:new fWe,B:new mWe,h:new pWe,H:new gWe,K:new yWe,k:new xWe,m:new _We,s:new vWe,S:new bWe,X:new wWe,x:new SWe,t:new TWe,T:new EWe},jWe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,kWe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,CWe=/^'([^]*?)'?$/,IWe=/''/g,NWe=/\S/,PWe=/[a-zA-Z]/;function RWe(t,e,r,n){var P,R,D,M;const i=DHe(),o=i.locale??T3,c=i.firstWeekContainsDate??((R=(P=i.locale)==null?void 0:P.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):Ys(r,NaN);const f={firstWeekContainsDate:c,weekStartsOn:s,locale:o},p=[new VHe],y=e.match(kWe).map(B=>{const V=B[0];if(V in vV){const G=vV[V];return G(B,o.formatLong)}return B}).join("").match(jWe),_=[];for(let B of y){V0e(B)&&bV(B,e,t),U0e(B)&&bV(B,e,t);const V=B[0],G=AWe[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 Z=G.run(t,B,o.match,f);if(!Z)return Ys(r,NaN);p.push(Z.setter),t=Z.rest}else{if(V.match(PWe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+V+"`");if(B==="''"?B="'":V==="'"&&(B=LWe(B)),t.indexOf(B)===0)t=t.slice(B.length);else return Ys(r,NaN)}}if(t.length>0&&NWe.test(t))return Ys(r,NaN);const T=p.map(B=>B.priority).sort((B,V)=>V-B).filter((B,V,G)=>G.indexOf(B)===V).map(B=>p.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 Ys(r,NaN);const k={};for(const B of T){if(!B.validate(E,f))return Ys(r,NaN);const V=B.set(E,k,f);Array.isArray(V)?(E=V[0],Object.assign(k,V[1])):E=V}return Ys(r,E)}function LWe(t){return t.match(CWe)[1].replace(IWe,"'")}function V1(t){return+On(t)2)return e;if(/:/.test(r[0])?n=r[0]:(e.date=r[0],n=r[1],HP.timeZoneDelimiter.test(e.date)&&(e.date=t.split(HP.timeZoneDelimiter)[0],n=t.substr(e.date.length,t.length))),n){const i=HP.timezone.exec(n);i?(e.time=n.replace(i[1],""),e.timezone=i[1]):e.time=n}return e}function UWe(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,o=n[2]?parseInt(n[2]):null;return{year:o===null?i:o*100,restDateString:t.slice((n[1]||n[2]).length)}}function VWe(t,e){if(e===null)return new Date(NaN);const r=t.match(FWe);if(!r)return new Date(NaN);const n=!!r[4],i=V2(r[1]),o=V2(r[2])-1,c=V2(r[3]),s=V2(r[4]),f=V2(r[5])-1;if(n)return ZWe(e,s,f)?HWe(e,s,f):new Date(NaN);{const p=new Date(0);return!KWe(e,o,c)||!YWe(e,i)?new Date(NaN):(p.setUTCFullYear(e,o,Math.max(i,c)),p)}}function V2(t){return t?parseInt(t):1}function qWe(t){const e=t.match(BWe);if(!e)return NaN;const r=_z(e[1]),n=_z(e[2]),i=_z(e[3]);return XWe(r,n,i)?r*k7+n*j7+i*1e3:NaN}function _z(t){return t&&parseFloat(t.replace(",","."))||0}function GWe(t){if(t==="Z")return 0;const e=t.match(zWe);if(!e)return 0;const r=e[1]==="+"?-1:1,n=parseInt(e[2]),i=e[3]&&parseInt(e[3])||0;return QWe(n,i)?r*(n*k7+i*j7):NaN}function HWe(t,e,r){const n=new Date(0);n.setUTCFullYear(t,0,4);const i=n.getUTCDay()||7,o=(e-1)*7+r+1-i;return n.setUTCDate(n.getUTCDate()+o),n}const WWe=[31,null,31,30,31,30,31,31,30,31,30,31];function Y0e(t){return t%400===0||t%4===0&&t%100!==0}function KWe(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(WWe[e]||(Y0e(t)?29:28))}function YWe(t,e){return e>=1&&e<=(Y0e(t)?366:365)}function ZWe(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}function XWe(t,e,r){return t===24?e===0&&r===0:r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}function QWe(t,e){return e>=0&&e<=59}function vz(t,e){const r=On(t),n=r.getFullYear(),i=r.getDate(),o=Ys(t,0);o.setFullYear(n,e,15),o.setHours(0,0,0,0);const c=LHe(o);return r.setMonth(e,Math.min(i,c)),r}function _re(t,e){const r=On(t);return isNaN(+r)?Ys(t,NaN):(r.setFullYear(e),r)}function JWe(t,e){return yd(t,-e)}const eKe=()=>{const{user:t}=Gn(),e=Gs(),[r,n]=I.useState([]),[i,o]=I.useState(0),[c,s]=I.useState(!1),[f,p]=I.useState(null),y=I.useRef(null);I.useEffect(()=>{y.current=f},[f]),I.useEffect(()=>{if(!t)return;const P=`notification_last_read_${t.id}`,R=localStorage.getItem(P);R&&!y.current&&(y.current=R,p(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 Z=y.current?new Date(y.current):null,Q=W.filter(re=>Z?new Date(re.created_at)>Z:!0);o(Q.length)};B();const G=Re.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},W=>{const Z=W.new;n(re=>{const se=[Z,...re].slice(0,20);try{sessionStorage.setItem(D,JSON.stringify({ts:Date.now(),data:se}))}catch{}return se});const Q=y.current?new Date(y.current):null;(!Q||new Date(Z.created_at)>Q)&&o(re=>re+1),Notification.permission==="granted"&&new Notification(Z.title,{body:Z.body,icon:"/favicon.ico"})}).subscribe();return()=>{Re.removeChannel(G)}},[t]);const _=P=>{const R=P.toLowerCase();return R.includes("community")||R.includes("post")?of:R.includes("academy")||R.includes("video")?DA:R.includes("template")?PO:R.includes("event")?yo:R.includes("newsletter")?Bfe:R.includes("brokerage")?Cfe:R.includes("swag")||R.includes("social")?rf:R.includes("toolbox")||R.includes("tool")?u9:R.includes("brief")?xs:of},T=P=>{s(!1),P.url&&P.url!=="/"&&e(P.url)},E=()=>{if(!t)return;const P=new Date().toISOString(),R=`notification_last_read_${t.id}`;localStorage.setItem(R,P),p(P),o(0)},k=P=>{s(P),P&&i>0&&E()};return a.jsxs(mC,{open:c,onOpenChange:k,children:[a.jsx(pC,{asChild:!0,children:a.jsxs(zt,{variant:"ghost",size:"icon",className:"relative",children:[a.jsx(Qk,{className:"h-5 w-5"}),i>0&&a.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})]})}),a.jsxs(qS,{align:"end",className:"w-80",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[a.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&a.jsx(zt,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:E,children:"Mark all read"})]}),a.jsx(Sm,{className:"h-[300px]",children:r.length===0?a.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(P=>{const R=_(P.title);return a.jsxs(Eu,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>T(P),children:[a.jsx("div",{className:"flex-shrink-0 mt-0.5",children:a.jsx(R,{className:"h-4 w-4 text-primary"})}),a.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[a.jsx("span",{className:"font-medium text-sm",children:P.title}),a.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:P.body}),a.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:q0e(new Date(P.created_at),{addSuffix:!0})})]})]},P.id)})})]})]})};function tKe(t){return t!=null&&t.length?t.find(e=>e.is_active&&e.mls_provider_id&&!e.no_mls_mode)||t[0]:null}function Z0e(){const{user:t}=Gn(),{data:e,isLoading:r}=gr({queryKey:["agent-lead-site",t==null?void 0:t.id],queryFn:async()=>{const{data:n,error:i}=await Re.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 tKe(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 X0e(t=!0){const{user:e}=Gn(),{data:r,isLoading:n}=gr({queryKey:["free-lead-site-offer",e==null?void 0:e.id],enabled:!!e&&t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i}=await Re.from("profiles").select("brokerage_id").eq("id",e.id).maybeSingle();if(!(i!=null&&i.brokerage_id))return null;const{data:o}=await Re.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",i.brokerage_id).eq("enabled",!0).maybeSingle();return o??null}});return{offer:r??null,hasOffer:!!r,isLoading:n}}const rKe="coaching_access";function nKe(){const{user:t,loading:e,isAdmin:r,isCoach:n}=Gn(),{data:i,isLoading:o}=gr({queryKey:["coaching-access",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const[c,s]=await Promise.all([Re.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1),Re.from("feature_entitlements").select("enabled, expires_at").eq("user_id",t.id).eq("feature_key",rKe).maybeSingle()]),f=(c.data||[]).length>0,p=s.data,y=!!(p!=null&&p.enabled)&&(!p.expires_at||new Date(p.expires_at).getTime()>Date.now());return{hasAssignment:f,entitled:y}}});return{hasAccess:!!(r||n||i!=null&&i.hasAssignment||i!=null&&i.entitled),hasAssignment:!!(i!=null&&i.hasAssignment),isLoading:e||o}}const Wi=Re,KVt=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function YVt(t){return t.total_items===0?"not_started":t.rejected_items>0?"changes_requested":t.approved_items>=t.total_items?"compliant":"in_review"}const ZVt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function iKe(){return gr({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:t}=await Re.auth.getUser();if(!t.user)return[];const{data:e,error:r}=await Wi.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",t.user.id);if(r)throw r;return e||[]}})}function XVt(t){return gr({queryKey:["transaction-admins",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.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 Wi.from("profiles").select("id, name, email").in("id",n.map(c=>c.user_id)),o=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=o.get(c.user_id))==null?void 0:s.name)??null,email:((f=o.get(c.user_id))==null?void 0:f.email)??null}})}})}function QVt(){const t=Nr();return kr({mutationFn:async({brokerageId:e,userId:r})=>{const{error:n}=await Wi.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 JVt(){const t=Nr();return kr({mutationFn:async({id:e})=>{const{error:r}=await Wi.from("brokerage_transaction_admins").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function e8t(t){return gr({queryKey:["compliance-settings",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("brokerage_compliance_settings").select("*").eq("brokerage_id",t).maybeSingle();if(r)throw r;return e}})}function t8t(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Wi.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 r8t(t){return gr({queryKey:["compliance-templates",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("brokerage_checklist_templates").select("*").eq("brokerage_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]}})}function n8t(t){return gr({queryKey:["compliance-template-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("brokerage_checklist_template_items").select("*").eq("template_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function i8t(){const t=Nr();return kr({mutationFn:async e=>{if(e.id){const{error:i}=await Wi.from("brokerage_checklist_templates").update(e).eq("id",e.id);if(i)throw i;return e.id}const{data:r,error:n}=await Wi.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 s8t(){const t=Nr();return kr({mutationFn:async({id:e})=>{const{error:r}=await Wi.from("brokerage_checklist_templates").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerageId]})})}function a8t(){const t=Nr();return kr({mutationFn:async e=>{if(e.id){const{error:n}=await Wi.from("brokerage_checklist_template_items").update(e).eq("id",e.id);if(n)throw n;return}const{error:r}=await Wi.from("brokerage_checklist_template_items").insert(e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.template_id]})})}function o8t(){const t=Nr();return kr({mutationFn:async({id:e})=>{const{error:r}=await Wi.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 l8t(t){return gr({queryKey:["compliance-deals",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.rpc("get_brokerage_compliance_deals",{_brokerage_id:t});if(r)throw r;return e||[]}})}function c8t(t){return gr({queryKey:["deal-compliance-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("deal_compliance_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function u8t(t){return gr({queryKey:["deal-compliance-events",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("deal_compliance_events").select("*").eq("deal_id",t).order("created_at",{ascending:!1}).limit(200);if(r)throw r;return e||[]}})}async function vC(t){var r;const{data:e}=await Re.auth.getUser();await Wi.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 d8t(){const t=Nr();return kr({mutationFn:async({item:e,status:r,note:n})=>{var c;const{data:i}=await Re.auth.getUser(),{error:o}=await Wi.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(o)throw o;await vC({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 h8t(){const t=Nr();return kr({mutationFn:async({dealId:e,brokerageId:r,templateId:n,deal:i})=>{const{data:o,error:c}=await Wi.from("brokerage_checklist_template_items").select("*").eq("template_id",n).order("sort_order",{ascending:!0});if(c)throw c;const s=(y,_)=>{if(!y)return null;const[T,E,k]=y.split(/[-/T]/).map(Number);return new Date(Date.UTC(T,E-1,k+(_||0))).toISOString().slice(0,10)},f=(o||[]).map(y=>({deal_id:e,brokerage_id:r,template_item_id:y.id,title:y.title,description:y.description,phase:y.phase,requires_document:y.requires_document,required_for_closing:y.required_for_closing,due_date:y.due_anchor==="contract_date"?s(i==null?void 0:i.contract_date,y.due_offset_days):y.due_anchor==="target_close_date"?s(i==null?void 0:i.target_close_date,y.due_offset_days):null,sort_order:y.sort_order}));if(f.length===0)return;const{error:p}=await Wi.from("deal_compliance_items").insert(f);if(p)throw p;await vC({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 f8t(t){return gr({queryKey:["deal-compliance-files",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.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 m8t(){const t=Nr();return kr({mutationFn:async({item:e,file:r})=>{var _,T;const{data:n}=await Re.auth.getUser(),i=(_=n.user)==null?void 0:_.id;if(!i)throw new Error("Not signed in");const{data:o}=await Wi.from("deal_files").select("id, version_no").eq("compliance_item_id",e.id).order("version_no",{ascending:!1}).limit(1),c=(((T=o==null?void 0:o[0])==null?void 0:T.version_no)||0)+1,s=r.name.split(".").pop(),f=`${i}/${e.deal_id}/${crypto.randomUUID()}.${s}`,{error:p}=await Re.storage.from("deal-files").upload(f,r);if(p)throw p;o!=null&&o.length&&await Wi.from("deal_files").update({is_current:!1}).eq("compliance_item_id",e.id);const{error:y}=await Wi.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(y)throw y;await Wi.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",e.id),await vC({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 p8t(t){const{data:e,error:r}=await Re.storage.from("deal-files").createSignedUrl(t,3600);if(r)throw r;window.open(e.signedUrl,"_blank","noopener,noreferrer")}function g8t(t){return gr({queryKey:["deal-compliance-messages",t],enabled:!!t,refetchInterval:3e4,queryFn:async()=>{const{data:e,error:r}=await Wi.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:o}=await Wi.from("profiles").select("id, name").in("id",i),c=new Map((o||[]).map(s=>[s.id,s.name??null]));return n.map(s=>({...s,sender_name:c.get(s.sender_user_id)??null}))}})}function y8t(){const t=Nr();return kr({mutationFn:async({dealId:e,brokerageId:r,body:n,senderRole:i,itemId:o})=>{var y;const{data:c}=await Re.auth.getUser(),s=(y=c.user)==null?void 0:y.id;if(!s)throw new Error("Not signed in");const{data:f,error:p}=await Wi.from("deal_compliance_messages").insert({deal_id:e,brokerage_id:r,sender_user_id:s,sender_role:i,item_id:o??null,body:n.trim()}).select("id").single();if(p)throw p;try{await Re.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 x8t(){const t=Nr();return kr({mutationFn:async({dealId:e,senderRole:r})=>{const{error:n}=await Wi.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 _8t(t){return gr({queryKey:["brokerage-agent-roster",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",t).order("name",{ascending:!0});if(r)throw r;return e||[]}})}function v8t(t){return gr({queryKey:["agent-pipeline-stages",t],enabled:!!t,queryFn:async()=>{const e=async()=>{const{data:n,error:i}=await Wi.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 Wi.rpc("initialize_deal_pipeline_stages",{p_user_id:t});n||(r=await e())}return r}})}function b8t(){const t=Nr();return kr({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 Wi.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 o=n.id;try{await Wi.rpc("ensure_deal_compliance",{_deal_id:o})}catch(c){console.error("ensure_deal_compliance failed",c)}return await vC({dealId:o,brokerageId:e.brokerageId,eventType:"deal_added_by_staff",detail:"Deal added by brokerage staff for the agent's pipeline"}),o},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["compliance-deals",r.brokerageId]}),t.invalidateQueries({queryKey:["deal-pipeline"]})}})}function w8t(t){return gr({queryKey:["staff-deal-detail",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Wi.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 S8t(){const t=Nr();return kr({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{error:n}=await Wi.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 vC({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 A3=[{id:"home",label:"Home",icon:Ofe,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:um,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:i9,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:go,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:Jk,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:P1,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:Sj,description:"Training, programs and coaching",accent:"nav-academy"},{id:"mainstage",label:"Main Stage",icon:zfe,route:"/main-stage",accent:"nav-mainstage"},{id:"events",label:"Events",icon:Vfe,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:JLe,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:ul,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:IO,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager||t.isOnTeam)},{id:"more",label:"More",icon:YLe,description:"Community, marketplace and help",accent:"nav-more"}],Tl=t=>e=>e.hasPermission(t),sKe=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:qLe,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Tl("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:xs,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:ul,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Tl("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"contact-map",label:"Contact Map",route:"/mission-control/sphere-map",icon:qs,iconTone:"red",description:"See your sphere on a map — boundaries, farms and prospects",primaryCategory:"crm",section:"Contacts",visible:Tl("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:hee,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Tl("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:bDe,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Tl("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:lD,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Tl("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:yee,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Tl("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:go,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:im,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Tl("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:dD,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:Ti,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:_De,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:rf,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Tl("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:i9,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Tl("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"lending-partners",label:"Lending Partners",route:"/mission-control/lenders",icon:IO,description:"Loan officers, loan milestones and lead exchange",primaryCategory:"deals",section:"Pipeline",visible:Tl("pipeline"),searchKeywords:["lender","loan officer","mortgage","pre-approval","referral"],displayOrder:135},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:hU,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Tl("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:ZLe,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:Tl("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:EDe,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Tl("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:wj,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Tl("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:im,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:im,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:go,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Tl("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:yDe,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:Lfe,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:La,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:Ife,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:hU,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:gee,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:PO,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:TDe,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:ru,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:gee,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:UB,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:UB,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:pee,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:Bfe,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:Ti,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:lD,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:rf,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:Tl("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:Tl("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:pee,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:_ee,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:mU,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:yee,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:nDe,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:P1,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:P1,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:CO,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:fDe,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:go,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:ul,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:La,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:wj,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:hee,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:UB,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:xs,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:Sj,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:N1,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:u9,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:Vfe,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:_ee,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:Sj,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:um,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:of,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:sDe,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:iv,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:Ufe,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:uD,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:rf,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:iDe,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:xs,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:oD,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:oD,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:xs,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:dD,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:go,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:eDe,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:N1,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:ul,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:ul,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:s9,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:ul,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:Jk,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:$B,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:Ofe,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:mDe,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:$B,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:mU,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:cm,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:Cfe,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:xs,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:$B,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 Q0e(t,e){return typeof t.route=="function"?t.route(e):t.route}function J0e(){const{user:t,isAdmin:e,isBrokerageManager:r,isCoach:n,brokerageId:i}=Gn(),{hasPermission:o}=a3(),{isInnerCircleEnabled:c,isMarketplaceEnabled:s,isFeatureEnabled:f}=u3(),{hasAccess:p}=t7(),{data:y,teams:_}=GS(),{leadSite:T,hasLeadSite:E,siteUrl:k}=Z0e(),{hasOffer:P}=X0e(!E),R=Fye(),{hasAccess:D}=nKe(),{data:M}=iKe(),B=Nr(),{data:V}=gr({queryKey:["my-coach-nav",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:be}=await Re.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1);return(be||[]).length>0}}),{data:G}=gr({queryKey:["user-tool-favorites",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:60*1e3,queryFn:async()=>{const{data:be}=await Re.from("user_tool_favorites").select("tool_id").eq("user_id",t.id);return(be||[]).map(me=>me.tool_id)}}),W=I.useMemo(()=>new Set(G||[]),[G]),Z=kr({mutationFn:async be=>{t!=null&&t.id&&(W.has(be)?await Re.from("user_tool_favorites").delete().eq("user_id",t.id).eq("tool_id",be):await Re.from("user_tool_favorites").insert({user_id:t.id,tool_id:be}))},onSuccess:()=>{B.invalidateQueries({queryKey:["user-tool-favorites"]}),B.invalidateQueries({queryKey:["app-catalog"]})}}),Q=I.useMemo(()=>{var be,me;return{isAdmin:!!e,isBrokerageManager:!!r,isTransactionAdmin:((M==null?void 0:M.length)||0)>0,isCoach:!!n,isOnTeam:!!y,isTeamLeader:(_||[]).some(Pe=>Pe.role==="team_leader"),hasCoach:!!V,brokerageId:i??null,hasPermission:o,isInnerCircleEnabled:!!c,stagingStudioEnabled:f("staging_studio_enabled"),isMarketplaceEnabled:!!s,hasWeeklyReels:!!p,hasLeadSite:!!E,hasLeadSiteMLS:!!(T!=null&&T.mls_provider_id),hasFreeSiteOffer:!!P,leadSiteId:(T==null?void 0:T.id)??null,siteUrl:k??null,email:(t==null?void 0:t.email)??null,isPartnershipMember:R.isMember,hasCoachingOnboarding:R.isMember&&!!((be=R.pkg)!=null&&be.includes_coaching),hasCoachingAccess:!!D||R.isMember&&!!((me=R.pkg)!=null&&me.includes_coaching)}},[e,r,M,n,y,_,V,i,o,c,s,f,p,E,T,P,k,t==null?void 0:t.email,R.isMember,R.pkg,D]),re=I.useMemo(()=>sKe.filter(be=>be.visible?be.visible(Q):!0).map(be=>{if(!R.isRestricted)return be;const me=sUe(be);return!me||R.hasFeature(me)?be:{...be,locked:!0,route:`/upgrade/${me}`}}).sort((be,me)=>be.displayOrder-me.displayOrder),[Q,R.isRestricted,R.features]),se=I.useMemo(()=>A3.filter(be=>be.visible?be.visible(Q):!0),[Q]),ue=I.useMemo(()=>se.filter(be=>!be.route).map(be=>{const me=re.filter(Se=>Se.primaryCategory===be.id),Pe=[],Ie=new Map;for(const Se of me)Ie.has(Se.section)||(Ie.set(Se.section,[]),Pe.push(Se.section)),Ie.get(Se.section).push(Se);return{id:be.id,label:be.label,sections:Pe.map(Se=>({title:Se,items:Ie.get(Se)}))}}),[re,se]),_e=I.useMemo(()=>new Map(ue.map(be=>[be.id,be])),[ue]),we=be=>be.toolId||`nav:${be.id}`,Ce=be=>W.has(we(be));return{ctx:Q,categories:ue,railCategories:se,categoryMap:_e,destinations:re,favorites:W,isFavorite:Ce,favoritesFor:be=>re.filter(me=>me.primaryCategory===be&&Ce(me)),favoriteKey:we,toggleFavorite:be=>Z.mutate(be),searchDestinations:be=>{const me=be.trim().toLowerCase();return me?re.map(Ie=>{const Se=Ie.label.toLowerCase(),ve=(Ie.description||"").toLowerCase(),We=(Ie.searchKeywords||[]).join(" ").toLowerCase();let rt=0;return Se===me?rt=100:Se.startsWith(me)?rt=80:Se.includes(me)?rt=60:We.includes(me)?rt=40:ve.includes(me)?rt=20:Ie.section.toLowerCase().includes(me)&&(rt=10),rt&&Ce(Ie)&&(rt+=5),{d:Ie,score:rt}}).filter(Ie=>Ie.score>0).sort((Ie,Se)=>Se.score-Ie.score).map(Ie=>Ie.d):[]},routeFor:be=>Q0e(be,Q)}}var vre=1,aKe=.9,oKe=.8,lKe=.17,bz=.1,wz=.999,cKe=.9999,uKe=.99,dKe=/[\\\/_+.#"@\[\(\{&]/,hKe=/[\\\/_+.#"@\[\(\{&]/g,fKe=/[\s-]/,e_e=/[\s-]/g;function wV(t,e,r,n,i,o,c){if(o===e.length)return i===t.length?vre:uKe;var s=`${i},${o}`;if(c[s]!==void 0)return c[s];for(var f=n.charAt(o),p=r.indexOf(f,i),y=0,_,T,E,k;p>=0;)_=wV(t,e,r,n,p+1,o+1,c),_>y&&(p===i?_*=vre:dKe.test(t.charAt(p-1))?(_*=oKe,E=t.slice(i,p-1).match(hKe),E&&i>0&&(_*=Math.pow(wz,E.length))):fKe.test(t.charAt(p-1))?(_*=aKe,k=t.slice(i,p-1).match(e_e),k&&i>0&&(_*=Math.pow(wz,k.length))):(_*=lKe,i>0&&(_*=Math.pow(wz,p-i))),t.charAt(p)!==e.charAt(o)&&(_*=cKe)),(__&&(_=T*bz)),_>y&&(y=_),p=r.indexOf(f,p+1);return c[s]=y,y}function bre(t){return t.toLowerCase().replace(e_e," ")}function mKe(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,wV(t,e,bre(t),bre(e),0,0,{})}var q2='[cmdk-group=""]',Sz='[cmdk-group-items=""]',pKe='[cmdk-group-heading=""]',t_e='[cmdk-item=""]',wre=`${t_e}:not([aria-disabled="true"])`,SV="cmdk-item-select",mw="data-value",gKe=(t,e,r)=>mKe(t,e,r),r_e=I.createContext(void 0),bC=()=>I.useContext(r_e),n_e=I.createContext(void 0),O7=()=>I.useContext(n_e),i_e=I.createContext(void 0),s_e=I.forwardRef((t,e)=>{let r=pw(()=>{var ve,We;return{search:"",value:(We=(ve=t.value)!=null?ve:t.defaultValue)!=null?We:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=pw(()=>new Set),i=pw(()=>new Map),o=pw(()=>new Map),c=pw(()=>new Set),s=a_e(t),{label:f,children:p,value:y,onValueChange:_,filter:T,shouldFilter:E,loop:k,disablePointerSelection:P=!1,vimBindings:R=!0,...D}=t,M=Dl(),B=Dl(),V=Dl(),G=I.useRef(null),W=jKe();G_(()=>{if(y!==void 0){let ve=y.trim();r.current.value=ve,Z.emit()}},[y]),G_(()=>{W(6,we)},[]);let Z=I.useMemo(()=>({subscribe:ve=>(c.current.add(ve),()=>c.current.delete(ve)),snapshot:()=>r.current,setState:(ve,We,rt)=>{var at,Et,_t,Vt;if(!Object.is(r.current[ve],We)){if(r.current[ve]=We,ve==="search")_e(),se(),W(1,ue);else if(ve==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let pt=document.getElementById(V);pt?pt.focus():(at=document.getElementById(M))==null||at.focus()}if(W(7,()=>{var pt;r.current.selectedItemId=(pt=Ce())==null?void 0:pt.id,Z.emit()}),rt||W(5,we),((Et=s.current)==null?void 0:Et.value)!==void 0){let pt=We??"";(Vt=(_t=s.current).onValueChange)==null||Vt.call(_t,pt);return}}Z.emit()}},emit:()=>{c.current.forEach(ve=>ve())}}),[]),Q=I.useMemo(()=>({value:(ve,We,rt)=>{var at;We!==((at=o.current.get(ve))==null?void 0:at.value)&&(o.current.set(ve,{value:We,keywords:rt}),r.current.filtered.items.set(ve,re(We,rt)),W(2,()=>{se(),Z.emit()}))},item:(ve,We)=>(n.current.add(ve),We&&(i.current.has(We)?i.current.get(We).add(ve):i.current.set(We,new Set([ve]))),W(3,()=>{_e(),se(),r.current.value||ue(),Z.emit()}),()=>{o.current.delete(ve),n.current.delete(ve),r.current.filtered.items.delete(ve);let rt=Ce();W(4,()=>{_e(),(rt==null?void 0:rt.getAttribute("id"))===ve&&ue(),Z.emit()})}),group:ve=>(i.current.has(ve)||i.current.set(ve,new Set),()=>{o.current.delete(ve),i.current.delete(ve)}),filter:()=>s.current.shouldFilter,label:f||t["aria-label"],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:M,inputId:V,labelId:B,listInnerRef:G}),[]);function re(ve,We){var rt,at;let Et=(at=(rt=s.current)==null?void 0:rt.filter)!=null?at:gKe;return ve?Et(ve,r.current.search,We):0}function se(){if(!r.current.search||s.current.shouldFilter===!1)return;let ve=r.current.filtered.items,We=[];r.current.filtered.groups.forEach(at=>{let Et=i.current.get(at),_t=0;Et.forEach(Vt=>{let pt=ve.get(Vt);_t=Math.max(pt,_t)}),We.push([at,_t])});let rt=G.current;Me().sort((at,Et)=>{var _t,Vt;let pt=at.getAttribute("id"),Nt=Et.getAttribute("id");return((_t=ve.get(Nt))!=null?_t:0)-((Vt=ve.get(pt))!=null?Vt:0)}).forEach(at=>{let Et=at.closest(Sz);Et?Et.appendChild(at.parentElement===Et?at:at.closest(`${Sz} > *`)):rt.appendChild(at.parentElement===rt?at:at.closest(`${Sz} > *`))}),We.sort((at,Et)=>Et[1]-at[1]).forEach(at=>{var Et;let _t=(Et=G.current)==null?void 0:Et.querySelector(`${q2}[${mw}="${encodeURIComponent(at[0])}"]`);_t==null||_t.parentElement.appendChild(_t)})}function ue(){let ve=Me().find(rt=>rt.getAttribute("aria-disabled")!=="true"),We=ve==null?void 0:ve.getAttribute(mw);Z.setState("value",We||void 0)}function _e(){var ve,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=(ve=o.current.get(_t))==null?void 0:ve.value)!=null?We:"",pt=(at=(rt=o.current.get(_t))==null?void 0:rt.keywords)!=null?at:[],Nt=re(Vt,pt);r.current.filtered.items.set(_t,Nt),Nt>0&&Et++}for(let[_t,Vt]of i.current)for(let pt of Vt)if(r.current.filtered.items.get(pt)>0){r.current.filtered.groups.add(_t);break}r.current.filtered.count=Et}function we(){var ve,We,rt;let at=Ce();at&&(((ve=at.parentElement)==null?void 0:ve.firstChild)===at&&((rt=(We=at.closest(q2))==null?void 0:We.querySelector(pKe))==null||rt.scrollIntoView({block:"nearest"})),at.scrollIntoView({block:"nearest"}))}function Ce(){var ve;return(ve=G.current)==null?void 0:ve.querySelector(`${t_e}[aria-selected="true"]`)}function Me(){var ve;return Array.from(((ve=G.current)==null?void 0:ve.querySelectorAll(wre))||[])}function Ae(ve){let We=Me()[ve];We&&Z.setState("value",We.getAttribute(mw))}function be(ve){var We;let rt=Ce(),at=Me(),Et=at.findIndex(Vt=>Vt===rt),_t=at[Et+ve];(We=s.current)!=null&&We.loop&&(_t=Et+ve<0?at[at.length-1]:Et+ve===at.length?at[0]:at[Et+ve]),_t&&Z.setState("value",_t.getAttribute(mw))}function me(ve){let We=Ce(),rt=We==null?void 0:We.closest(q2),at;for(;rt&&!at;)rt=ve>0?EKe(rt,q2):AKe(rt,q2),at=rt==null?void 0:rt.querySelector(wre);at?Z.setState("value",at.getAttribute(mw)):be(ve)}let Pe=()=>Ae(Me().length-1),Ie=ve=>{ve.preventDefault(),ve.metaKey?Pe():ve.altKey?me(1):be(1)},Se=ve=>{ve.preventDefault(),ve.metaKey?Ae(0):ve.altKey?me(-1):be(-1)};return I.createElement(rn.div,{ref:e,tabIndex:-1,...D,"cmdk-root":"",onKeyDown:ve=>{var We;(We=D.onKeyDown)==null||We.call(D,ve);let rt=ve.nativeEvent.isComposing||ve.keyCode===229;if(!(ve.defaultPrevented||rt))switch(ve.key){case"n":case"j":{R&&ve.ctrlKey&&Ie(ve);break}case"ArrowDown":{Ie(ve);break}case"p":case"k":{R&&ve.ctrlKey&&Se(ve);break}case"ArrowUp":{Se(ve);break}case"Home":{ve.preventDefault(),Ae(0);break}case"End":{ve.preventDefault(),Pe();break}case"Enter":{ve.preventDefault();let at=Ce();if(at){let Et=new Event(SV);at.dispatchEvent(Et)}}}}},I.createElement("label",{"cmdk-label":"",htmlFor:Q.inputId,id:Q.labelId,style:CKe},f),j3(t,ve=>I.createElement(n_e.Provider,{value:Z},I.createElement(r_e.Provider,{value:Q},ve))))}),yKe=I.forwardRef((t,e)=>{var r,n;let i=Dl(),o=I.useRef(null),c=I.useContext(i_e),s=bC(),f=a_e(t),p=(n=(r=f.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;G_(()=>{if(!p)return s.item(i,c==null?void 0:c.id)},[p]);let y=o_e(i,o,[t.value,t.children,o],t.keywords),_=O7(),T=nx(W=>W.value&&W.value===y.current),E=nx(W=>p||s.filter()===!1?!0:W.search?W.filtered.items.get(i)>0:!0);I.useEffect(()=>{let W=o.current;if(!(!W||t.disabled))return W.addEventListener(SV,k),()=>W.removeEventListener(SV,k)},[E,t.onSelect,t.disabled]);function k(){var W,Z;P(),(Z=(W=f.current).onSelect)==null||Z.call(W,y.current)}function P(){_.setState("value",y.current,!0)}if(!E)return null;let{disabled:R,value:D,onSelect:M,forceMount:B,keywords:V,...G}=t;return I.createElement(rn.div,{ref:Fp(o,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:P,onClick:R?void 0:k},t.children)}),xKe=I.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...o}=t,c=Dl(),s=I.useRef(null),f=I.useRef(null),p=Dl(),y=bC(),_=nx(E=>i||y.filter()===!1?!0:E.search?E.filtered.groups.has(c):!0);G_(()=>y.group(c),[]),o_e(c,s,[t.value,t.heading,f]);let T=I.useMemo(()=>({id:c,forceMount:i}),[i]);return I.createElement(rn.div,{ref:Fp(s,e),...o,"cmdk-group":"",role:"presentation",hidden:_?void 0:!0},r&&I.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:p},r),j3(t,E=>I.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?p:void 0},I.createElement(i_e.Provider,{value:T},E))))}),_Ke=I.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=I.useRef(null),o=nx(c=>!c.search);return!r&&!o?null:I.createElement(rn.div,{ref:Fp(i,e),...n,"cmdk-separator":"",role:"separator"})}),vKe=I.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,o=O7(),c=nx(p=>p.search),s=nx(p=>p.selectedItemId),f=bC();return I.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),I.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:p=>{i||o.setState("search",p.target.value),r==null||r(p.target.value)}})}),bKe=I.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,o=I.useRef(null),c=I.useRef(null),s=nx(p=>p.selectedItemId),f=bC();return I.useEffect(()=>{if(c.current&&o.current){let p=c.current,y=o.current,_,T=new ResizeObserver(()=>{_=requestAnimationFrame(()=>{let E=p.offsetHeight;y.style.setProperty("--cmdk-list-height",E.toFixed(1)+"px")})});return T.observe(p),()=>{cancelAnimationFrame(_),T.unobserve(p)}}},[]),I.createElement(rn.div,{ref:Fp(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":s,"aria-label":n,id:f.listId},j3(t,p=>I.createElement("div",{ref:Fp(c,f.listInnerRef),"cmdk-list-sizer":""},p)))}),wKe=I.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:o,container:c,...s}=t;return I.createElement(BO,{open:r,onOpenChange:n},I.createElement(zO,{container:c},I.createElement(LS,{"cmdk-overlay":"",className:i}),I.createElement(DS,{"aria-label":t.label,"cmdk-dialog":"",className:o},I.createElement(s_e,{ref:e,...s}))))}),SKe=I.forwardRef((t,e)=>nx(r=>r.filtered.count===0)?I.createElement(rn.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),TKe=I.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...o}=t;return I.createElement(rn.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},j3(t,c=>I.createElement("div",{"aria-hidden":!0},c)))}),Du=Object.assign(s_e,{List:bKe,Item:yKe,Input:vKe,Group:xKe,Separator:_Ke,Dialog:wKe,Empty:SKe,Loading:TKe});function EKe(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function AKe(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function a_e(t){let e=I.useRef(t);return G_(()=>{e.current=t}),e}var G_=typeof window>"u"?I.useEffect:I.useLayoutEffect;function pw(t){let e=I.useRef();return e.current===void 0&&(e.current=t()),e}function nx(t){let e=O7(),r=()=>t(e.snapshot());return I.useSyncExternalStore(e.subscribe,r,r)}function o_e(t,e,r,n=[]){let i=I.useRef(),o=bC();return G_(()=>{var c;let s=(()=>{var p;for(let y of r){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(p=y.current.textContent)==null?void 0:p.trim():i.current}})(),f=n.map(p=>p.trim());o.value(t,s,f),(c=e.current)==null||c.setAttribute(mw,s),i.current=s}),i}var jKe=()=>{let[t,e]=I.useState(),r=pw(()=>new Map);return G_(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function kKe(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function j3({asChild:t,children:e},r){return t&&I.isValidElement(e)?I.cloneElement(kKe(e),{ref:e.ref},r(e.props.children)):r(e)}var CKe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const zj=I.forwardRef(({className:t,...e},r)=>a.jsx(Du,{ref:r,className:sr("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));zj.displayName=Du.displayName;const IKe=({children:t,...e})=>a.jsx(io,{...e,children:a.jsx(Ua,{className:"overflow-hidden p-0 shadow-lg",children:a.jsx(zj,{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})})}),$j=I.forwardRef(({className:t,...e},r)=>a.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[a.jsx(hd,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),a.jsx(Du.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})]}));$j.displayName=Du.Input.displayName;const Uj=I.forwardRef(({className:t,...e},r)=>a.jsx(Du.List,{ref:r,className:sr("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));Uj.displayName=Du.List.displayName;const Vj=I.forwardRef((t,e)=>a.jsx(Du.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));Vj.displayName=Du.Empty.displayName;const q1=I.forwardRef(({className:t,...e},r)=>a.jsx(Du.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}));q1.displayName=Du.Group.displayName;const NKe=I.forwardRef(({className:t,...e},r)=>a.jsx(Du.Separator,{ref:r,className:sr("-mx-1 h-px bg-border",t),...e}));NKe.displayName=Du.Separator.displayName;const ky=I.forwardRef(({className:t,...e},r)=>a.jsx(Du.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}));ky.displayName=Du.Item.displayName;const PKe={event:{label:"Events",icon:im,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:PO,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Sj,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:u9,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:xs,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Sre=()=>{const[t,e]=I.useState(!1),[r,n]=I.useState(""),[i,o]=I.useState([]),[c,s]=I.useState(!1),f=Gs(),{searchDestinations:p,isFavorite:y,routeFor:_}=J0e(),T=r.trim()?p(r).slice(0,6):[];I.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=I.useCallback(async R=>{if(!R.trim()){o([]);return}s(!0);const D=`%${R}%`;try{const[M,B,V,G,W]=await Promise.all([Re.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5),Re.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${D},description.ilike.${D}`).limit(5),Re.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5),Re.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${D},description.ilike.${D}`).limit(5),Re.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5)]),Z=[];M.data&&M.data.forEach(Q=>{Z.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=>{Z.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=>{Z.push({id:Q.id,title:Q.title,description:Q.description,type:"academy",date:Q.publish_date,path:`/academy/${Q.id}`})}),G.data&&G.data.forEach(Q=>{Z.push({id:Q.id,title:Q.name,description:Q.description,type:"toolbox",date:Q.publish_date,path:`/toolbox/${Q.id}`})}),W.data&&W.data.forEach(Q=>{Z.push({id:Q.id,title:Q.title,description:Q.description,type:"social-swag",date:Q.publish_date,path:`/social-swag/${Q.id}`})}),o(Z)}catch(M){console.error("Search error:",M)}finally{s(!1)}},[]);I.useEffect(()=>{const R=setTimeout(()=>{E(r)},300);return()=>clearTimeout(R)},[r,E]);const k=R=>{e(!1),n(""),f(R)},P=i.reduce((R,D)=>(R[D.type]||(R[D.type]=[]),R[D.type].push(D),R),{});return a.jsxs(a.Fragment,{children:[a.jsxs(zt,{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:[a.jsx(hd,{className:"h-4 w-4 xl:mr-2"}),a.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),a.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:[a.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),a.jsxs(IKe,{open:t,onOpenChange:e,children:[a.jsx($j,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),a.jsxs(Uj,{children:[T.length>0&&a.jsx(q1,{heading:"Go to",children:T.map(R=>{const D=R.icon;return a.jsxs(ky,{value:`nav-${R.id}-${R.label}`,onSelect:()=>{const M=_(R);R.external||R.openInNewTab?(e(!1),n(""),window.open(M,"_blank","noopener,noreferrer")):k(M)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[a.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:a.jsx(D,{className:"h-4 w-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[R.label,y(R)&&a.jsx(aD,{className:"h-3 w-3 fill-current text-primary"})]}),R.description&&a.jsx("div",{className:"text-sm text-muted-foreground truncate",children:R.description})]}),a.jsx(us,{variant:"secondary",className:"text-xs shrink-0",children:R.section})]},`nav-${R.id}`)})}),c&&a.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!c&&r&&i.length===0&&T.length===0&&a.jsxs(Vj,{children:['No results found for "',r,'"']}),!c&&!r&&a.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(P).map(([R,D])=>{const M=PKe[R],B=M.icon;return a.jsx(q1,{heading:M.label,children:D.map(V=>a.jsxs(ky,{value:`${V.type}-${V.id}-${V.title}`,onSelect:()=>k(V.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[a.jsx("div",{className:`p-2 rounded-md ${M.color}`,children:a.jsx(B,{className:"h-4 w-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-medium truncate",children:V.title}),V.description&&a.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:V.description})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[a.jsx(us,{variant:"secondary",className:"text-xs",children:M.label}),a.jsx("span",{className:"text-xs text-muted-foreground",children:q0e(new Date(V.date),{addSuffix:!0})})]})]},`${V.type}-${V.id}`))},R)})]})]})]})},RKe=({expiresAt:t,className:e,showUpgradeButton:r=!0})=>{const[n,i]=I.useState(null),o=Gs();if(I.useEffect(()=>{const p=()=>{const _=new Date().getTime(),E=new Date(t).getTime()-_;if(E<=0){i({days:0,hours:0,minutes:0});return}const k=Math.floor(E/(1e3*60*60*24)),P=Math.floor(E%(1e3*60*60*24)/(1e3*60*60)),R=Math.floor(E%(1e3*60*60)/(1e3*60));i({days:k,hours:P,minutes:R})};p();const y=setInterval(p,6e4);return()=>clearInterval(y)},[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?a.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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(PS,{className:"h-4 w-4 text-destructive"}),a.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&a.jsxs(zt,{size:"sm",onClick:()=>o("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[a.jsx(xs,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rl,{className:sr("h-4 w-4",s?"text-destructive":f?"text-amber-500":"text-primary")}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:sr("text-sm font-medium",s?"text-destructive":f?"text-amber-600":"text-primary"),children:"Free Trial:"}),a.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&a.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.days,"d"]}),a.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),a.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),a.jsx("span",{className:sr("text-xs",s?"text-destructive/70":f?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&a.jsxs(zt,{size:"sm",onClick:()=>o("/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:[a.jsx(xs,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},LKe=()=>{const t=Gs();return a.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:a.jsxs(Wn,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[a.jsxs(id,{className:"text-center pb-2",children:[a.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:a.jsx(PS,{className:"h-8 w-8 text-destructive"})}),a.jsx(sd,{className:"text-2xl",children:"Your Free Trial Has Ended"}),a.jsx(Mj,{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!"})]}),a.jsxs(si,{className:"space-y-6",children:[a.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[a.jsx(Wn,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:a.jsxs(si,{className:"p-5 text-center",children:[a.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:a.jsx(ul,{className:"h-6 w-6 text-primary"})}),a.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),a.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",a.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),a.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),a.jsxs(zt,{className:"w-full",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[a.jsx(xs,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),a.jsx(Wn,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:a.jsxs(si,{className:"p-5 text-center",children:[a.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:a.jsx(go,{className:"h-6 w-6 text-amber-600"})}),a.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),a.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",a.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),a.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),a.jsxs(zt,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[a.jsx(go,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),a.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),a.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[a.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[a.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[a.jsx(ai,{className:"h-4 w-4"}),a.jsx("span",{children:"1-866-527-8668"})]}),a.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[a.jsx(Ti,{className:"h-4 w-4"}),a.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},DKe=({hasUnseenBrief:t,onClick:e,className:r})=>a.jsxs(DFe,{children:[a.jsx(MFe,{asChild:!0,children:a.jsxs(zt,{variant:"ghost",size:"icon",onClick:e,className:sr("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[a.jsx(Jk,{className:"h-5 w-5"}),t&&a.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),a.jsx(bpe,{children:a.jsx("p",{children:"The LevelUp Brief"})})]});var k3="Checkbox",[MKe,T8t]=Yo(k3),[OKe,F7]=MKe(k3);function FKe(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:o,form:c,name:s,onCheckedChange:f,required:p,value:y="on",internal_do_not_use_render:_}=t,[T,E]=dd({prop:r,defaultProp:i??!1,onChange:f,caller:k3}),[k,P]=I.useState(null),[R,D]=I.useState(null),M=I.useRef(!1),B=k?!!c||!!k.closest("form"):!0,V={checked:T,disabled:o,setChecked:E,control:k,setControl:P,name:s,form:c,value:y,hasConsumerStoppedPropagationRef:M,required:p,defaultChecked:$y(i)?!1:i,isFormControl:B,bubbleInput:R,setBubbleInput:D};return a.jsx(OKe,{scope:e,...V,children:BKe(_)?_(V):n})}var l_e="CheckboxTrigger",c_e=I.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:r,...n},i)=>{const{control:o,value:c,disabled:s,checked:f,required:p,setControl:y,setChecked:_,hasConsumerStoppedPropagationRef:T,isFormControl:E,bubbleInput:k}=F7(l_e,t),P=Kn(i,y),R=I.useRef(f);return I.useEffect(()=>{const D=o==null?void 0:o.form;if(D){const M=()=>_(R.current);return D.addEventListener("reset",M),()=>D.removeEventListener("reset",M)}},[o,_]),a.jsx(rn.button,{type:"button",role:"checkbox","aria-checked":$y(f)?"mixed":f,"aria-required":p,"data-state":m_e(f),"data-disabled":s?"":void 0,disabled:s,value:c,...n,ref:P,onKeyDown:Or(e,D=>{D.key==="Enter"&&D.preventDefault()}),onClick:Or(r,D=>{_(M=>$y(M)?!0:!M),k&&E&&(T.current=D.isPropagationStopped(),T.current||D.stopPropagation())})})});c_e.displayName=l_e;var B7=I.forwardRef((t,e)=>{const{__scopeCheckbox:r,name:n,checked:i,defaultChecked:o,required:c,disabled:s,value:f,onCheckedChange:p,form:y,..._}=t;return a.jsx(FKe,{__scopeCheckbox:r,checked:i,defaultChecked:o,disabled:s,required:c,onCheckedChange:p,name:n,form:y,value:f,internal_do_not_use_render:({isFormControl:T})=>a.jsxs(a.Fragment,{children:[a.jsx(c_e,{..._,ref:e,__scopeCheckbox:r}),T&&a.jsx(f_e,{__scopeCheckbox:r})]})})});B7.displayName=k3;var u_e="CheckboxIndicator",d_e=I.forwardRef((t,e)=>{const{__scopeCheckbox:r,forceMount:n,...i}=t,o=F7(u_e,r);return a.jsx(pl,{present:n||$y(o.checked)||o.checked===!0,children:a.jsx(rn.span,{"data-state":m_e(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e,style:{pointerEvents:"none",...t.style}})})});d_e.displayName=u_e;var h_e="CheckboxBubbleInput",f_e=I.forwardRef(({__scopeCheckbox:t,...e},r)=>{const{control:n,hasConsumerStoppedPropagationRef:i,checked:o,defaultChecked:c,required:s,disabled:f,name:p,value:y,form:_,bubbleInput:T,setBubbleInput:E}=F7(h_e,t),k=Kn(r,E),P=xC(o),R=oC(n);I.useEffect(()=>{const M=T;if(!M)return;const B=window.HTMLInputElement.prototype,G=Object.getOwnPropertyDescriptor(B,"checked").set,W=!i.current;if(P!==o&&G){const Z=new Event("click",{bubbles:W});M.indeterminate=$y(o),G.call(M,$y(o)?!1:o),M.dispatchEvent(Z)}},[T,P,o,i]);const D=I.useRef($y(o)?!1:o);return a.jsx(rn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??D.current,required:s,disabled:f,name:p,value:y,form:_,...e,tabIndex:-1,ref:k,style:{...e.style,...R,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});f_e.displayName=h_e;function BKe(t){return typeof t=="function"}function $y(t){return t==="indeterminate"}function m_e(t){return $y(t)?"indeterminate":t?"checked":"unchecked"}const wC=I.forwardRef(({className:t,...e},r)=>a.jsx(B7,{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:a.jsx(d_e,{className:sr("flex items-center justify-center text-current"),children:a.jsx(ko,{className:"h-4 w-4"})})}));wC.displayName=B7.displayName;var z7="Radio",[zKe,p_e]=Yo(z7),[$Ke,UKe]=zKe(z7),g_e=I.forwardRef((t,e)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:o,disabled:c,value:s="on",onCheck:f,form:p,...y}=t,[_,T]=I.useState(null),E=Kn(e,R=>T(R)),k=I.useRef(!1),P=_?p||!!_.closest("form"):!0;return a.jsxs($Ke,{scope:r,checked:i,disabled:c,children:[a.jsx(rn.button,{type:"button",role:"radio","aria-checked":i,"data-state":v_e(i),"data-disabled":c?"":void 0,disabled:c,value:s,...y,ref:E,onClick:Or(t.onClick,R=>{i||f==null||f(),P&&(k.current=R.isPropagationStopped(),k.current||R.stopPropagation())})}),P&&a.jsx(__e,{control:_,bubbles:!k.current,name:n,value:s,checked:i,required:o,disabled:c,form:p,style:{transform:"translateX(-100%)"}})]})});g_e.displayName=z7;var y_e="RadioIndicator",x_e=I.forwardRef((t,e)=>{const{__scopeRadio:r,forceMount:n,...i}=t,o=UKe(y_e,r);return a.jsx(pl,{present:n||o.checked,children:a.jsx(rn.span,{"data-state":v_e(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e})})});x_e.displayName=y_e;var VKe="RadioBubbleInput",__e=I.forwardRef(({__scopeRadio:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=I.useRef(null),s=Kn(c,o),f=xC(r),p=oC(e);return I.useEffect(()=>{const y=c.current;if(!y)return;const _=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(_,"checked").set;if(f!==r&&E){const k=new Event("click",{bubbles:n});E.call(y,r),y.dispatchEvent(k)}},[f,r,n]),a.jsx(rn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:s,style:{...i.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});__e.displayName=VKe;function v_e(t){return t?"checked":"unchecked"}var qKe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],C3="RadioGroup",[GKe,E8t]=Yo(C3,[VS,p_e]),b_e=VS(),w_e=p_e(),[HKe,WKe]=GKe(C3),S_e=I.forwardRef((t,e)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:o,required:c=!1,disabled:s=!1,orientation:f,dir:p,loop:y=!0,onValueChange:_,...T}=t,E=b_e(r),k=av(p),[P,R]=dd({prop:o,defaultProp:i??null,onChange:_,caller:C3});return a.jsx(HKe,{scope:r,name:n,required:c,disabled:s,value:P,onValueChange:R,children:a.jsx(G9,{asChild:!0,...E,orientation:f,dir:k,loop:y,children:a.jsx(rn.div,{role:"radiogroup","aria-required":c,"aria-orientation":f,"data-disabled":s?"":void 0,dir:k,...T,ref:e})})})});S_e.displayName=C3;var T_e="RadioGroupItem",E_e=I.forwardRef((t,e)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,o=WKe(T_e,r),c=o.disabled||n,s=b_e(r),f=w_e(r),p=I.useRef(null),y=Kn(e,p),_=o.value===i.value,T=I.useRef(!1);return I.useEffect(()=>{const E=P=>{qKe.includes(P.key)&&(T.current=!0)},k=()=>T.current=!1;return document.addEventListener("keydown",E),document.addEventListener("keyup",k),()=>{document.removeEventListener("keydown",E),document.removeEventListener("keyup",k)}},[]),a.jsx(H9,{asChild:!0,...s,focusable:!c,active:_,children:a.jsx(g_e,{disabled:c,required:o.required,checked:_,...f,...i,name:o.name,ref:y,onCheck:()=>o.onValueChange(i.value),onKeyDown:Or(E=>{E.key==="Enter"&&E.preventDefault()}),onFocus:Or(i.onFocus,()=>{var E;T.current&&((E=p.current)==null||E.click())})})})});E_e.displayName=T_e;var KKe="RadioGroupIndicator",A_e=I.forwardRef((t,e)=>{const{__scopeRadioGroup:r,...n}=t,i=w_e(r);return a.jsx(x_e,{...i,...n,ref:e})});A_e.displayName=KKe;var j_e=S_e,k_e=E_e,YKe=A_e;const C_e=I.forwardRef(({className:t,...e},r)=>a.jsx(j_e,{className:sr("grid gap-2",t),...e,ref:r}));C_e.displayName=j_e.displayName;const I_e=I.forwardRef(({className:t,...e},r)=>a.jsx(k_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:a.jsx(YKe,{className:"flex items-center justify-center",children:a.jsx(F_,{className:"h-2.5 w-2.5 fill-current text-current"})})}));I_e.displayName=k_e.displayName;const ZKe=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=Gn(),[o,c]=I.useState({}),[s,f]=I.useState({}),[p,y]=I.useState([]);I.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 Re.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)}})},k=async R=>{if(!i)return;const D=o[R];if(!D||Array.isArray(D)&&D.length===0){Gt.error("Please select an option");return}y(M=>[...M,R]);try{await Re.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 Re.from("levelup_brief_poll_responses").insert(B);if(V)throw V;f(G=>({...G,[R]:M})),Gt.success("Response submitted!")}catch(M){console.error("Error submitting poll response:",M),Gt.error("Failed to submit response")}finally{y(M=>M.filter(B=>B!==R))}},P=R=>(R.includes("mediadelivery.net")||R.includes("bunny"),R);return a.jsx(io,{open:e,onOpenChange:R=>!R&&r(),children:a.jsxs(Ua,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[a.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[a.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:a.jsx(Ds,{className:"h-5 w-5 text-white"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:a.jsx(Jk,{className:"h-6 w-6"})}),a.jsxs("div",{children:[a.jsx(us,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),a.jsx(Ko,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})]}),a.jsx(Sm,{className:"max-h-[calc(90vh-240px)]",children:a.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&a.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.brief.description}}),t.brief.video_url&&a.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:a.jsx("iframe",{src:P(t.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),t.brief.graphic_url&&!t.brief.video_url&&a.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:t.brief.graphic_link_url?a.jsx("a",{href:t.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:a.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):a.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),t.links.length>0&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(R=>a.jsxs(zt,{variant:"outline",size:"sm",onClick:()=>window.open(R.url,"_blank"),className:"gap-2",children:[a.jsx(iv,{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=p.includes(R.id);return a.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"font-semibold text-foreground",children:R.question}),D&&a.jsxs(us,{variant:"secondary",className:"gap-1",children:[a.jsx(ic,{className:"h-3 w-3"}),"Responded"]})]}),R.poll_type==="single"?a.jsx(C_e,{value:o[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=>a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(I_e,{value:G.id,id:G.id}),a.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id))}):a.jsx("div",{className:"space-y-2",children:R.options.map(G=>{const Z=(o[R.id]||s[R.id]||[]).includes(G.id);return a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(wC,{id:G.id,checked:Z,onCheckedChange:Q=>E(R.id,G.id,Q)}),a.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id)})}),a.jsx(zt,{size:"sm",onClick:()=>k(R.id),disabled:M,children:M?"Submitting...":D?"Update Response":"Submit"})]},R.id)})]})}),a.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:[a.jsx(zt,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),a.jsx(zt,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},XKe=()=>{const{user:t}=Gn(),[e,r]=I.useState(null),[n,i]=I.useState(!1),[o,c]=I.useState(!0),[s,f]=I.useState(!1),p=I.useCallback(async()=>{if(!t){c(!1);return}try{const{data:k,error:P}=await Re.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(P||!k){c(!1);return}const{data:R}=await Re.from("levelup_brief_views").select("*").eq("brief_id",k.id).eq("user_id",t.id).maybeSingle(),[D,M]=await Promise.all([Re.from("levelup_brief_links").select("*").eq("brief_id",k.id).order("sort_order"),Re.from("levelup_brief_polls").select("*").eq("brief_id",k.id).order("sort_order")]),B=[];if(M.data)for(const Q of M.data){const{data:re}=await Re.from("levelup_brief_poll_options").select("*").eq("poll_id",Q.id).order("sort_order");B.push({...Q,options:re||[]})}const V={brief:k,links:D.data||[],polls:B};r(V);const G=!!R,W=(R==null?void 0:R.dismissed_at)!=null,Z=localStorage.getItem(`brief-dismissed-${k.id}`)==="true";if(W||Z)f(!1),i(!1);else if(!G)i(!0),f(!0);else if(k.show_frequency==="every_login")i(!0),f(!0);else if(k.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(k){console.error("Error fetching brief:",k)}finally{c(!1)}},[t]);I.useEffect(()=>{p()},[p]);const y=async()=>{if(!(!t||!e))try{const{data:k}=await Re.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();k?await Re.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",k.id):await Re.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(k){console.error("Error marking brief as viewed:",k)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:s,loading:o,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),y()},dismissBrief:async()=>{if(!(!t||!e)){i(!1),f(!1);try{const{data:k,error:P}=await Re.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();if(P&&console.error("Error checking existing brief view:",P),k){const{error:R}=await Re.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",k.id).eq("user_id",t.id);R&&console.error("Error updating brief dismiss:",R)}else{const{error:R}=await Re.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(k){console.error("Error dismissing brief:",k),e&&localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}}},refetch:p}};function QKe(){const[t,e]=I.useState(!1),[r,n]=I.useState(!1),[i,o]=I.useState(null);I.useEffect(()=>{const f=localStorage.getItem("install-banner-dismissed"),p=localStorage.getItem("install-banner-shown");if(f||p)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=k=>{k.preventDefault(),o(k)};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(),o(null)}};return t?a.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:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[a.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:a.jsx(rc,{className:"h-5 w-5"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?a.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",a.jsx(wDe,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):a.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&i&&a.jsx(zt,{size:"sm",variant:"secondary",onClick:s,className:"text-xs",children:"Install"}),a.jsx(zt,{size:"sm",variant:"secondary",onClick:c,className:"text-xs",children:"Got it"}),a.jsx("button",{onClick:c,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:a.jsx(Ds,{className:"h-4 w-4"})})]})]})}):null}const JKe=({children:t,onRefresh:e})=>{const[r,n]=I.useState(!1),[i,o]=I.useState(0),[c,s]=I.useState(!1),f=I.useRef(null),p=I.useRef(0),y=Nr(),_=80,T=120,E=I.useCallback(M=>{const B=f.current;B&&B.scrollTop<=0&&(p.current=M.touches[0].clientY,n(!0))},[]),k=I.useCallback(M=>{if(!r||c)return;const B=f.current;if(!B||B.scrollTop>0){n(!1),o(0);return}const G=M.touches[0].clientY-p.current;if(G>0){const Z=Math.min(G*.5,T);o(Z),Z>10&&M.preventDefault()}},[r,c]),P=I.useCallback(async()=>{if(r)if(n(!1),i>=_&&!c){s(!0),o(_);try{e?await e():await y.invalidateQueries()}catch(M){console.error("Refresh failed:",M)}finally{s(!1),o(0)}}else o(0)},[r,i,c,e,y]),R=Math.min(i/_,1),D=R*180;return a.jsxs("div",{ref:f,className:"h-full overflow-auto",onTouchStart:E,onTouchMove:k,onTouchEnd:P,children:[a.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:a.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:a.jsx(vDe,{className:"h-5 w-5 text-primary"})})}),a.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})]})},eYe=()=>{const{user:t}=Gn(),[e,r]=I.useState(!1),[n,i]=I.useState(!1),[o,c]=I.useState(0),[s,f]=I.useState(!0);I.useEffect(()=>{(async()=>{if(!t){f(!1);return}try{const{data:E}=await Re.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(E){i(!0),r(!1),f(!1);return}const{data:k}=await Re.from("profiles").select("login_count").eq("id",t.id).single(),P=(k==null?void 0:k.login_count)||0;c(P);const R=sessionStorage.getItem("review-prompt-dismissed");r(P>=4&&!R)}catch(E){console.error("Error checking review eligibility:",E)}finally{f(!1)}})()},[t]);const p=I.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),y=I.useCallback(async(T,E)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:k}=await Re.from("membership_reviews").insert({user_id:t.id,rating:T,review_text:E});if(k)throw k;return i(!0),r(!1),{success:!0,pointsAwarded:25}}catch(k){return console.error("Error submitting review:",k),{success:!1,error:k.message}}},[t]),_=I.useCallback(async()=>{if(t)try{await Re.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:o,isLoading:s,dismissPrompt:p,submitReview:y,markPostedToGoogle:_}},tYe="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",rYe=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=eYe(),[o,c]=I.useState(!1),[s,f]=I.useState("review"),[p,y]=I.useState(0),[_,T]=I.useState(0),[E,k]=I.useState(""),[P,R]=I.useState(!1),[D,M]=I.useState(!1);if(e||!t&&!D)return null;const B=async()=>{if(p===0){Ts({title:"Please select a rating",variant:"destructive"});return}R(!0);const W=await n(p,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||`${p} star rating for LevelUp!`),Ts({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(tYe,"_blank")),c(!1),r()},G=()=>{c(!1),r()};return a.jsxs(a.Fragment,{children:[a.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:[a.jsx(ru,{className:"h-3.5 w-3.5 fill-current"}),a.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),a.jsx(io,{open:o,onOpenChange:G,children:a.jsx(Ua,{className:"sm:max-w-md",children:s==="review"?a.jsxs(a.Fragment,{children:[a.jsxs(ml,{children:[a.jsx(Ko,{className:"text-center",children:"How are you enjoying LevelUp?"}),a.jsx(gd,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),a.jsxs("div",{className:"space-y-6 py-4",children:[a.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(W=>a.jsx("button",{type:"button",onClick:()=>y(W),onMouseEnter:()=>T(W),onMouseLeave:()=>T(0),className:"p-1 transition-transform hover:scale-110",children:a.jsx(ru,{className:sr("h-8 w-8 transition-colors",(_||p)>=W?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},W))}),a.jsx(bd,{placeholder:"Tell us about your experience (optional)",value:E,onChange:W=>k(W.target.value),rows:4,className:"resize-none"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(zt,{variant:"outline",onClick:G,className:"flex-1",children:"Maybe Later"}),a.jsx(zt,{onClick:B,disabled:P||p===0,className:"flex-1",children:P?"Submitting...":"Submit Review"})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs(ml,{children:[a.jsx(Ko,{className:"text-center",children:"🎉 Thank you!"}),a.jsx(gd,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),a.jsxs("div",{className:"space-y-4 py-4",children:[a.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(zt,{variant:"outline",onClick:()=>V(!1),className:"flex-1",children:"No Thanks"}),a.jsx(zt,{onClick:()=>V(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function nYe(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 o=0;o{if(!_){c(!1);return}(async()=>{try{const P="vapid_public_key";let R=localStorage.getItem(P);if(!R){const{data:B,error:V}=await Re.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(P,R)}y(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(P){console.error("Error initializing push notifications:",P)}finally{c(!1)}})()},[_]);const T=I.useCallback(async()=>{if(!_||!s||!t)return console.error("Push notifications not supported or user not logged in"),!1;if(!p)return Gt.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{c(!0);const k=await s.pushManager.getSubscription();if(k){try{await k.unsubscribe()}catch(V){console.warn("Failed to unsubscribe existing push subscription:",V)}const{error:B}=await Re.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"?Gt.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):Gt.error("Notification permission was dismissed. Please try again."),!1}const P=nYe(p);let R;try{R=await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:P})}catch(B){console.error("PushManager.subscribe() failed:",B);const V=(B==null?void 0:B.message)||String(B);return V.includes("permission")?Gt.error("Push permission denied. Check your browser notification settings."):V.includes("key")||V.includes("VAPID")?Gt.error("Push configuration error. Please contact support."):V.includes("AbortError")?Gt.error("Push subscription was cancelled. Please try again."):Gt.error(`Failed to subscribe: ${V}`),!1}const D=R.toJSON(),{error:M}=await Re.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),Gt.error("Failed to save notification preferences. Please try again."),M;return i(!0),Gt.success("Push notifications enabled!"),!0}catch(k){if(console.error("Error subscribing to push notifications:",k),!(k instanceof Error&&k.message.includes("toast"))){const P=k instanceof Error?k.message:"Unknown error";Gt.error("Failed to enable push notifications: "+P)}return!1}finally{c(!1)}},[_,s,t,p]),E=I.useCallback(async()=>{if(!s||!t)return!1;try{c(!0);const k=await s.pushManager.getSubscription();return k&&await k.unsubscribe(),await Re.from("push_subscriptions").delete().eq("user_id",t.id),i(!1),Gt.success("Push notifications disabled"),!0}catch(k){console.error("Error unsubscribing:",k);const P=k instanceof Error?k.message:"Unknown error";return Gt.error("Failed to disable push notifications: "+P),!1}finally{c(!1)}},[s,t]);return{isSupported:_,permission:e,isSubscribed:n,isLoading:o,vapidPublicKey:p,subscribe:T,unsubscribe:E}}const Tz="push_notification_prompt_dismissed",sYe=["/dashboard","/admin"],aYe=()=>{const{user:t}=Gn(),{isSupported:e,isSubscribed:r,isLoading:n,subscribe:i}=iYe(),o=Bi(),[c,s]=I.useState(!1),[f,p]=I.useState(!1),y=sYe.some(E=>o.pathname===E||o.pathname.startsWith(`${E}/`));I.useEffect(()=>{if(y){s(!1);return}if(!t||!e||r||n||localStorage.getItem(`${Tz}_${t.id}`))return;const k=setTimeout(()=>{s(!0)},2e3);return()=>clearTimeout(k)},[t,e,r,n,y]);const _=async()=>{p(!0);const E=await i();p(!1),E&&(t&&localStorage.setItem(`${Tz}_${t.id}`,"true"),s(!1))},T=()=>{t&&localStorage.setItem(`${Tz}_${t.id}`,"true"),s(!1)};return!e||r||y?null:a.jsx(io,{open:c,onOpenChange:E=>!E&&T(),children:a.jsxs(Ua,{className:"sm:max-w-md",children:[a.jsxs(ml,{children:[a.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:a.jsx(Qk,{className:"h-6 w-6 text-primary"})}),a.jsx(Ko,{className:"text-center",children:"Stay in the Loop!"}),a.jsx(gd,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),a.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(zt,{onClick:_,disabled:f,className:"w-full",children:f?"Enabling...":"Enable Notifications"}),a.jsx(zt,{variant:"ghost",onClick:T,className:"w-full",children:"Not Now"})]}),a.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},Tre=t=>{let e;const r=new Set,n=(p,y)=>{const _=typeof p=="function"?p(e):p;if(!Object.is(_,e)){const T=e;e=y??(typeof _!="object"||_===null)?_:Object.assign({},e,_),r.forEach(E=>E(e,T))}},i=()=>e,s={setState:n,getState:i,getInitialState:()=>f,subscribe:p=>(r.add(p),()=>r.delete(p))},f=e=t(n,i,s);return s},oYe=t=>t?Tre(t):Tre,lYe=t=>t;function cYe(t,e=lYe){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 Ere=t=>{const e=oYe(t),r=n=>cYe(e,n);return Object.assign(r,e),r},uYe=t=>t?Ere(t):Ere;function dYe(t,e){let r;try{r=t()}catch{return}return{getItem:i=>{var o;const c=f=>f===null?null:JSON.parse(f,void 0),s=(o=r.getItem(i))!=null?o:null;return s instanceof Promise?s.then(c):c(s)},setItem:(i,o)=>r.setItem(i,JSON.stringify(o,void 0)),removeItem:i=>r.removeItem(i)}}const TV=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return TV(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return TV(n)(r)}}}},hYe=(t,e)=>(r,n,i)=>{let o={storage:dYe(()=>window.localStorage),partialize:R=>R,version:0,merge:(R,D)=>({...D,...R}),...e},c=!1,s=0;const f=new Set,p=new Set;let y=o.storage;if(!y)return t((...R)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...R)},n,i);const _=()=>{const R=o.partialize({...n()});return y.setItem(o.name,{state:R,version:o.version})},T=i.setState;i.setState=(R,D)=>(T(R,D),_());const E=t((...R)=>(r(...R),_()),n,i);i.getInitialState=()=>E;let k;const P=()=>{var R,D;if(!y)return;const M=++s;c=!1,f.forEach(V=>{var G;return V((G=n())!=null?G:E)});const B=((D=o.onRehydrateStorage)==null?void 0:D.call(o,(R=n())!=null?R:E))||void 0;return TV(y.getItem.bind(y))(o.name).then(V=>{if(V)if(typeof V.version=="number"&&V.version!==o.version){if(o.migrate){const G=o.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,Z]=V;if(k=o.merge(Z,(G=n())!=null?G:E),r(k,!0),W)return _()}).then(()=>{M===s&&(B==null||B(n(),void 0),k=n(),c=!0,p.forEach(V=>V(k)))}).catch(V=>{M===s&&(B==null||B(void 0,V))})};return i.persist={setOptions:R=>{o={...o,...R},R.storage&&(y=R.storage)},clearStorage:()=>{y==null||y.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>P(),hasHydrated:()=>c,onHydrate:R=>(f.add(R),()=>{f.delete(R)}),onFinishHydration:R=>(p.add(R),()=>{p.delete(R)})},o.skipHydration||P(),k||E},fYe=hYe,N_e=uYe()(fYe((t,e)=>({cartItems:[],addToCart:(r,n,i=1,o)=>{t(c=>{const s=c.cartItems.findIndex(f=>{var p;return f.product.id===r.id&&((p=f.variant)==null?void 0:p.id)===(n==null?void 0:n.id)});if(s>=0){const f=[...c.cartItems];return f[s].quantity+=i,o&&(f[s].artworkUrl=o),{cartItems:f}}return{cartItems:[...c.cartItems,{product:r,variant:n,quantity:i,artworkUrl:o}]}})},removeFromCart:(r,n)=>{t(i=>({cartItems:i.cartItems.filter(o=>{var c;return!(o.product.id===r&&((c=o.variant)==null?void 0:c.id)===n)})}))},updateQuantity:(r,n,i)=>{t(o=>({cartItems:o.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(o=>({cartItems:o.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,o)=>i+n(o)*o.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})})),mYe="/admin/beta/boost",pYe=I.lazy(()=>Fe(()=>import("./BoostCompanion-BkvUCyD3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])));function gYe(){const{user:t,isAdmin:e}=Gn(),{isFeatureEnabled:r}=u3(),{pathname:n}=Bi(),i=n==="/main-stage"||n.startsWith("/main-stage/");return!(!!t&&(e||r("boost_mascot"))&&n!==mYe&&!i)||!t?null:a.jsx(I.Suspense,{fallback:null,children:a.jsx(pYe,{userId:t.id})})}async function yYe(t){const{data:e,error:r}=await Re.rpc("main_stage_list_events",t?{_event_id:t}:{});if(r)throw r;return(e||[]).map(n=>({...n,speakers:Array.isArray(n.speakers)?n.speakers:[],registered_count:Number(n.registered_count)}))}async function A8t(t){const{data:e,error:r}=await Re.functions.invoke("main-stage-events",{body:t});if(e!=null&&e.error)throw new Error(e.error);if(r)throw new Error(r.message);return e}const P_e="America/New_York",j8t=t=>new Intl.DateTimeFormat("en-US",{timeZone:P_e,weekday:"short",month:"short",day:"numeric"}).format(new Date(t)),k8t=t=>new Intl.DateTimeFormat("en-US",{timeZone:P_e,hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(new Date(t)),C8t=t=>t.trim().toUpperCase().replace(/\s+/g,"");function I8t(t,e="https://dashboard.relevelup.com"){const r=s=>s.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(t.starts_at),i=new Date(n.getTime()+t.duration_min*6e4),o=`${e}/main-stage?event=${t.id}`;return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:`The Main Stage: ${t.title}`,dates:`${r(n)}/${r(i)}`,details:`Join here: ${o}`,location:o})}`}function N8t(t,e="https://dashboard.relevelup.com"){const r=s=>s.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(t.starts_at),i=new Date(n.getTime()+t.duration_min*6e4),o=`${e}/main-stage?event=${t.id}`,c=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Main Stage//EN","BEGIN:VEVENT",`UID:main-stage-${t.id}@relevelup.com`,`DTSTAMP:${r(new Date)}`,`DTSTART:${r(n)}`,`DTEND:${r(i)}`,`SUMMARY:The Main Stage: ${t.title.replace(/[,;]/g," ")}`,`URL:${o}`,`LOCATION:${o}`,"END:VEVENT","END:VCALENDAR"].join(`\r `);return URL.createObjectURL(new Blob([c],{type:"text/calendar"}))}const P8t=t=>{const e=Math.floor(t/1e3);return{d:Math.floor(e/86400),h:Math.floor(e%86400/3600),m:Math.floor(e%3600/60),s:e%60}};function R_e(){const{data:t}=gr({queryKey:["main-stage-live-nav"],queryFn:async()=>(await yYe()).some(e=>e.status==="live"),refetchInterval:6e4,staleTime:3e4});return!!t}function xYe({activeCategory:t,currentCategory:e,onSelect:r,onHover:n,badgeCounts:i,categories:o=A3}){const c=R_e();return a.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:o.map(s=>{const f=s.icon,p=t===s.id,y=e===s.id,_=(i==null?void 0:i[s.id])??0,T=`hsl(var(--${s.accent}))`,E=p||y;return a.jsxs("button",{type:"button",onClick:()=>r(s.id),onMouseEnter:()=>n==null?void 0:n(s.id),"aria-expanded":s.route?void 0:p,"aria-controls":s.route?void 0:"primary-nav-flyout","aria-current":y?"page":void 0,style:{color:E?T:void 0,backgroundColor:E?`hsl(var(--${s.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:[y&&a.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:T}}),a.jsxs("span",{className:"relative",children:[a.jsx(f,{className:"h-5 w-5 transition-colors",style:{color:T}}),s.id==="mainstage"&&c&&a.jsxs("span",{className:"absolute -right-1 -top-1 flex h-3 w-3",children:[a.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-destructive opacity-75"}),a.jsx("span",{className:"relative inline-flex h-3 w-3 rounded-full bg-destructive"})]}),_>0&&a.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:T},children:_>9?"9+":_})]}),s.id==="mainstage"&&c?a.jsx("span",{className:"rounded bg-destructive px-1 text-[9px] font-bold uppercase tracking-wider leading-tight text-destructive-foreground",children:"Live"}):a.jsx("span",{className:"leading-tight",children:s.label})]},s.id)})})}function _Ye({category:t,top:e,left:r,onClose:n,onNavigate:i,isFavorite:o,favorites:c,onToggleFavorite:s,isCurrent:f,badgeCounts:p}){const y=I.useRef(null);I.useEffect(()=>{const T=k=>{k.key==="Escape"&&n()},E=k=>{var R;if(!y.current)return;const P=k.target;!y.current.contains(P)&&!((R=P==null?void 0:P.closest)!=null&&R.call(P,"[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,k=T.badgeKey?(p==null?void 0:p[T.badgeKey])??0:0;return a.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:[a.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:[a.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:a.jsx(E,{className:sr("h-4 w-4",T.iconTone==="red"&&"fill-destructive/20")})}),a.jsxs("span",{className:"min-w-0",children:[a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:T.label}),T.badge==="new"&&a.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"&&a.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&&a.jsx(Zy,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),k>0&&a.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:k>9?"9+":k})]}),T.description&&a.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:T.description})]})]}),a.jsx("button",{type:"button","aria-label":o(T)?`Remove ${T.label} from favorites`:`Add ${T.label} to favorites`,onClick:P=>{P.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",o(T)&&"opacity-100 text-primary",!o(T)&&"text-muted-foreground/60 hover:text-primary"),children:a.jsx(aD,{className:sr("h-4 w-4",o(T)&&"fill-current")})})]},T.id)};return a.jsxs("div",{id:"primary-nav-flyout",ref:y,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:[a.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:a.jsx("h2",{className:"text-sm font-semibold text-foreground",children:t.label})}),a.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[c.length>0&&a.jsxs("section",{className:"mb-4",children:[a.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[a.jsx(aD,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),a.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:c.map(_)})]}),t.sections.map(T=>a.jsxs("section",{className:"mb-4 last:mb-0",children:[a.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:T.title}),a.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:T.items.map(_)})]},T.title)),t.sections.length===0&&a.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function vYe({categories:t,railCategories:e=A3,currentCategory:r,onNavigate:n,onNavigateRoute:i,isCurrent:o,badgeCounts:c,isFavorite:s,onToggleFavorite:f}){const[p,y]=I.useState(r),_=R_e();return a.jsx("nav",{"aria-label":"Primary",className:"p-2",children:e.map(T=>{const E=T.icon;if(T.route)return a.jsxs("button",{type:"button",onClick:()=>i(T.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===T.id&&"bg-sidebar-accent"),children:[a.jsx(E,{className:"h-4 w-4",style:{color:`hsl(var(--${T.accent}))`}}),T.label,T.id==="mainstage"&&_&&a.jsxs("span",{className:"ml-auto flex items-center gap-1 rounded-full bg-destructive px-2 py-0.5 text-[10px] font-bold uppercase text-destructive-foreground",children:[a.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-destructive-foreground"}),"Live"]})]},T.id);const k=t.find(R=>R.id===T.id),P=p===T.id;return a.jsxs("div",{children:[a.jsxs("button",{type:"button","aria-expanded":P,onClick:()=>y(P?null:T.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===T.id&&"text-primary"),children:[a.jsx(E,{className:"h-4 w-4",style:{color:`hsl(var(--${T.accent}))`}}),T.label,a.jsx(wc,{className:sr("ml-auto h-4 w-4 transition-transform",P&&"rotate-180")})]}),P&&k&&a.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:k.sections.map(R=>a.jsxs("div",{children:[a.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:R.title}),R.items.map(D=>{const M=D.icon,B=D.badgeKey?(c==null?void 0:c[D.badgeKey])??0:0,V=(s==null?void 0:s(D))??!1;return a.jsxs("div",{className:sr("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",o(D)&&"bg-sidebar-accent"),children:[a.jsxs("button",{type:"button",onClick:()=>n(D),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[a.jsx(M,{className:sr("h-4 w-4 shrink-0",D.iconTone==="red"&&"text-destructive")}),a.jsx("span",{className:"truncate",children:D.label}),B>0&&a.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:B>9?"9+":B})]}),f&&a.jsx("button",{type:"button","aria-label":V?`Remove ${D.label} from favorites`:`Add ${D.label} to favorites`,onClick:()=>f(D),className:sr("rounded p-2",V?"text-primary":"text-muted-foreground/60"),children:a.jsx(aD,{className:sr("h-4 w-4",V&&"fill-current")})})]},D.id)})]},R.title))})]},T.id)})})}function L_e(){const t=Gs(),e=Bi(),r=J0e(),n=I.useCallback(s=>Q0e(s,r.ctx),[r.ctx]),i=I.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 p=n(f);p!=="/"&&e.pathname.startsWith(p)&&(!s||p.length>s.len)&&(s={id:f.primaryCategory,len:p.length})}return(s==null?void 0:s.id)??null},[e.pathname,r.destinations,n]),o=I.useCallback(s=>!s.external&&e.pathname===n(s),[e.pathname,n]),c=I.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:o,go:c}}function bYe({communityUnreadCount:t=0,wishlistOpenCount:e=0,flyoutTop:r=64,flyoutLeft:n=80}){const{nav:i,navigate:o,currentCategory:c,isCurrent:s,go:f}=L_e(),[p,y]=I.useState(null),_=I.useRef(null),T=P=>{const R=A3.find(D=>D.id===P);if(R!=null&&R.route){y(null),o(R.route);return}y(D=>D===P?null:P)},E=p?i.categoryMap.get(p):void 0,k={more:t+e};return a.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>y(null),250)},onMouseEnter:()=>{_.current&&window.clearTimeout(_.current)},children:[a.jsx(xYe,{activeCategory:p,currentCategory:c,onSelect:T,categories:i.railCategories,badgeCounts:k}),E&&a.jsx(_Ye,{category:E,top:r,left:n,onClose:()=>y(null),onNavigate:P=>{y(null),f(P)},isFavorite:i.isFavorite,favorites:i.favoritesFor(E.id),onToggleFavorite:P=>i.toggleFavorite(i.favoriteKey(P)),isCurrent:s,badgeCounts:{community:t,wishlist:e}})]})}function wYe({communityUnreadCount:t=0,wishlistOpenCount:e=0,onNavigated:r}){const{nav:n,navigate:i,currentCategory:o,isCurrent:c,go:s}=L_e();return a.jsx(vYe,{categories:n.categories,railCategories:n.railCategories,currentCategory:o,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 SYe=({bannerHeight:t,communityUnreadCount:e,wishlistOpenCount:r,isTrial:n,isExpired:i})=>{const o=Gs();return a.jsxs("div",{className:"flex h-full flex-col",children:[a.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:a.jsx("button",{type:"button",onClick:()=>o("/dashboard"),"aria-label":"LevelUp home",children:a.jsx("img",{src:LUe,alt:"LevelUp",className:"h-8 w-auto"})})}),a.jsxs(Sm,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[a.jsx(bYe,{communityUnreadCount:e,wishlistOpenCount:r,flyoutTop:t+64,flyoutLeft:80}),n&&!i&&a.jsx("div",{className:"p-2",children:a.jsxs("button",{type:"button",onClick:()=>o("/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:[a.jsx(xs,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},TYe=({isTrial:t,isExpired:e,expiresAt:r,communityUnreadCount:n,wishlistOpenCount:i,pathname:o,onSignOut:c,onNavigated:s})=>{const f=Gs();return a.jsxs("div",{className:"flex h-full flex-col",children:[a.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:a.jsx("img",{src:RUe,alt:"LevelUp",className:"h-8 w-auto"})}),a.jsxs(Sm,{className:"flex-1",children:[t&&!e&&a.jsx("div",{className:"p-2",children:a.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:a.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[a.jsx(xs,{className:"h-4 w-4 text-amber-500"}),a.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),r&&a.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"]})]})})}),a.jsx(wYe,{communityUnreadCount:n,wishlistOpenCount:i,onNavigated:s})]}),a.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[a.jsxs(zt,{variant:"ghost",size:"sm",className:sr("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",o==="/profile"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{f("/profile"),s==null||s()},children:[a.jsx(vc,{className:"h-4 w-4"}),"Profile"]}),a.jsxs(zt,{variant:"ghost",size:"sm",className:sr("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",o==="/credits"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{f("/credits"),s==null||s()},children:[a.jsx(c9,{className:"h-4 w-4"}),"Credits & Wallet"]}),a.jsxs(zt,{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:[a.jsx(NO,{className:"h-4 w-4"}),"Sign Out"]})]})]})},G1=({children:t,title:e})=>{var at;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:o,isCoach:c,brokerageId:s}=Gn(),{isAssistant:f,actingAsAgent:p,hasPermission:y}=a3();t7();const{isImpersonating:_}=Age(),E=(f&&!!p?40:0)+(_?40:0),{avatarUrl:k}=dUe(r==null?void 0:r.id),{isTrial:P,isExpired:R,expiresAt:D}=hUe(r==null?void 0:r.id),{isInnerCircleEnabled:M,isMarketplaceEnabled:B}=u3(),{currentBrief:V,shouldShowPopup:G,hasUnseenBrief:W,openBrief:Z,closeBrief:Q,dismissBrief:re}=XKe(),{unreadCount:se}=fUe(),{openCount:ue}=mUe();GS();const we=N_e(Et=>Et.cartItems).reduce((Et,_t)=>Et+_t.quantity,0),{leadSite:Ce,hasLeadSite:Me,siteUrl:Ae}=Z0e();X0e(!Me);const be=Gs(),me=Bi(),[Pe,Ie]=I.useState(null);I.useEffect(()=>{r!=null&&r.id&&Re.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 Se=Pe||((at=r==null?void 0:r.user_metadata)==null?void 0:at.name)||(r==null?void 0:r.email)||"User",[ve,We]=I.useState(!1),rt=Et=>Et.split(" ").map(_t=>_t[0]).join("").toUpperCase().slice(0,2);return a.jsx(vpe,{children:a.jsxs("div",{className:"min-h-screen bg-background flex",children:[P&&R&&me.pathname!=="/subscription"&&a.jsx(LKe,{}),typeof document<"u"&&Yp.createPortal(a.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:a.jsx(SYe,{bannerHeight:E,communityUnreadCount:se,wishlistOpenCount:ue,isTrial:P,isExpired:R})}),document.body),a.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${E}px)`,marginTop:`${E}px`},children:[a.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:a.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[a.jsxs(Uye,{open:ve,onOpenChange:We,children:[a.jsx(gUe,{asChild:!0,children:a.jsx(zt,{variant:"ghost",size:"icon",className:"md:hidden",children:a.jsx(IS,{className:"h-5 w-5"})})}),a.jsx(r7,{side:"left",className:"w-72 p-0 bg-card",children:a.jsx(TYe,{isTrial:P,isExpired:R,expiresAt:D,communityUnreadCount:se,wishlistOpenCount:ue,pathname:me.pathname,onSignOut:n,onNavigated:()=>We(!1)})})]}),a.jsx("div",{className:"flex-1 md:hidden",children:a.jsx("img",{src:DUe,alt:"LevelUp",className:"h-8 w-auto"})}),a.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:a.jsx(Sre,{})}),a.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[P&&!R&&D&&a.jsx(RKe,{expiresAt:D,className:"hidden lg:flex"}),a.jsx("div",{className:"md:hidden",children:a.jsx(Sre,{})}),V&&a.jsx(DKe,{hasUnseenBrief:W,onClick:Z}),B&&a.jsxs(zt,{variant:"ghost",size:"icon",className:"relative",onClick:()=>be("/marketplace/cart"),children:[a.jsx($fe,{className:"h-5 w-5"}),we>0&&a.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:we>99?"99+":we})]}),a.jsx(zt,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>be("/mission-control/calendar"),children:a.jsx(im,{className:"h-5 w-5"})}),a.jsx(eKe,{}),a.jsx(E7e,{}),a.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",Se.split(" ")[0],"!"]}),a.jsxs(mC,{children:[a.jsx(pC,{asChild:!0,children:a.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:a.jsxs(fd,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[a.jsx(md,{src:k||void 0}),a.jsx(pd,{className:"bg-primary text-primary-foreground font-medium text-sm",children:rt(Se)})]})})}),a.jsxs(qS,{align:"end",className:"w-48",children:[a.jsxs(Eu,{onClick:()=>be("/profile"),className:"cursor-pointer",children:[a.jsx(vc,{className:"h-4 w-4 mr-2"}),"Profile"]}),a.jsxs(Eu,{onClick:()=>be("/credits"),className:"cursor-pointer",children:[a.jsx(c9,{className:"h-4 w-4 mr-2"}),"Credits & Wallet"]}),a.jsxs(Eu,{onClick:()=>be("/mission-control/integrations"),className:"cursor-pointer",children:[a.jsx(oD,{className:"h-4 w-4 mr-2"}),"Integrations"]}),a.jsxs(Eu,{onClick:()=>be("/mission-control/browser-extension"),className:"cursor-pointer",children:[a.jsx(oD,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),a.jsx(Dj,{}),a.jsxs(Eu,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[a.jsx(NO,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),a.jsx(JKe,{children:a.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),V&&a.jsx(ZKe,{brief:V,open:G,onClose:Q,onDismiss:re}),a.jsx(QKe,{}),a.jsx(rYe,{}),a.jsx(aYe,{}),a.jsx(gYe,{})]})]})})},ut=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,rolesLoading:o,isAdmin:c,isBrokerageManager:s}=Gn(),f=Bi(),p=Fye();if(i||(e||r)&&o)return a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),a.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const y=f.pathname+f.search+f.hash;return y&&y!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",y),a.jsx(li,{to:"/auth",replace:!0})}if(e&&!c)return a.jsx(li,{to:"/dashboard",replace:!0});if(r&&!s&&!c)return a.jsx(li,{to:"/dashboard",replace:!0});if(p.isRestricted&&!p.isLoading){const y=oUe(f.pathname);if(y&&!p.hasFeature(y))return a.jsx(G1,{title:"Upgrade required",children:a.jsx(uUe,{featureKey:y})})}return a.jsx(a.Fragment,{children:t})};function Ez({children:t}){const{isAdmin:e,loading:r,rolesLoading:n}=Gn(),{isFeatureEnabled:i,isLoading:o}=u3();return r||n||o?a.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!e&&!i("staging_studio_enabled")?a.jsx(li,{to:"/apps",replace:!0}):a.jsx(G1,{title:"Staging Studio",children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:t})})}var $7={};(function t(e,r,n,i){var o=!!(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),Se=Ie.getContext("2d");Se.fillRect(0,0,1,1);var ve=Ie.transferToImageBitmap();Se.createPattern(ve,"no-repeat")}catch{return!1}return!0}();function f(){}function p(Ie){var Se=r.exports.Promise,ve=Se!==void 0?Se:e.Promise;return typeof ve=="function"?new ve(Ie):(Ie(f,f),null)}var y=function(Ie,Se){return{transform:function(ve){if(Ie)return ve;if(Se.has(ve))return Se.get(ve);var We=new OffscreenCanvas(ve.width,ve.height),rt=We.getContext("2d");return rt.drawImage(ve,0,0),Se.set(ve,We),We},clear:function(){Se.clear()}}}(s,new Map),_=function(){var Ie=Math.floor(16.666666666666668),Se,ve,We={},rt=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(Se=function(at){var Et=Math.random();return We[Et]=requestAnimationFrame(function _t(Vt){rt===Vt||rt+Ie-1{const{data:e,error:r}=await Re.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 AYe(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}function R8t(){const t=Nr(),{user:e}=Gn();return kr({mutationFn:async r=>{const{error:n}=await Re.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 jYe={points_earned:uD,listing_created:La,deal_closed:jp,custom:ru},jre={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"},kre=()=>{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 kYe(){const{user:t}=Gn(),e=Nr(),{data:r}=EYe(),n=AYe(),[i,o]=I.useState(null),[c,s]=I.useState(!1),f=I.useCallback(()=>{const E=Date.now()+3e3,k={startVelocity:30,spread:360,ticks:60,zIndex:9999},P=(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);Are({...k,particleCount:M,origin:{x:P(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Are({...k,particleCount:M,origin:{x:P(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);I.useEffect(()=>{kre()||r&&r.length>0&&!i&&(o(r[0]),s(!0),setTimeout(f,100))},[r,i,f]);const p=async()=>{if(i){const T=i.id;s(!1),o(null),e.setQueryData(["celebrations","pending",t==null?void 0:t.id],E=>(E==null?void 0:E.filter(k=>k.id!==T))??[]),await n.mutateAsync(T)}};if(kre()||!i)return null;const y=jYe[i.celebration_type]||ru,_=jre[i.celebration_type]||jre.custom;return a.jsx(io,{open:c,onOpenChange:T=>!T&&p(),children:a.jsxs(Ua,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[a.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${_} opacity-10`}),a.jsxs("div",{className:"relative z-10 py-6",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${_} flex items-center justify-center animate-bounce`,children:a.jsx(y,{className:"w-10 h-10 text-white"})})}),a.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[a.jsx(xs,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),a.jsx(xs,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),a.jsx(xs,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),a.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&&a.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",i.points_amount," points!"]}),i.message&&a.jsx("p",{className:"text-muted-foreground mb-6",children:i.message}),a.jsx(zt,{onClick:p,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&a.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}function dl({className:t,...e}){return a.jsx("div",{className:sr("animate-pulse rounded-md bg-muted",t),...e})}var I3="Tabs",[CYe,L8t]=Yo(I3,[VS]),D_e=VS(),[IYe,U7]=CYe(I3),M_e=I.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,onValueChange:i,defaultValue:o,orientation:c="horizontal",dir:s,activationMode:f="automatic",...p}=t,y=av(s),[_,T]=dd({prop:n,onChange:i,defaultProp:o??"",caller:I3});return a.jsx(IYe,{scope:r,baseId:Dl(),value:_,onValueChange:T,orientation:c,dir:y,activationMode:f,children:a.jsx(rn.div,{dir:y,"data-orientation":c,...p,ref:e})})});M_e.displayName=I3;var O_e="TabsList",F_e=I.forwardRef((t,e)=>{const{__scopeTabs:r,loop:n=!0,...i}=t,o=U7(O_e,r),c=D_e(r);return a.jsx(G9,{asChild:!0,...c,orientation:o.orientation,dir:o.dir,loop:n,children:a.jsx(rn.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:e})})});F_e.displayName=O_e;var B_e="TabsTrigger",z_e=I.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,disabled:i=!1,...o}=t,c=U7(B_e,r),s=D_e(r),f=V_e(c.baseId,n),p=q_e(c.baseId,n),y=n===c.value;return a.jsx(H9,{asChild:!0,...s,focusable:!i,active:y,children:a.jsx(rn.button,{type:"button",role:"tab","aria-selected":y,"aria-controls":p,"data-state":y?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:f,...o,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";!y&&!i&&_&&c.onValueChange(n)})})})});z_e.displayName=B_e;var $_e="TabsContent",U_e=I.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,forceMount:i,children:o,...c}=t,s=U7($_e,r),f=V_e(s.baseId,n),p=q_e(s.baseId,n),y=n===s.value,_=I.useRef(y);return I.useEffect(()=>{const T=requestAnimationFrame(()=>_.current=!1);return()=>cancelAnimationFrame(T)},[]),a.jsx(pl,{present:i||y,children:({present:T})=>a.jsx(rn.div,{"data-state":y?"active":"inactive","data-orientation":s.orientation,role:"tabpanel","aria-labelledby":f,hidden:!T,id:p,tabIndex:0,...c,ref:e,style:{...t.style,animationDuration:_.current?"0s":void 0},children:T&&o})})});U_e.displayName=$_e;function V_e(t,e){return`${t}-trigger-${e}`}function q_e(t,e){return`${t}-content-${e}`}var NYe=M_e,G_e=F_e,H_e=z_e,W_e=U_e;const V7=NYe,N3=I.forwardRef(({className:t,...e},r)=>a.jsx(G_e,{ref:r,className:sr("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));N3.displayName=G_e.displayName;const kp=I.forwardRef(({className:t,...e},r)=>a.jsx(H_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}));kp.displayName=H_e.displayName;const Uy=I.forwardRef(({className:t,...e},r)=>a.jsx(W_e,{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}));Uy.displayName=W_e.displayName;const qj="#0d0d0d",zD="#1a1a1a",Zl="#c9a84c",SC="#f0d78c",hm={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function P3(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 Re.functions.invoke("public-site-lead",{body:e});if(n)throw n;try{localStorage.setItem(hm.captured,JSON.stringify({email:t.email,ts:Date.now()}))}catch{}return r}function q7(){try{return!!localStorage.getItem(hm.captured)}catch{return!1}}function PYe(){try{const t=localStorage.getItem(hm.captured);return t?JSON.parse(t).email??null:null}catch{return null}}function G7({open:t,onClose:e,children:r}){return I.useEffect(()=>{if(!t)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[t]),t?Yp.createPortal(a.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:a.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, ${zD} 0%, ${qj} 100%)`,border:`1px solid ${Zl}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${Zl}22 inset`},children:[a.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:a.jsx(Ds,{className:"h-4 w-4"})}),r]})}),document.body):null}function H7(){const[t,e]=I.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=I.useState(!1),[i,o]=I.useState("");return{values:t,setValues:e,loading:r,setLoading:n,honeypot:i,setHoneypot:o}}function W7({values:t,setValues:e,honeypot:r,setHoneypot:n,showPhone:i=!0,showArea:o=!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 a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(vc,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),a.jsx("input",{type:"text",placeholder:"First name",value:t.first_name,onChange:p=>e({...t,first_name:p.target.value}),className:s,style:f})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Ti,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),a.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:t.email,onChange:p=>e({...t,email:p.target.value}),className:s,style:f})]}),i&&a.jsxs("div",{className:"relative",children:[a.jsx(ai,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),a.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:t.phone,onChange:p=>e({...t,phone:p.target.value}),className:s,style:f})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx(qs,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),a.jsx("input",{type:"text",placeholder:c,value:t.area,onChange:p=>e({...t,area:p.target.value}),className:s,style:f})]}),a.jsx("input",{type:"text",value:r,onChange:p=>n(p.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function K7({children:t,disabled:e,onClick:r,type:n="button"}){return a.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, ${SC} 0%, ${Zl} 100%)`,color:qj,boxShadow:`0 8px 24px ${Zl}55`},children:t})}function Cre({open:t,onClose:e,initialCriteria:r}){const{values:n,setValues:i,loading:o,setLoading:c,honeypot:s,setHoneypot:f}=H7(),[p,y]=I.useState(!1),_=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await P3({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()}:{}}}),y(!0);try{localStorage.setItem(hm.stickyDismissed,"1")}catch{}setTimeout(e,2200)}catch{Gt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return a.jsx(G7,{open:t,onClose:e,children:a.jsxs("div",{className:"p-8",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Qk,{className:"h-4 w-4",style:{color:Zl}}),a.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:SC},children:"New Listing Alerts"})]}),a.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),a.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."}),p?a.jsxs("div",{className:"py-6 text-center",children:[a.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${Zl}22`,border:`1px solid ${Zl}55`},children:a.jsx(xs,{className:"h-5 w-5",style:{color:Zl}})}),a.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),a.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):a.jsxs("form",{onSubmit:_,className:"space-y-4",children:[a.jsx(W7,{values:n,setValues:i,honeypot:s,setHoneypot:f}),a.jsx(K7,{type:"submit",disabled:o||!n.email,children:o?"Activating…":"Activate Alerts"}),a.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function RYe(){const[t,e]=I.useState(!0),[r,n]=I.useState(!1);I.useEffect(()=>{try{const o=!!localStorage.getItem(hm.stickyDismissed)||q7();e(o)}catch{e(!1)}},[]);const i=()=>{e(!0);try{localStorage.setItem(hm.stickyDismissed,"1")}catch{}};return t?a.jsx(Cre,{open:r,onClose:()=>n(!1)}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${zD} 0%, ${qj} 100%)`,borderTop:`1px solid ${Zl}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:a.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[a.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${Zl}22`,border:`1px solid ${Zl}55`},children:a.jsx(Qk,{className:"h-4 w-4",style:{color:Zl}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),a.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),a.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, ${SC} 0%, ${Zl} 100%)`,color:qj},children:"Get Alerts"}),a.jsx("button",{onClick:i,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:a.jsx(Ds,{className:"h-4 w-4"})})]})}),a.jsx(Cre,{open:r,onClose:()=>n(!1)})]})}function LYe(){const[t,e]=I.useState(!1),r=I.useRef(!1);I.useEffect(()=>{try{if(sessionStorage.getItem(hm.exitShown)||q7())return}catch{}const T=setTimeout(()=>{r.current=!0},8e3),E=k=>{if(r.current&&!(k.clientY>0)){e(!0);try{sessionStorage.setItem(hm.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:o,setLoading:c,honeypot:s,setHoneypot:f}=H7(),[p,y]=I.useState(!1),_=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await P3({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}),y(!0),setTimeout(()=>e(!1),2200)}catch{Gt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return a.jsx(G7,{open:t,onClose:()=>e(!1),children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${qj} 0%, ${zD} 60%, ${Zl} 130%)`},children:a.jsx("div",{className:"absolute top-4 left-6",children:a.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:SC},children:"Before You Go"})})}),a.jsxs("div",{className:"p-8 -mt-10",children:[a.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:zD,border:`1px solid ${Zl}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:a.jsx(xs,{className:"h-6 w-6",style:{color:Zl}})}),a.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),a.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."}),p?a.jsxs("div",{className:"py-4 text-center",children:[a.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),a.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):a.jsxs("form",{onSubmit:_,className:"space-y-4",children:[a.jsx(W7,{values:n,setValues:i,honeypot:s,setHoneypot:f,showPhone:!1}),a.jsx(K7,{type:"submit",disabled:o||!n.email,children:o?"Sending…":"Send My List"})]})]})]})})}function DYe(){const[t,e]=I.useState([]);I.useEffect(()=>{try{const s=localStorage.getItem(hm.savedListings);s&&e(JSON.parse(s))}catch{}},[]);const r=s=>{e(s);try{localStorage.setItem(hm.savedListings,JSON.stringify(s))}catch{}},n=I.useCallback(s=>t.includes(s),[t]),i=s=>{t.includes(s)||r([...t,s])},o=s=>r(t.filter(f=>f!==s));return{ids:t,has:n,add:i,remove:o,toggle:s=>t.includes(s)?o(s):i(s)}}function MYe({listingId:t,listingAddress:e,className:r}){const{has:n,add:i,remove:o}=DYe(),c=n(t),[s,f]=I.useState(!1),p=()=>{if(c){o(t);return}if(q7()){i(t),Gt.success("Saved to your favorites"),P3({lead_type:"saved_listing",email:PYe()||"unknown@local",listing_id:t,listing_address:e}).catch(()=>{});return}f(!0)};return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:p,className:r,"aria-label":c?"Remove from favorites":"Save to favorites",children:a.jsx(um,{className:`h-5 w-5 ${c?"fill-current":""}`})}),a.jsx(OYe,{open:s,onClose:()=>f(!1),listingId:t,listingAddress:e,onSaved:()=>i(t)})]})}function OYe({open:t,onClose:e,listingId:r,listingAddress:n,onSaved:i}){const{values:o,setValues:c,loading:s,setLoading:f,honeypot:p,setHoneypot:y}=H7(),_=async T=>{if(T.preventDefault(),!!o.email){f(!0);try{await P3({lead_type:"saved_listing",email:o.email.trim().toLowerCase(),first_name:o.first_name.trim()||void 0,phone:o.phone.trim()||void 0,listing_id:r,listing_address:n}),i(),Gt.success("Saved to your favorites"),e()}catch{Gt.error("Something went wrong. Please try again.")}finally{f(!1)}}};return a.jsx(G7,{open:t,onClose:e,children:a.jsxs("div",{className:"p-8",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(um,{className:"h-4 w-4",style:{color:Zl}}),a.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:SC},children:"Save This Home"})]}),a.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),a.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."}),a.jsxs("form",{onSubmit:_,className:"space-y-4",children:[a.jsx(W7,{values:o,setValues:c,honeypot:p,setHoneypot:y}),a.jsx(K7,{type:"submit",disabled:s||!o.email,children:s?"Saving…":"Save Home"})]})]})})}var K_e=["PageUp","PageDown"],Y_e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Z_e={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},KS="Slider",[EV,FYe,BYe]=Zk(KS),[X_e,D8t]=Yo(KS,[BYe]),[zYe,R3]=X_e(KS),Q_e=I.forwardRef((t,e)=>{const{name:r,min:n=0,max:i=100,step:o=1,orientation:c="horizontal",disabled:s=!1,minStepsBetweenThumbs:f=0,defaultValue:p=[n],value:y,onValueChange:_=()=>{},onValueCommit:T=()=>{},inverted:E=!1,form:k,...P}=t,R=I.useRef(new Set),D=I.useRef(0),B=c==="horizontal"?$Ye:UYe,[V=[],G]=dd({prop:y,defaultProp:p,onChange:ue=>{var we;(we=[...R.current][D.current])==null||we.focus(),_(ue)}}),W=I.useRef(V);function Z(ue){const _e=WYe(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:we}={commit:!1}){const Ce=XYe(o),Me=QYe(Math.round((ue-n)/o)*o+n,Ce),Ae=Oj(Me,[n,i]);G((be=[])=>{const me=GYe(be,Ae,_e);if(ZYe(me,f*o)){D.current=me.indexOf(Ae);const Pe=String(me)!==String(be);return Pe&&we&&T(me),Pe?me:be}else return be})}return a.jsx(zYe,{scope:t.__scopeSlider,name:r,disabled:s,min:n,max:i,valueIndexToChangeRef:D,thumbs:R.current,values:V,orientation:c,form:k,children:a.jsx(EV.Provider,{scope:t.__scopeSlider,children:a.jsx(EV.Slot,{scope:t.__scopeSlider,children:a.jsx(B,{"aria-disabled":s,"data-disabled":s?"":void 0,...P,ref:e,onPointerDown:Or(P.onPointerDown,()=>{s||(W.current=V)}),min:n,max:i,inverted:E,onSlideStart:s?void 0:Z,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 Me=K_e.includes(ue.key)||ue.shiftKey&&Y_e.includes(ue.key)?10:1,Ae=D.current,be=V[Ae],me=o*Me*_e;se(be+me,Ae,{commit:!0})}}})})})})});Q_e.displayName=KS;var[J_e,eve]=X_e(KS,{startEdge:"left",endEdge:"right",size:"width",direction:1}),$Ye=I.forwardRef((t,e)=>{const{min:r,max:n,dir:i,inverted:o,onSlideStart:c,onSlideMove:s,onSlideEnd:f,onStepKeyDown:p,...y}=t,[_,T]=I.useState(null),E=Kn(e,B=>T(B)),k=I.useRef(void 0),P=av(i),R=P==="ltr",D=R&&!o||!R&&o;function M(B){const V=k.current||_.getBoundingClientRect(),G=[0,V.width],Z=Y7(G,D?[r,n]:[n,r]);return k.current=V,Z(B-V.left)}return a.jsx(J_e,{scope:t.__scopeSlider,startEdge:D?"left":"right",endEdge:D?"right":"left",direction:D?1:-1,size:"width",children:a.jsx(tve,{dir:P,"data-orientation":"horizontal",...y,ref:E,style:{...y.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:()=>{k.current=void 0,f==null||f()},onStepKeyDown:B=>{const G=Z_e[D?"from-left":"from-right"].includes(B.key);p==null||p({event:B,direction:G?-1:1})}})})}),UYe=I.forwardRef((t,e)=>{const{min:r,max:n,inverted:i,onSlideStart:o,onSlideMove:c,onSlideEnd:s,onStepKeyDown:f,...p}=t,y=I.useRef(null),_=Kn(e,y),T=I.useRef(void 0),E=!i;function k(P){const R=T.current||y.current.getBoundingClientRect(),D=[0,R.height],B=Y7(D,E?[n,r]:[r,n]);return T.current=R,B(P-R.top)}return a.jsx(J_e,{scope:t.__scopeSlider,startEdge:E?"bottom":"top",endEdge:E?"top":"bottom",size:"height",direction:E?1:-1,children:a.jsx(tve,{"data-orientation":"vertical",...p,ref:_,style:{...p.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:P=>{const R=k(P.clientY);o==null||o(R)},onSlideMove:P=>{const R=k(P.clientY);c==null||c(R)},onSlideEnd:()=>{T.current=void 0,s==null||s()},onStepKeyDown:P=>{const D=Z_e[E?"from-bottom":"from-top"].includes(P.key);f==null||f({event:P,direction:D?-1:1})}})})}),tve=I.forwardRef((t,e)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:c,onEndKeyDown:s,onStepKeyDown:f,...p}=t,y=R3(KS,r);return a.jsx(rn.span,{...p,ref:e,onKeyDown:Or(t.onKeyDown,_=>{_.key==="Home"?(c(_),_.preventDefault()):_.key==="End"?(s(_),_.preventDefault()):K_e.concat(Y_e).includes(_.key)&&(f(_),_.preventDefault())}),onPointerDown:Or(t.onPointerDown,_=>{const T=_.target;T.setPointerCapture(_.pointerId),_.preventDefault(),y.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),o(_))})})}),rve="SliderTrack",nve=I.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=R3(rve,r);return a.jsx(rn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:e})});nve.displayName=rve;var AV="SliderRange",ive=I.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=R3(AV,r),o=eve(AV,r),c=I.useRef(null),s=Kn(e,c),f=i.values.length,p=i.values.map(T=>ove(T,i.min,i.max)),y=f>1?Math.min(...p):0,_=100-Math.max(...p);return a.jsx(rn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:s,style:{...t.style,[o.startEdge]:y+"%",[o.endEdge]:_+"%"}})});ive.displayName=AV;var jV="SliderThumb",sve=I.forwardRef((t,e)=>{const r=FYe(t.__scopeSlider),[n,i]=I.useState(null),o=Kn(e,s=>i(s)),c=I.useMemo(()=>n?r().findIndex(s=>s.ref.current===n):-1,[r,n]);return a.jsx(VYe,{...t,ref:o,index:c})}),VYe=I.forwardRef((t,e)=>{const{__scopeSlider:r,index:n,name:i,...o}=t,c=R3(jV,r),s=eve(jV,r),[f,p]=I.useState(null),y=Kn(e,M=>p(M)),_=f?c.form||!!f.closest("form"):!0,T=oC(f),E=c.values[n],k=E===void 0?0:ove(E,c.min,c.max),P=HYe(n,c.values.length),R=T==null?void 0:T[s.size],D=R?KYe(R,k,s.direction):0;return I.useEffect(()=>{if(f)return c.thumbs.add(f),()=>{c.thumbs.delete(f)}},[f,c.thumbs]),a.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${k}% + ${D}px)`},children:[a.jsx(EV.ItemSlot,{scope:t.__scopeSlider,children:a.jsx(rn.span,{role:"slider","aria-label":t["aria-label"]||P,"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,...o,ref:y,style:E===void 0?{display:"none"}:t.style,onFocus:Or(t.onFocus,()=>{c.valueIndexToChangeRef.current=n})})}),_&&a.jsx(ave,{name:i??(c.name?c.name+(c.values.length>1?"[]":""):void 0),form:c.form,value:E},n)]})});sve.displayName=jV;var qYe="RadioBubbleInput",ave=I.forwardRef(({__scopeSlider:t,value:e,...r},n)=>{const i=I.useRef(null),o=Kn(i,n),c=xC(e);return I.useEffect(()=>{const s=i.current;if(!s)return;const f=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&y){const _=new Event("input",{bubbles:!0});y.call(s,e),s.dispatchEvent(_)}},[c,e]),a.jsx(rn.input,{style:{display:"none"},...r,ref:o,defaultValue:e})});ave.displayName=qYe;function GYe(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,o)=>i-o)}function ove(t,e,r){const o=100/(r-e)*(t-e);return Oj(o,[0,100])}function HYe(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function WYe(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 KYe(t,e,r){const n=t/2,o=Y7([0,50],[0,n]);return(n-o(e)*r)*r}function YYe(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}function ZYe(t,e){if(e>0){const r=YYe(t);return Math.min(...r)>=e}return!0}function Y7(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 XYe(t){return(String(t).split(".")[1]||"").length}function QYe(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}var lve=Q_e,JYe=nve,eZe=ive,tZe=sve;const UA=I.forwardRef(({className:t,...e},r)=>a.jsxs(lve,{ref:r,className:sr("relative flex w-full touch-none select-none items-center",t),...e,children:[a.jsx(JYe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a.jsx(eZe,{className:"absolute h-full bg-primary"})}),a.jsx(tZe,{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"})]}));UA.displayName=lve.displayName;const rZe=t=>gr({queryKey:["public-listings",t],queryFn:async()=>{let e=Re.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 o=`%${i}%`;e=e.or(`city.ilike.${o},neighborhood.ilike.${o},property_address.ilike.${o}`)}}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}}),nZe=()=>gr({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:e}=await Re.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(o=>{if(o.city){const c=`${o.city}|${o.state||""}`.toLowerCase(),s=o.state?`${o.city}, ${o.state}`:o.city,f=r.get(c);f?f.count++:r.set(c,{label:s,city:o.city,state:o.state,count:1})}if(o.neighborhood){const c=`${o.neighborhood}|${o.city||""}`.toLowerCase(),s=o.city?`${o.neighborhood} — ${o.city}`:o.neighborhood,f=n.get(c);f?f.count++:n.set(c,{label:s,city:o.city||"",neighborhood:o.neighborhood,count:1})}if(o.property_address){const c=String(o.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((o,c)=>c.count-o.count),neighborhoods:Array.from(n.values()).sort((o,c)=>c.count-o.count),zips:Array.from(i.values()).sort((o,c)=>c.count-o.count)}}}),iZe=t=>gr({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=Re.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 o=n;return Array.isArray(o==null?void 0:o.photos)&&(o.photos=[...o.photos].sort((c,s)=>(c.sort_order??0)-(s.sort_order??0)||(s.is_primary?1:0)-(c.is_primary?1:0))),o},enabled:!!t}),sZe=()=>kr({mutationFn:async({listingId:t,agentId:e,firstName:r,lastName:n,email:i,phone:o,shareToken:c,leadType:s="info_request",preferredDate:f,preferredTime:p,showingMode:y,message:_})=>{let T=null,E=null;if(c){const{data:M}=await Re.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 k=crypto.randomUUID(),P={id:k},{error:R}=await Re.from("listing_leads").insert({id:k,listing_id:t,agent_id:E||e,first_name:r,last_name:n,email:i,phone:o,share_id:T,referred_by_agent_id:E,lead_type:s,preferred_date:f||null,preferred_time:p||null,showing_mode:y||null,message:_||null});if(R)throw R;const{error:D}=await Re.functions.invoke("process-listing-lead",{body:{leadId:P.id}});return D&&console.error("Error processing lead:",D),P}}),aZe=()=>kr({mutationFn:async t=>{const{error:e}=await Re.rpc("increment_listing_share_click",{p_share_token:t});if(e)throw e}});function oZe({title:t,subtitle:e,areaLabel:r,sections:n,agent:i,tone:o="light"}){const c=o==="dark",s=c?"text-white/65":"text-muted-foreground",f=c?"border-white/10":"border-border";return a.jsxs("div",{className:c?"text-white":"text-foreground",id:"community-guide-print",children:[a.jsxs("header",{className:`border-b ${f} pb-6 mb-8`,children:[a.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${s} mb-3`,children:[a.jsx(N1,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),a.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:t}),e&&a.jsx("p",{className:`mt-3 text-base leading-relaxed ${s}`,children:e}),r&&a.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${s}`,children:[a.jsx(qs,{className:"h-3.5 w-3.5"}),r]})]}),a.jsx("div",{className:"space-y-10",children:n.map((p,y)=>a.jsxs("section",{children:[a.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[a.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(y+1).padStart(2,"0")}),a.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:p.heading})]}),p.intro&&a.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${s} mb-4`,children:p.intro}),a.jsx("ul",{className:"space-y-3",children:(p.items??[]).map((_,T)=>a.jsxs("li",{className:`rounded-xl border ${f} ${c?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[a.jsx("p",{className:"font-medium text-sm sm:text-base",children:_.name}),_.note&&a.jsx("p",{className:`text-sm mt-1 leading-relaxed ${s}`,children:_.note})]},T))})]},y))}),(i==null?void 0:i.name)&&a.jsxs("footer",{className:`mt-10 pt-6 border-t ${f}`,children:[a.jsxs("div",{className:"flex items-center gap-4",children:[i.avatar_url?a.jsx("img",{src:i.avatar_url,alt:i.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${s}`,children:"Prepared for you by"}),a.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:i.name}),i.brokerage&&a.jsx("p",{className:`text-sm ${s}`,children:i.brokerage}),a.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${s}`,children:[i.phone&&a.jsxs("a",{href:`tel:${i.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[a.jsx(ai,{className:"h-3.5 w-3.5"}),i.phone]}),i.email&&a.jsxs("a",{href:`mailto:${i.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[a.jsx(Ti,{className:"h-3.5 w-3.5"}),i.email]})]})]})]}),a.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 WP="border-white/15 bg-white/5 text-white placeholder:text-white/40";function lZe({listingId:t}){const[e,r]=I.useState(null),[n,i]=I.useState({firstName:"",lastName:"",email:"",phone:""}),[o,c]=I.useState(!1),[s,f]=I.useState(null),[p,y]=I.useState(!1);if(I.useEffect(()=>{let T=!1;return Re.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()){Gt.error("Please add your name and email.");return}c(!0);try{const{data:E,error:k}=await Re.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:t,...n}});if(k||E!=null&&E.error)throw new Error((E==null?void 0:E.error)||"Something went wrong.");f(E),y(!0),Gt.success("Your guide is ready!")}catch(E){Gt.error((E==null?void 0:E.message)||"We could not send your guide. Please try again.")}finally{c(!1)}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[a.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[a.jsx(N1,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),a.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:e.title}),e.subtitle&&a.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:e.subtitle}),(e.teaser??[]).length>0&&a.jsx("ul",{className:"mt-4 space-y-2",children:e.teaser.map((T,E)=>a.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[a.jsx(ko,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),T]},E))}),s?a.jsxs(zt,{className:"w-full mt-5",onClick:()=>y(!0),children:[a.jsx(N1,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):a.jsxs("form",{onSubmit:_,className:"mt-5 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),a.jsx($r,{id:"cg-first",value:n.firstName,onChange:T=>i({...n,firstName:T.target.value}),className:WP,required:!0})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),a.jsx($r,{id:"cg-last",value:n.lastName,onChange:T=>i({...n,lastName:T.target.value}),className:WP})]})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),a.jsx($r,{id:"cg-email",type:"email",value:n.email,onChange:T=>i({...n,email:T.target.value}),className:WP,required:!0})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),a.jsx($r,{id:"cg-phone",type:"tel",value:n.phone,onChange:T=>i({...n,phone:T.target.value}),className:WP})]}),a.jsxs(zt,{type:"submit",className:"w-full",disabled:o,children:[o?a.jsx(Ru,{className:"h-4 w-4 mr-2 animate-spin"}):a.jsx(rc,{className:"h-4 w-4 mr-2"}),o?"Preparing your guide…":"Get the free guide"]}),a.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[a.jsx(Zy,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),a.jsx(io,{open:p,onOpenChange:y,children:a.jsx(Ua,{className:"max-w-2xl p-0 gap-0",children:a.jsx(Sm,{className:"max-h-[82vh]",children:a.jsxs("div",{className:"p-6 sm:p-8",children:[a.jsx("div",{id:"community-guide-print",children:s&&a.jsx(oZe,{title:s.title,subtitle:s.subtitle,areaLabel:s.area_label,sections:s.sections??[],agent:s.agent})}),a.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:a.jsxs(zt,{variant:"outline",onClick:()=>cZe(s==null?void 0:s.title),children:[a.jsx(rc,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function cZe(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 o=()=>{i||(i=!0,r.remove(),document.body.classList.remove("printing-doc"),document.title=n,window.removeEventListener("afterprint",o))};window.addEventListener("afterprint",o);try{window.print()}finally{setTimeout(o,1e3)}}const Ire={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},cve={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"},M8t=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],uZe={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},dZe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},O8t={public:"Open download",email:"Email required",nda:"NDA required"},hZe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},F8t=[{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"}],Az=[{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"}],B8t=[{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 Yh(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 Nre(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`:Yh(e)}function kV(t){return t==null?null:`${new Intl.NumberFormat("en-US").format(Number(t))} SF`}function uve(t,e=2){return t==null?null:`${Number(t).toFixed(e).replace(/\.?0+$/,"")}%`}function CV(t){if(!(t!=null&&t.lease_rate))return null;const e=uZe[t.lease_rate_unit||"sf_year"]??"";return`${t.lease_rate_unit==="month"?Yh(t.lease_rate):`$${Number(t.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${e}${t.lease_type?` ${t.lease_type}`:""}`}function Pre(t,e){if(!t)return Yh(e)??"Price on request";if(t.deal_type==="lease")return CV(t)??"Rate on request";const r=t.asking_price??e;if(t.deal_type==="sale_or_lease"){const n=[Yh(r),CV(t)].filter(Boolean);return n.length?n.join(" · "):"Price on request"}return Yh(r)??"Price on request"}function fZe(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?cve[e.commercial_type]:"Commercial"} Opportunity`:t.property_address||`${t.city??""}, ${t.state??""}`}function mZe(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 z8t(t,e){var o;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:(((o=t==null?void 0:t.investment_highlights)==null?void 0:o.length)??0)>=3,om:e.hasOm,microsite:e.isPublic};for(const c of Az)(i[c.key]||r[c.key])&&n.push(c.key);return{done:n,total:Az.length,score:Math.round(n.length/Az.length*100)}}const $8t={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 U8t(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 V8t="https://commercial.relevelup.com",fm=Re;function q8t(t){return gr({queryKey:["commercial-details",t],queryFn:async()=>{const{data:e,error:r}=await fm.from("commercial_listing_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function G8t(){const t=Nr(),{user:e}=Gn();return kr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await fm.from("commercial_listing_details").upsert({listing_id:r,agent_id:e==null?void 0:e.id,...n},{onConflict:"listing_id"}).select().single();if(o)throw o;return i},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["commercial-details",n.listingId]}),t.invalidateQueries({queryKey:["listing",n.listingId]})}})}function H8t(t){return gr({queryKey:["commercial-pitch",t],queryFn:async()=>{const{data:e,error:r}=await fm.from("commercial_pitch_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function W8t(){const t=Nr(),{user:e}=Gn();return kr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await fm.from("commercial_pitch_details").upsert({listing_id:r,agent_id:e==null?void 0:e.id,...n},{onConflict:"listing_id"}).select().single();if(o)throw o;return i},onSuccess:(r,n)=>t.invalidateQueries({queryKey:["commercial-pitch",n.listingId]})})}function K8t(){const t=Nr();return kr({mutationFn:async({listingId:e,stage:r,lostReason:n})=>{const i=r==="won",o=r==="lost",c={lifecycle_stage:r};i&&(c.status="coming_soon"),o&&(c.is_public=!1,c.allow_sharing=!1);const{error:s}=await fm.from("listings").update(c).eq("id",e);if(s)throw s;return(i||o)&&await fm.from("commercial_pitch_details").update({outcome:i?"won":"lost",won_at:i?new Date().toISOString():null,lost_at:o?new Date().toISOString():null,lost_reason:o?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 Y8t(){const t=Nr();return kr({mutationFn:async({listingId:e,values:r})=>{const{error:n}=await fm.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 Z8t(t,e=90){return gr({queryKey:["commercial-engagement",t,e],queryFn:async()=>{const r=new Date(Date.now()-e*864e5).toISOString(),{data:n,error:i}=await fm.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 X8t(t){return gr({queryKey:["commercial-leads",t],queryFn:async()=>{const{data:e,error:r}=await fm.from("listing_leads").select("*").eq("listing_id",t).order("created_at",{ascending:!1});if(r)throw r;return e??[]},enabled:!!t})}const Rre="lu_commercial_session";function dve(){try{let t=localStorage.getItem(Rre);return t||(t=crypto.randomUUID(),localStorage.setItem(Rre,t)),t}catch{return"anonymous"}}async function tw(t,e,r={}){try{await fm.from("commercial_engagement_events").insert({listing_id:t,event_type:e,session_id:dve(),source:typeof document<"u"&&document.referrer||null,metadata:r})}catch{}}const pZe={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 gZe({open:t,onOpenChange:e,listingId:r,kind:n,documentId:i,requiresNda:o,brokerName:c}){const s=pZe[n],[f,p]=I.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[y,_]=I.useState(!1),[T,E]=I.useState(!1),[k,P]=I.useState(null),R=async()=>{if(!f.firstName.trim()||!f.email.trim()){Gt.error("Name and email are required");return}if(o&&n==="om_request"&&!y){Gt.error("Please acknowledge the confidentiality terms");return}E(!0);try{const{data:D,error:M}=await Re.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:y,sessionId:dve()}});if(M)throw M;if(D!=null&&D.error)throw new Error(D.error);P({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){Gt.error(D.message||"Something went wrong. Please try again.")}finally{E(!1)}};return a.jsx(io,{open:t,onOpenChange:D=>{e(D),D||P(null)},children:a.jsxs(Ua,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[a.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:s.eyebrow}),a.jsx("h2",{className:"mt-2 font-serif text-2xl",children:k?"Access granted":s.title}),a.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:k?k.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})]}),k?a.jsxs("div",{className:"space-y-4 px-7 py-7",children:[a.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[a.jsx(ic,{className:"h-5 w-5 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white/80",children:k.fileName??"Request received"})]}),k.signedUrl&&a.jsx(zt,{className:"w-full",onClick:()=>window.open(k.signedUrl,"_blank"),children:"Download again"}),a.jsx(zt,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>e(!1),children:"Close"})]}):a.jsxs("div",{className:"space-y-4 px-7 py-6",children:[a.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[a.jsx($0,{label:"First name *",children:a.jsx($r,{value:f.firstName,onChange:D=>p({...f,firstName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),a.jsx($0,{label:"Last name",children:a.jsx($r,{value:f.lastName,onChange:D=>p({...f,lastName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),a.jsx($0,{label:"Email *",children:a.jsx($r,{type:"email",value:f.email,onChange:D=>p({...f,email:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),a.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[a.jsx($0,{label:"Company",children:a.jsx($r,{value:f.company,onChange:D=>p({...f,company:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),a.jsx($0,{label:"Phone",children:a.jsx($r,{value:f.phone,onChange:D=>p({...f,phone:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),a.jsx($0,{label:"I am a *",children:a.jsxs(_a,{value:f.role,onValueChange:D=>p({...f,role:D}),children:[a.jsx(aa,{className:"border-white/15 bg-white/5 text-white",children:a.jsx(va,{})}),a.jsx(oa,{children:Object.entries(hZe).map(([D,M])=>a.jsx(fn,{value:D,children:M},D))})]})}),n!=="om_request"&&a.jsx($0,{label:"Message",children:a.jsx(bd,{rows:3,value:f.message,onChange:D=>p({...f,message:D.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:n==="tour_request"?"Preferred dates and times…":"Your question…"})}),o&&n==="om_request"&&a.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[a.jsx(wC,{checked:y,onCheckedChange:D=>_(!!D),className:"mt-0.5 border-white/30"}),a.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[a.jsx(a9,{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."]})]}),a.jsxs(zt,{className:"w-full",size:"lg",onClick:R,disabled:T,children:[T?a.jsx(Ru,{className:"mr-2 h-4 w-4 animate-spin"}):a.jsx(Zy,{className:"mr-2 h-4 w-4"}),s.cta]}),a.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function $0({label:t,children:e}){return a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:t}),e]})}function hve(t){if(!t)return[];const e=[],r=(n,i)=>{i&&e.push({label:n,value:i})};return r("Cap Rate",uve(t.cap_rate)),r("NOI",Nre(t.noi)),r("Occupancy",t.occupancy_pct!=null?`${Math.round(Number(t.occupancy_pct))}%`:null),r("Building SF",kV(t.building_sf)),r("Available SF",kV(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?Yh(t.price_per_sf,2):null),r("Price / Unit",Nre(t.price_per_unit)),r("Lease Rate",t.deal_type!=="sale"?CV(t):null),r("Year Built",null),r("Zoning",t.zoning??null),e}function Q8t({details:t,className:e="",tone:r="light"}){const n=hve(t).slice(0,8);if(!n.length)return null;const i=r==="dark";return a.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(o=>a.jsxs("div",{className:`${i?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[a.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${i?"text-white/45":"text-muted-foreground"}`,children:o.label}),a.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${i?"text-white":""}`,children:o.value})]},o.label))})}function yZe(t){return gr({queryKey:["commercial-microsite",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 xZe({slug:t}){var ue,_e;const{data:e,isLoading:r,error:n}=yZe(t),[i,o]=I.useState(null),[c,s]=I.useState(null),f=e==null?void 0:e.listing,p=(e==null?void 0:e.details)??void 0,y=(e==null?void 0:e.documents)??[],_=(f==null?void 0:f.photos)??[],T=f==null?void 0:f.agent,E=!!(p!=null&&p.is_confidential||p!=null&&p.hide_address),k=I.useMemo(()=>hve(p).slice(0,8),[p]);if(I.useEffect(()=>{f!=null&&f.id&&tw(f.id,"page_view",{slug:t})},[f==null?void 0:f.id,t]),I.useEffect(()=>{if(i===null)return;const we=Ce=>{Ce.key==="Escape"&&o(null),Ce.key==="ArrowRight"&&o(Me=>Me===null?Me:(Me+1)%_.length),Ce.key==="ArrowLeft"&&o(Me=>Me===null?Me:(Me-1+_.length)%_.length)};return window.addEventListener("keydown",we),()=>window.removeEventListener("keydown",we)},[i,_.length]),r)return a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(n||!f)return a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const P=fZe(f,p),R=mZe(f,p),D=f.latitude&&f.longitude?`${f.latitude},${f.longitude}`:E?[p==null?void 0:p.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=(p==null?void 0:p.tenants)??[],V=(p==null?void 0:p.spaces)??[],G=(p==null?void 0:p.demographics)??{},W=(p==null?void 0:p.traffic_counts)??[],Z=(p==null?void 0:p.investment_highlights)??[],Q=(p==null?void 0:p.property_highlights)??[],re=["radius_1","radius_3","radius_5"].some(we=>(G==null?void 0:G[we])&&Object.values(G[we]).some(Boolean)),se=(we,Ce)=>{s({kind:we,documentId:Ce}),tw(f.id,we==="om_request"?"om_request":we,{})};return a.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[a.jsxs(Wo,{children:[a.jsx("title",{children:`${P} | ${R}`}),a.jsx("meta",{name:"description",content:(f.description??"").slice(0,155)||`${Ire[(p==null?void 0:p.deal_type)??"sale"]} — ${R}`}),E&&a.jsx("meta",{name:"robots",content:"noindex,nofollow"}),a.jsx("meta",{property:"og:title",content:P}),a.jsx("meta",{property:"og:type",content:"website"})]}),a.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:a.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[a.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:[a.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),a.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),a.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[M?a.jsx("img",{src:M,alt:P,className:"absolute inset-0 h-full w-full object-cover"}):a.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),a.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:[a.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[a.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:Ire[(p==null?void 0:p.deal_type)??"sale"]}),(p==null?void 0:p.commercial_type)&&a.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:cve[p.commercial_type]}),E&&a.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:[a.jsx(Zy,{className:"h-3 w-3"})," Confidential offering"]})]}),a.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:P}),a.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[a.jsx(qs,{className:"h-4 w-4"})," ",R]}),a.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(p==null?void 0:p.deal_type)==="lease"?"Lease rate":"Asking price"}),a.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:Pre(p,f.price)})]}),(p==null?void 0:p.cap_rate)!=null&&a.jsxs("div",{children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),a.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:uve(p.cap_rate)})]})]}),a.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[a.jsxs(zt,{size:"lg",className:"rounded-full px-7",onClick:()=>{var we;return se("om_request",((we=y.find(Ce=>Ce.doc_kind==="om"))==null?void 0:we.id)??null)},children:["Request Offering Memorandum ",a.jsx(ra,{className:"ml-2 h-4 w-4"})]}),a.jsx(zt,{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"})]})]})]}),k.length>0&&a.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:a.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(k.length,4)}, minmax(0, 1fr))`},children:k.map(we=>a.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:we.label}),a.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:we.value})]},we.label))})}),Z.length>0&&a.jsx(Hg,{eyebrow:"The opportunity",title:"Investment highlights",children:a.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:Z.map((we,Ce)=>a.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[a.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(Ce+1).padStart(2,"0")}),a.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:we})]},Ce))})}),(f.description||Q.length>0)&&a.jsx(Hg,{eyebrow:"Property",title:"The asset",children:a.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[f.description&&a.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(f.description).split(/\n{2,}/).map((we,Ce)=>a.jsx("p",{children:we},Ce))}),Q.length>0&&a.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:Q.map((we,Ce)=>a.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[a.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",we]},Ce))})]})}),_.length>1&&a.jsx(Hg,{eyebrow:"Gallery",title:"Property imagery",children:a.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:_.slice(1,10).map((we,Ce)=>a.jsx("button",{onClick:()=>{o(Ce+1),tw(f.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${Ce===0?"md:col-span-2 md:row-span-2":""}`,children:a.jsx("img",{src:we.photo_url,alt:`${P} — image ${Ce+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${Ce===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},we.id))})}),((p==null?void 0:p.noi)||(p==null?void 0:p.gross_income)||(p==null?void 0:p.operating_expenses)||(p==null?void 0:p.occupancy_pct)!=null)&&a.jsxs(Hg,{eyebrow:"Financials",title:"Offering snapshot",children:[a.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:Yh(p==null?void 0:p.noi)},{l:"Gross income",v:Yh(p==null?void 0:p.gross_income)},{l:"Operating expenses",v:Yh(p==null?void 0:p.operating_expenses)},{l:"Occupancy",v:(p==null?void 0:p.occupancy_pct)!=null?`${Math.round(Number(p.occupancy_pct))}%`:null},{l:"Price per SF",v:(p==null?void 0:p.price_per_sf)!=null?Yh(p.price_per_sf,2):null},{l:"Price per unit",v:Yh(p==null?void 0:p.price_per_unit)},{l:"Tenancy",v:p!=null&&p.tenancy?`${p.tenancy[0].toUpperCase()}${p.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(p==null?void 0:p.broker_coop_pct)!=null?`${p.broker_coop_pct}%`:null}].filter(we=>we.v).map(we=>a.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:we.l}),a.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:we.v})]},we.l))}),(p==null?void 0:p.call_for_offers_at)&&a.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(p.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(B.length>0||V.length>0)&&a.jsx(Hg,{eyebrow:"Occupancy",title:V.length?"Space availability":"Tenant roster",children:a.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:a.jsxs("table",{className:"w-full text-left text-sm",children:[a.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-6 py-4",children:V.length?"Suite":"Tenant"}),a.jsx("th",{className:"px-6 py-4",children:"SF"}),a.jsx("th",{className:"px-6 py-4",children:V.length?"Rate":"Rent"}),a.jsx("th",{className:"px-6 py-4",children:V.length?"Availability":"Lease expiry"})]})}),a.jsx("tbody",{className:"divide-y divide-white/5",children:(V.length?V:B).map((we,Ce)=>a.jsxs("tr",{className:"text-white/80",children:[a.jsx("td",{className:"px-6 py-4 font-medium text-white",children:we.suite??we.name??"—"}),a.jsx("td",{className:"px-6 py-4 tabular-nums",children:we.sf?kV(Number(we.sf)):"—"}),a.jsx("td",{className:"px-6 py-4",children:we.rate??we.rent??"—"}),a.jsx("td",{className:"px-6 py-4",children:we.availability??we.lease_expiry??"—"})]},Ce))})]})})}),a.jsx(Hg,{eyebrow:"Location",title:p!=null&&p.submarket?`${p.submarket} submarket`:R,children:a.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[D?a.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:a.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:()=>tw(f.id,"map_view",{})})}):a.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}),a.jsxs("div",{className:"space-y-5",children:[(p==null?void 0:p.zoning)&&a.jsx(rw,{label:"Zoning",value:p.zoning}),(p==null?void 0:p.lot_acres)!=null&&a.jsx(rw,{label:"Site size",value:`${p.lot_acres} acres`}),(p==null?void 0:p.parking_spaces)!=null&&a.jsx(rw,{label:"Parking",value:`${p.parking_spaces} spaces`}),(p==null?void 0:p.opportunity_zone)&&a.jsx(rw,{label:"Opportunity Zone",value:"Qualified"}),W.filter(we=>we.road||we.count).map((we,Ce)=>a.jsx(rw,{label:`Traffic count — ${we.road??"Adjacent road"}`,value:`${we.count??"—"} VPD`},Ce)),!(p!=null&&p.zoning)&&(p==null?void 0:p.lot_acres)==null&&(p==null?void 0:p.parking_spaces)==null&&!(p!=null&&p.opportunity_zone)&&a.jsx(rw,{label:"Submarket",value:(p==null?void 0:p.submarket)||R})]})]})}),re&&a.jsx(Hg,{eyebrow:"Market",title:"Demographics",children:a.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([we,Ce])=>{const Me=G==null?void 0:G[we];return!Me||!Object.values(Me).some(Boolean)?null:a.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:Ce}),a.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",Me.population],["Households",Me.households],["Avg. income",Me.avg_income],["Daytime pop.",Me.daytime_pop]].filter(([,Ae])=>Ae).map(([Ae,be])=>a.jsxs("div",{className:"flex justify-between gap-4",children:[a.jsx("dt",{className:"text-white/50",children:Ae}),a.jsx("dd",{className:"font-medium tabular-nums",children:be})]},Ae))})]},we)})})}),y.length>0&&a.jsx(Hg,{eyebrow:"Deal room",title:"Offering documents",children:a.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:y.map(we=>{const Ce=we.gate_level==="public";return a.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:[a.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:Ce?a.jsx(rc,{className:"h-5 w-5"}):we.gate_level==="nda"?a.jsx(a9,{className:"h-5 w-5"}):a.jsx(Zy,{className:"h-5 w-5"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"truncate font-medium",children:we.title||dZe[we.doc_kind||"other"]}),a.jsx("p",{className:"text-xs text-white/45",children:Ce?"Available to download":we.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),a.jsx(zt,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>se("om_request",we.id),children:Ce?"Download":"Request"})]},we.id)})})}),T&&a.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:a.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:a.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[a.jsxs("div",{className:"flex items-center gap-6",children:[T.avatar_url&&a.jsx("img",{src:T.avatar_url,alt:T.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),a.jsx("p",{className:"mt-2 font-serif text-2xl",children:T.name}),a.jsx("p",{className:"text-sm text-white/55",children:((_e=T.brokerage)==null?void 0:_e.name)||T.brokerage_name})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-3",children:[T.email&&a.jsxs(zt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{tw(f.id,"contact_click",{}),window.location.href=`mailto:${T.email}`},children:[a.jsx(Ti,{className:"mr-2 h-4 w-4"})," Email"]}),T.phone&&a.jsxs(zt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{tw(f.id,"contact_click",{}),window.location.href=`tel:${T.phone}`},children:[a.jsx(ai,{className:"mr-2 h-4 w-4"})," Call"]}),a.jsx(zt,{className:"rounded-full",onClick:()=>se("investor_inquiry"),children:"Request information"})]})]})})}),a.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:a.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."})}),a.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:a.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:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"truncate text-sm font-medium",children:P}),a.jsxs("p",{className:"truncate text-xs text-white/50",children:[Pre(p,f.price)," · ",R]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(zt,{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"}),a.jsx(zt,{size:"sm",className:"rounded-full",onClick:()=>{var we;return se("om_request",((we=y.find(Ce=>Ce.doc_kind==="om"))==null?void 0:we.id)??null)},children:"Request OM"})]})]})}),a.jsx(io,{open:i!==null,onOpenChange:we=>!we&&o(null),children:a.jsx(Ua,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:i!==null&&_[i]&&a.jsxs("div",{className:"relative",children:[a.jsx("img",{src:_[i].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),a.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>o(null),children:a.jsx(Ds,{className:"h-5 w-5"})}),a.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>o(we=>(we-1+_.length)%_.length),children:a.jsx(xm,{className:"h-6 w-6"})}),a.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>o(we=>(we+1)%_.length),children:a.jsx(vd,{className:"h-6 w-6"})})]})})}),c&&a.jsx(gZe,{open:!0,onOpenChange:we=>!we&&s(null),listingId:f.id,kind:c.kind,documentId:c.documentId,requiresNda:!!(p!=null&&p.requires_nda)||(p==null?void 0:p.om_gate_mode)==="nda",brokerName:T==null?void 0:T.name})]})}function Hg({eyebrow:t,title:e,children:r}){return a.jsx("section",{className:"border-t border-white/10",children:a.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:t}),a.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:e}),a.jsx("div",{className:"mt-12",children:r})]})})}function rw({label:t,value:e}){return a.jsxs("div",{className:"border-t border-white/10 pt-4",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:t}),a.jsx("p",{className:"mt-1 text-lg",children:e})]})}const Lre="/assets/levelup-logo-color-BeKd2k_g.png",_Ze={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"},jz={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"},Dre={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},kz=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),G2=t=>new Intl.NumberFormat("en-US").format(t);function fve(t){var e,r;if(!t)return null;try{const n=new URL(t.trim()),i=n.hostname.replace(/^www\.|^m\./,"");let o=null;if(i==="youtu.be"?o=n.pathname.slice(1).split("/")[0]:(i==="youtube.com"||i==="youtube-nocookie.com")&&(o=n.searchParams.get("v")||((e=n.pathname.match(/\/(?:embed|shorts|live)\/([^/?]+)/))==null?void 0:e[1])||null),o&&/^[\w-]{6,20}$/.test(o))return`https://www.youtube.com/embed/${o}`;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 Z7({slugOverride:t}={}){var la,Cr,Fn,As,Sa,_o,Yr;const e=bm(),r=t||e.slugOrId,[n]=px(),{data:i,isLoading:o}=iZe(r||""),c=sZe(),s=aZe(),f=n.get("ref"),[p,y]=I.useState(""),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(""),[D,M]=I.useState(""),[B,V]=I.useState(""),[G,W]=I.useState(""),[Z,Q]=I.useState("in_person"),[re,se]=I.useState("info"),[ue,_e]=I.useState(!1),[we,Ce]=I.useState(!1),[Me,Ae]=I.useState(null),[be,me]=I.useState(!1);I.useState(!1);const[Pe,Ie]=I.useState(!1),[Se,ve]=I.useState(20),[We,rt]=I.useState(6.5),[at,Et]=I.useState(30),_t=I.useRef(null),[Vt,pt]=I.useState(!1);I.useEffect(()=>{const hn=()=>pt(window.scrollY>300);return window.addEventListener("scroll",hn,{passive:!0}),()=>window.removeEventListener("scroll",hn)},[]),I.useEffect(()=>{f&&s.mutate(f)},[f]),I.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const Nt=(i==null?void 0:i.photos)||[],er=Nt.find(hn=>hn.is_primary)||Nt[0],vt=I.useMemo(()=>{if(!(i!=null&&i.price))return 0;const hn=i.price*(1-Se/100),xn=We/100/12,Zr=at*12;return xn===0?hn/Zr:hn*xn/(1-Math.pow(1+xn,-Zr))},[i==null?void 0:i.price,Se,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),Gt.success("Link copied to clipboard")},Sr=async hn=>{if(hn.preventDefault(),!p.trim()||!E.trim()||!i)return;const xn=re==="showing";if(xn&&!B){Gt.error("Please pick a preferred date for your showing");return}_e(!0);try{await c.mutateAsync({listingId:i.id,agentId:i.agent_id,firstName:p.trim(),lastName:_.trim(),email:E.trim(),phone:P.trim(),shareToken:f,leadType:xn?"showing_request":"info_request",preferredDate:xn?B:null,preferredTime:xn&&G||null,showingMode:xn?Z:null,message:D.trim()||null}),Ce(!0),Gt.success(xn?"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),Gt.error(`Failed to submit: ${Zr.message||"Please try again"}`)}finally{_e(!1)}},nn=()=>{Me!==null&&Ae(Me===0?Nt.length-1:Me-1)},cr=()=>{Me!==null&&Ae(Me===Nt.length-1?0:Me+1)};if((i==null?void 0:i.listing_class)==="commercial")return a.jsx(xZe,{slug:r});if(o)return a.jsx("div",{className:"min-h-screen bg-neutral-950",children:a.jsx(dl,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!i)return a.jsxs("div",{className:"min-h-screen bg-background",children:[a.jsx("header",{className:"border-b bg-card",children:a.jsx("div",{className:"container mx-auto px-4 py-4",children:a.jsx(mn,{to:"/public/listings",className:"flex items-center gap-2",children:a.jsx("img",{src:Lre,alt:"LevelUp",className:"h-8"})})})}),a.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[a.jsx(La,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),a.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),a.jsx(zt,{asChild:!0,children:a.jsx(mn,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const xr=i.property_address?`${i.property_address} — ${i.city}, ${i.state}`:`${i.city}, ${i.state} Home for Sale`,tr=((Cr=(la=i.agent)==null?void 0:la.brokerage)==null?void 0:Cr.name)||((Fn=i.agent)==null?void 0:Fn.brokerage_name),_n=((As=i.agent)==null?void 0:As.name)||"",lt=fve(i.video_link),At=tr||_n||"",Mt=jz[i.status]==="Sold"?"Just Sold":jz[i.status],dr=Mt?`${Mt}: ${xr}`:xr,ur=[`${kz(i.price)} · ${i.city}, ${i.state}`,_n?`Presented by ${_n}${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,Xt=i.description||"",Pr=Xt.length>420,Rn=Pe||!Pr?Xt:Xt.slice(0,420).trimEnd()+"…",ci=i.page_config||{},ti=hn=>{var xn;return(((xn=ci.sections)==null?void 0:xn[hn])??!0)!==!1},zi=Array.isArray(ci.addons)?ci.addons:[],wa=ci.custom_note||"",xi=ci.accent_color||null;return a.jsxs(a.Fragment,{children:[a.jsxs(Wo,{children:[a.jsx("title",{children:At?`${xr} | ${At}`:xr}),a.jsx("meta",{name:"description",content:`${kz(i.price)} · ${i.bedrooms||""}BD ${i.bathrooms||""}BA ${i.square_footage?i.square_footage.toLocaleString()+" sqft · ":""}${Dre[i.property_type]} in ${i.city}, ${i.state}. ${Xt.slice(0,140)}`}),a.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${i.slug||i.id}`}),a.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),a.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),a.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"}),a.jsx("meta",{property:"og:title",content:dr}),a.jsx("meta",{property:"og:description",content:ur}),a.jsx("meta",{property:"og:type",content:"website"}),a.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${i.slug||i.id}`}),er&&a.jsx("meta",{property:"og:image",content:er.photo_url}),At&&a.jsx("meta",{property:"og:site_name",content:At}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),a.jsx("meta",{name:"twitter:title",content:dr}),a.jsx("meta",{name:"twitter:description",content:ur}),er&&a.jsx("meta",{name:"twitter:image",content:er.photo_url}),a.jsx("meta",{name:"robots",content:"index, follow"}),a.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:Xt,url:`https://listings.relevelup.com/${i.slug||i.id}`,datePosted:i.created_at,image:Nt.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})}),a.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; } `})]}),a.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[a.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:a.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[a.jsxs(mn,{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:[a.jsx(Yy,{className:"h-4 w-4"}),a.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Vt&&a.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,xn])=>a.jsx("a",{href:`#${hn}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:xn},hn))}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(MYe,{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"}),a.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:a.jsx(eC,{className:"h-4 w-4 text-white"})}),a.jsx(zt,{size:"sm",onClick:()=>me(!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"})]})]})}),a.jsxs("section",{ref:_t,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[er?a.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"}):a.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),a.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[a.jsx(us,{className:`${_Ze[i.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:jz[i.status]}),Nt.length>0&&a.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:[a.jsx(fee,{className:"h-3.5 w-3.5"}),Nt.length," photos"]})]}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[a.jsxs("div",{className:"max-w-3xl",children:[i.neighborhood&&a.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&&a.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&&a.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]}),a.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[a.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:kz(i.price)}),a.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),a.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[i.bedrooms&&a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-white",children:i.bedrooms})," bd"]}),i.bathrooms&&a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-white",children:i.bathrooms})," ba"]}),i.square_footage&&a.jsxs("span",{children:[a.jsx("span",{className:"font-semibold text-white",children:G2(i.square_footage)})," sqft"]})]})]})]}),a.jsxs("div",{className:"hidden md:flex flex-col gap-2",children:[i.agent&&a.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?a.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-12 w-12 rounded-full object-cover"}):a.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:a.jsx(vc,{className:"h-6 w-6 text-white"})}),a.jsxs("div",{className:"pr-2 flex-1",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),a.jsx("p",{className:"text-white font-medium leading-tight",children:i.agent.name}),tr&&a.jsx("p",{className:"text-xs text-white/60",children:tr})]}),a.jsx(zt,{size:"sm",onClick:()=>me(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]}),i.co_agent_name&&a.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?a.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):a.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:a.jsx(vc,{className:"h-6 w-6 text-white"})}),a.jsxs("div",{className:"pr-2 flex-1",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Co-Listing Agent"}),a.jsx("p",{className:"text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&a.jsx("p",{className:"text-xs text-white/60",children:i.co_agent_brokerage})]}),(i.co_agent_phone||i.co_agent_email)&&a.jsx(zt,{asChild:!0,size:"sm",className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:a.jsx("a",{href:i.co_agent_phone?`tel:${i.co_agent_phone}`:`mailto:${i.co_agent_email}`,children:"Contact"})})]})]})]}),a.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[a.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),ti("stats")&&a.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:a.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:CS,label:"Bedrooms",value:i.bedrooms},i.bathrooms&&{icon:nv,label:"Bathrooms",value:i.bathrooms},i.square_footage&&{icon:o9,label:"Interior",value:`${G2(i.square_footage)} sqft`},i.lot_size&&{icon:RO,label:"Lot Size",value:i.lot_size},i.year_built&&{icon:yo,label:"Year Built",value:i.year_built},!i.year_built&&i.square_footage&&{icon:Ife,label:"Price / sqft",value:`$${G2(Math.round(i.price/i.square_footage))}`}].filter(Boolean).slice(0,5).map((hn,xn)=>a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:a.jsx(hn.icon,{className:"h-4 w-4 text-white/70"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:hn.label}),a.jsx("p",{className:"font-display text-2xl text-white font-light",children:hn.value})]})]},xn))})}),a.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[a.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[ti("story")&&Xt&&a.jsxs("section",{id:"story",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),a.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:a.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:Rn})}),Pr&&a.jsx("button",{onClick:()=>Ie(!Pe),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:Pe?"Show less":"Read more"}),a.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[a.jsxs(us,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[a.jsx(go,{className:"h-3 w-3 mr-1.5"}),Dre[i.property_type]]}),i.has_hoa&&a.jsx(us,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),i.mls_link&&a.jsx(zt,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:a.jsxs("a",{href:i.mls_link,target:"_blank",rel:"noopener noreferrer",children:[a.jsx(iv,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(wa||i.agent_notes&&i.agent_notes_public)&&a.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(xs,{className:"h-4 w-4 text-amber-300"}),a.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),a.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',wa||i.agent_notes,'"']})]})]}),ti("gallery")&&Nt.length>1&&a.jsxs("section",{id:"gallery",children:[a.jsxs("div",{className:"flex items-end justify-between mb-6",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),a.jsxs("button",{onClick:()=>Ae(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Nt.length]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Nt.slice(0,7).map((hn,xn)=>{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"],ui=xn===6&&Nt.length>7;return a.jsxs("button",{onClick:()=>Ae(xn),className:`${Zr[xn]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[a.jsx("img",{src:hn.photo_url,alt:`Photo ${xn+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),ui&&a.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[a.jsx(fee,{className:"h-6 w-6 mb-1"}),a.jsxs("span",{className:"font-medium",children:["+",Nt.length-7," more"]})]})]},hn.id)})})]}),ti("video")&&!((Sa=i.video)!=null&&Sa.playback_url)&<&&a.jsxs("section",{id:"video",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),a.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:a.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"})})]}),ti("video")&&((_o=i.video)==null?void 0:_o.playback_url)&&a.jsxs("section",{id:"video",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),a.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:a.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"})})]}),ti("map")&&hr&&a.jsxs("section",{id:"map",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),a.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]}),a.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:a.jsx("iframe",{src:hr,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),a.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[a.jsx(qs,{className:"h-4 w-4"}),i.property_address?`${i.property_address}, `:"",i.city,", ",i.state]})]}),ti("payment")&&a.jsxs("section",{id:"payment",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),a.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[a.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[a.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",G2(Math.round(vt))]}),a.jsx("p",{className:"text-white/60",children:"/ month"})]}),a.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),a.jsxs("span",{className:"text-white font-medium",children:[Se,"%"]})]}),a.jsx(UA,{value:[Se],onValueChange:hn=>ve(hn[0]),min:0,max:50,step:1}),a.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",G2(Math.round(i.price*Se/100))," down"]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),a.jsxs("span",{className:"text-white font-medium",children:[We.toFixed(2),"%"]})]}),a.jsx(UA,{value:[We],onValueChange:hn=>rt(hn[0]),min:2,max:10,step:.125})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),a.jsxs("span",{className:"text-white font-medium",children:[at," yr"]})]}),a.jsx(UA,{value:[at],onValueChange:hn=>Et(hn[0]),min:10,max:30,step:5})]})]}),a.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),zi.map(hn=>{const xn=hn.type,Zr=hn.data||{};if(xn==="extra_video"&&Zr.url){const ui=String(Zr.url).includes("youtu")?`https://www.youtube.com/embed/${String(Zr.url).split(/[/=]/).pop()}`:Zr.url;return a.jsxs("section",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Zr.eyebrow||"Featured Video"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Watch"}),a.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:a.jsx("iframe",{src:ui,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Zr.title||"Video"})})]},hn.id)}return xn==="3d_tour"&&Zr.url?a.jsxs("section",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Step inside"}),a.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:a.jsx("iframe",{src:Zr.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},hn.id):xn==="floor_plan"&&Zr.image_url?a.jsxs("section",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),a.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Layout"}),a.jsx("img",{src:Zr.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},hn.id):xn==="testimonial"&&Zr.quote?a.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[a.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',Zr.quote,'"']}),Zr.author&&a.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Zr.author]})]},hn.id):xn==="custom_cta"&&Zr.label?a.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:xi?`${xi}22`:"rgba(255,255,255,0.05)",border:`1px solid ${xi||"rgba(255,255,255,0.1)"}`},children:[Zr.title&&a.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Zr.title}),a.jsx(zt,{asChild:!0,size:"lg",style:xi?{background:xi}:void 0,children:a.jsx("a",{href:Zr.url||"#agent",children:Zr.label})})]},hn.id):null})]}),a.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[a.jsx(lZe,{listingId:i.id}),i.agent&&a.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[a.jsxs("div",{className:"flex items-start gap-4",children:[i.agent.avatar_url?a.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"}):a.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:a.jsx(vc,{className:"h-7 w-7 text-white/70"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),a.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.agent.name}),tr&&a.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:tr})]})]}),a.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.agent.phone&&a.jsx(zt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:a.jsxs("a",{href:`tel:${i.agent.phone}`,children:[a.jsx(ai,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.agent.email&&a.jsx(zt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:a.jsxs("a",{href:`mailto:${i.agent.email}`,children:[a.jsx(Ti,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),i.co_agent_name&&a.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[a.jsxs("div",{className:"flex items-start gap-4",children:[i.co_agent_photo_url?a.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"}):a.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:a.jsx(vc,{className:"h-7 w-7 text-white/70"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),a.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&a.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:i.co_agent_brokerage})]})]}),(i.co_agent_phone||i.co_agent_email)&&a.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.co_agent_phone&&a.jsx(zt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:a.jsxs("a",{href:`tel:${i.co_agent_phone}`,children:[a.jsx(ai,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.co_agent_email&&a.jsx(zt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:a.jsxs("a",{href:`mailto:${i.co_agent_email}`,children:[a.jsx(Ti,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:a.jsx(Mre,{submitted:we,activeTab:re,setActiveTab:se,firstName:p,setFirstName:y,lastName:_,setLastName:T,email:E,setEmail:k,phone:P,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:Z,setShowingMode:Q,isSubmitting:ue,onSubmit:Sr})})]})]}),a.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)&&a.jsx(zt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:a.jsxs("a",{href:`tel:${i.agent.phone}`,children:[a.jsx(ai,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),a.jsxs(zt,{onClick:()=>me(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[a.jsx(r9,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),a.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:a.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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:Lre,alt:"LevelUp",className:"h-6 opacity-80"}),a.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),a.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),a.jsx(io,{open:Me!==null,onOpenChange:()=>Ae(null),children:a.jsxs(Ua,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[a.jsx(ml,{className:"sr-only",children:a.jsx(Ko,{children:"Photo Gallery"})}),a.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:a.jsx(Ds,{className:"h-5 w-5"})}),Me!==null&&Nt[Me]&&a.jsxs("div",{className:"relative",children:[a.jsx("img",{src:Nt[Me].photo_url,alt:`Photo ${Me+1}`,className:"w-full max-h-[85vh] object-contain"}),Nt.length>1&&a.jsxs(a.Fragment,{children:[a.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:a.jsx(xm,{className:"h-6 w-6"})}),a.jsx("button",{onClick:cr,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:a.jsx(vd,{className:"h-6 w-6"})}),a.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:[Me+1," / ",Nt.length]})]})]})]})}),a.jsx(io,{open:be,onOpenChange:me,children:a.jsxs(Ua,{className:"max-w-md p-0 bg-white text-neutral-900",children:[a.jsx(ml,{className:"sr-only",children:a.jsx(Ko,{children:"Contact the agent"})}),a.jsx("div",{className:"p-6",children:a.jsx(Mre,{submitted:we,activeTab:re,setActiveTab:se,firstName:p,setFirstName:y,lastName:_,setLastName:T,email:E,setEmail:k,phone:P,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:Z,setShowingMode:Q,isSubmitting:ue,onSubmit:Sr})})]})})]})]})}function Mre(t){const{submitted:e,activeTab:r,setActiveTab:n,firstName:i,setFirstName:o,lastName:c,setLastName:s,email:f,setEmail:p,phone:y,setPhone:_,message:T,setMessage:E,preferredDate:k,setPreferredDate:P,preferredTime:R,setPreferredTime:D,showingMode:M,setShowingMode:B,isSubmitting:V,onSubmit:G}=t;return e?a.jsxs("div",{className:"text-center py-6",children:[a.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:a.jsx(ko,{className:"h-7 w-7 text-emerald-600"})}),a.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:r==="showing"?"Showing request sent!":"Thanks — you're all set!"}),a.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."})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),a.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),a.jsxs(V7,{value:r,onValueChange:W=>n(W),children:[a.jsxs(N3,{className:"grid w-full grid-cols-2 mb-4",children:[a.jsxs(kp,{value:"info",className:"gap-1.5",children:[a.jsx(of,{className:"h-3.5 w-3.5"})," Get Info"]}),a.jsxs(kp,{value:"showing",className:"gap-1.5",children:[a.jsx(r9,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),a.jsxs("form",{onSubmit:G,className:"space-y-3",children:[a.jsxs(Uy,{value:"showing",className:"mt-0 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"preferredDate",children:"Preferred Date *"}),a.jsx($r,{id:"preferredDate",type:"date",value:k,onChange:W=>P(W.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"preferredTime",children:"Preferred Time"}),a.jsxs(_a,{value:R,onValueChange:D,children:[a.jsx(aa,{id:"preferredTime",children:a.jsx(va,{placeholder:"Any time"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"morning",children:"Morning (9am–12pm)"}),a.jsx(fn,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),a.jsx(fn,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"showingMode",children:"Tour Type"}),a.jsxs(_a,{value:M,onValueChange:W=>B(W),children:[a.jsx(aa,{id:"showingMode",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"in_person",children:"🏡 In-person showing"}),a.jsx(fn,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),a.jsx(fn,{value:"either",children:"Either works for me"})]})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"firstName",children:"First Name *"}),a.jsx($r,{id:"firstName",value:i,onChange:W=>o(W.target.value),required:!0})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lastName",children:"Last Name"}),a.jsx($r,{id:"lastName",value:c,onChange:W=>s(W.target.value)})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"email",children:"Email *"}),a.jsx($r,{id:"email",type:"email",value:f,onChange:W=>p(W.target.value),required:!0})]}),a.jsxs("div",{children:[a.jsxs(Mr,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),a.jsx($r,{id:"phone",type:"tel",value:y,onChange:W=>_(W.target.value),required:r==="showing"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),a.jsx(bd,{id:"message",value:T,onChange:W=>E(W.target.value),rows:2})]}),a.jsx(zt,{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"}),a.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const vZe=Object.freeze(Object.defineProperty({__proto__:null,default:Z7,toVideoEmbedUrl:fve},Symbol.toStringTag,{value:"Module"})),Ore="/assets/levelup-logo-white-C2RAgAoG.png",bZe="/assets/listings-hero-noir-BHCJrhvU.jpg";var mve={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Ql,function(){let r,n,i;function o(s,f){if(!r)r=f;else if(!n)n=f;else{const p={};r(p),i=f(p);const y="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([y],{type:"text/javascript"})))}}o(["exports"],function(s){var f=1e-6,p=typeof Float32Array<"u"?Float32Array:Array;function y(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=u*b-x*m;return S?(h[0]=b*(S=1/S),h[1]=-m*S,h[2]=-x*S,h[3]=u*S,h):null}function _(){var h=new p(9);return p!=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],m=l[1],x=l[2],b=l[3],S=l[4],j=l[5],C=l[6],O=l[7],z=l[8];return h[0]=S*z-j*O,h[1]=x*O-m*z,h[2]=m*j-x*S,h[3]=j*C-b*z,h[4]=u*z-x*C,h[5]=x*b-u*j,h[6]=b*O-S*C,h[7]=m*C-u*O,h[8]=u*S-m*b,h}function E(h,l,u){var m=l[0],x=l[1],b=l[2],S=l[3],j=l[4],C=l[5],O=l[6],z=l[7],U=l[8],q=u[0],K=u[1],X=u[2],J=u[3],ne=u[4],ae=u[5],he=u[6],ce=u[7],ye=u[8];return h[0]=q*m+K*S+X*O,h[1]=q*x+K*j+X*z,h[2]=q*b+K*C+X*U,h[3]=J*m+ne*S+ae*O,h[4]=J*x+ne*j+ae*z,h[5]=J*b+ne*C+ae*U,h[6]=he*m+ce*S+ye*O,h[7]=he*x+ce*j+ye*z,h[8]=he*b+ce*C+ye*U,h}function k(){var h=new p(16);return p!=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 P(h){var l=new p(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],m=l[1],x=l[2],b=l[3],S=l[4],j=l[5],C=l[6],O=l[7],z=l[8],U=l[9],q=l[10],K=l[11],X=l[12],J=l[13],ne=l[14],ae=l[15],he=u*j-m*S,ce=u*C-x*S,ye=u*O-b*S,Ee=m*C-x*j,ke=m*O-b*j,He=x*O-b*C,$e=z*J-U*X,Ge=z*ne-q*X,Ue=z*ae-K*X,Ve=U*ne-q*J,yt=U*ae-K*J,wt=q*ae-K*ne,jt=he*wt-ce*yt+ye*Ve+Ee*Ue-ke*Ge+He*$e;return jt?(h[0]=(j*wt-C*yt+O*Ve)*(jt=1/jt),h[1]=(x*yt-m*wt-b*Ve)*jt,h[2]=(J*He-ne*ke+ae*Ee)*jt,h[3]=(q*ke-U*He-K*Ee)*jt,h[4]=(C*Ue-S*wt-O*Ge)*jt,h[5]=(u*wt-x*Ue+b*Ge)*jt,h[6]=(ne*ye-X*He-ae*ce)*jt,h[7]=(z*He-q*ye+K*ce)*jt,h[8]=(S*yt-j*Ue+O*$e)*jt,h[9]=(m*Ue-u*yt-b*$e)*jt,h[10]=(X*ke-J*ye+ae*he)*jt,h[11]=(U*ye-z*ke-K*he)*jt,h[12]=(j*Ge-S*Ve-C*$e)*jt,h[13]=(u*Ve-m*Ge+x*$e)*jt,h[14]=(J*ce-X*Ee-ne*he)*jt,h[15]=(z*Ee-U*ce+q*he)*jt,h):null}function M(h,l,u){var m=l[0],x=l[1],b=l[2],S=l[3],j=l[4],C=l[5],O=l[6],z=l[7],U=l[8],q=l[9],K=l[10],X=l[11],J=l[12],ne=l[13],ae=l[14],he=l[15],ce=u[0],ye=u[1],Ee=u[2],ke=u[3];return h[0]=ce*m+ye*j+Ee*U+ke*J,h[1]=ce*x+ye*C+Ee*q+ke*ne,h[2]=ce*b+ye*O+Ee*K+ke*ae,h[3]=ce*S+ye*z+Ee*X+ke*he,h[4]=(ce=u[4])*m+(ye=u[5])*j+(Ee=u[6])*U+(ke=u[7])*J,h[5]=ce*x+ye*C+Ee*q+ke*ne,h[6]=ce*b+ye*O+Ee*K+ke*ae,h[7]=ce*S+ye*z+Ee*X+ke*he,h[8]=(ce=u[8])*m+(ye=u[9])*j+(Ee=u[10])*U+(ke=u[11])*J,h[9]=ce*x+ye*C+Ee*q+ke*ne,h[10]=ce*b+ye*O+Ee*K+ke*ae,h[11]=ce*S+ye*z+Ee*X+ke*he,h[12]=(ce=u[12])*m+(ye=u[13])*j+(Ee=u[14])*U+(ke=u[15])*J,h[13]=ce*x+ye*C+Ee*q+ke*ne,h[14]=ce*b+ye*O+Ee*K+ke*ae,h[15]=ce*S+ye*z+Ee*X+ke*he,h}function B(h,l,u){var m,x,b,S,j,C,O,z,U,q,K,X,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]):(x=l[1],b=l[2],S=l[3],j=l[4],C=l[5],O=l[6],z=l[7],U=l[8],q=l[9],K=l[10],X=l[11],h[0]=m=l[0],h[1]=x,h[2]=b,h[3]=S,h[4]=j,h[5]=C,h[6]=O,h[7]=z,h[8]=U,h[9]=q,h[10]=K,h[11]=X,h[12]=m*J+j*ne+U*ae+l[12],h[13]=x*J+C*ne+q*ae+l[13],h[14]=b*J+O*ne+K*ae+l[14],h[15]=S*J+z*ne+X*ae+l[15]),h}function V(h,l,u){var m=u[0],x=u[1],b=u[2];return h[0]=l[0]*m,h[1]=l[1]*m,h[2]=l[2]*m,h[3]=l[3]*m,h[4]=l[4]*x,h[5]=l[5]*x,h[6]=l[6]*x,h[7]=l[7]*x,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 m=Math.sin(u),x=Math.cos(u),b=l[4],S=l[5],j=l[6],C=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*x+O*m,h[5]=S*x+z*m,h[6]=j*x+U*m,h[7]=C*x+q*m,h[8]=O*x-b*m,h[9]=z*x-S*m,h[10]=U*x-j*m,h[11]=q*x-C*m,h}function W(h,l,u){var m=Math.sin(u),x=Math.cos(u),b=l[0],S=l[1],j=l[2],C=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*x-O*m,h[1]=S*x-z*m,h[2]=j*x-U*m,h[3]=C*x-q*m,h[8]=b*m+O*x,h[9]=S*m+z*x,h[10]=j*m+U*x,h[11]=C*m+q*x,h}function Z(h,l,u){var m=Math.sin(u),x=Math.cos(u),b=l[0],S=l[1],j=l[2],C=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*x+O*m,h[1]=S*x+z*m,h[2]=j*x+U*m,h[3]=C*x+q*m,h[4]=O*x-b*m,h[5]=z*x-S*m,h[6]=U*x-j*m,h[7]=q*x-C*m,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 m,x,b,S=u[0],j=u[1],C=u[2],O=Math.sqrt(S*S+j*j+C*C);return O0&&(b=1/Math.sqrt(b)),h[0]=l[0]*b,h[1]=l[1]*b,h[2]=l[2]*b,h}function Nt(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]}function er(h,l,u){var m=l[0],x=l[1],b=l[2],S=u[0],j=u[1],C=u[2];return h[0]=x*C-b*j,h[1]=b*S-m*C,h[2]=m*j-x*S,h}function vt(h,l,u,m){var x=l[0],b=l[1],S=l[2];return h[0]=x+m*(u[0]-x),h[1]=b+m*(u[1]-b),h[2]=S+m*(u[2]-S),h}function or(h,l,u){var m=l[0],x=l[1],b=l[2],S=u[3]*m+u[7]*x+u[11]*b+u[15];return h[0]=(u[0]*m+u[4]*x+u[8]*b+u[12])/(S=S||1),h[1]=(u[1]*m+u[5]*x+u[9]*b+u[13])/S,h[2]=(u[2]*m+u[6]*x+u[10]*b+u[14])/S,h}function Sr(h,l,u){var m=l[0],x=l[1],b=l[2];return h[0]=m*u[0]+x*u[3]+b*u[6],h[1]=m*u[1]+x*u[4]+b*u[7],h[2]=m*u[2]+x*u[5]+b*u[8],h}function nn(h,l,u){var m=u[0],x=u[1],b=u[2],S=u[3],j=l[0],C=l[1],O=l[2],z=x*O-b*C,U=b*j-m*O,q=m*C-x*j;return h[0]=j+S*(z+=z)+x*(q+=q)-b*(U+=U),h[1]=C+S*U+b*z-m*q,h[2]=O+S*q+m*U-x*z,h}function cr(h){return h[0]=0,h[1]=0,h[2]=0,h}function xr(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]}var tr=Pe,_n=Ie,lt=Me;function At(){var h=new p(4);return p!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function Mt(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],m=l[1],x=l[2],b=l[3],S=u*u+m*m+x*x+b*b;return S>0&&(S=1/Math.sqrt(S)),h[0]=u*S,h[1]=m*S,h[2]=x*S,h[3]=b*S,h}function ur(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 m=l[0],x=l[1],b=l[2],S=l[3];return h[0]=u[0]*m+u[4]*x+u[8]*b+u[12]*S,h[1]=u[1]*m+u[5]*x+u[9]*b+u[13]*S,h[2]=u[2]*m+u[6]*x+u[10]*b+u[14]*S,h[3]=u[3]*m+u[7]*x+u[11]*b+u[15]*S,h}function Xt(){var h=new p(4);return p!=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 Rn(h,l,u){u*=.5;var m=l[0],x=l[1],b=l[2],S=l[3],j=Math.sin(u),C=Math.cos(u);return h[0]=m*C+S*j,h[1]=x*C+b*j,h[2]=b*C-x*j,h[3]=S*C-m*j,h}function ci(h,l,u){u*=.5;var m=l[0],x=l[1],b=l[2],S=l[3],j=Math.sin(u),C=Math.cos(u);return h[0]=m*C-b*j,h[1]=x*C+S*j,h[2]=b*C+m*j,h[3]=S*C-x*j,h}we(),At();var ti,zi,wa,xi=dr,la=(ti=we(),zi=Ae(1,0,0),wa=Ae(0,1,0),function(h,l,u){var m=Nt(l,u);return m<-.999999?(er(ti,zi,l),lt(ti)<1e-6&&er(ti,wa,l),pt(ti,ti),function(x,b,S){S*=.5;var j=Math.sin(S);x[0]=j*b[0],x[1]=j*b[1],x[2]=j*b[2],x[3]=Math.cos(S)}(h,ti,Math.PI),h):m>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(er(ti,l,u),h[0]=ti[0],h[1]=ti[1],h[2]=ti[2],h[3]=1+m,xi(h,h))});function Cr(){var h=new p(2);return p!=Float32Array&&(h[0]=0,h[1]=0),h}function Fn(h,l){var u=new p(2);return u[0]=h,u[1]=l,u}function As(h,l,u){return h[0]=l,h[1]=u,h}function Sa(h,l,u){return h[0]=l[0]+u[0],h[1]=l[1]+u[1],h}function _o(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 xn(h,l){var u=l[0],m=l[1],x=u*u+m*m;return x>0&&(x=1/Math.sqrt(x)),h[0]=l[0]*x,h[1]=l[1]*x,h}function Zr(h,l){return h[0]*l[0]+h[1]*l[1]}Xt(),Xt(),_();var ui,Jr,Bn=_o;function ts(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}Cr();var yl=function(){if(Jr)return ui;function h(l,u,m,x){this.cx=3*l,this.bx=3*(m-l)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*u,this.by=3*(x-u)-this.cy,this.ay=1-this.cy-this.by,this.p1x=l,this.p1y=u,this.p2x=m,this.p2y=x}return Jr=1,ui=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 m=l,x=0;x<8;x++){var b=this.sampleCurveX(m)-l;if(Math.abs(b)b?j=m:C=m,m=.5*(C-j)+j;return m},solve:function(l,u){return this.sampleCurveY(this.solveCurveX(l,u))}},ui}(),Zo=ts(yl);function Ot(h,l){this.x=h,this.y=l}function Ro(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,m){const x=new Zo(h,l,u,m);return function(b){return x.solve(b)}}const de=ct(.25,.1,.25,1);function fe(h,l,u){return Math.min(u,Math.max(l,h))}function Oe(h,l,u){return(u=fe((u-h)/(l-h),0,1))*u*(3-2*u)}function Ye(h,l,u){const m=u-l,x=((h-l)%m+m)%m+l;return x===l?u:x}function Je(h,l,u){if(!h.length)return u(null,[]);let m=h.length;const x=new Array(h.length);let b=null;h.forEach((S,j)=>{l(S,(C,O)=>{C&&(b=C),x[j]=O,--m===0&&u(b,x)})})}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 $t(h,l,u){const m={};for(const x in h)m[x]=l.call(this,h[x],x,h);return m}function Pt(h,l,u){const m={};for(const x in h)l.call(this,h[x],x,h)&&(m[x]=h[x]);return m}function mr(h){return Array.isArray(h)?h.map(mr):typeof h=="object"&&h?$t(h,mr):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,m,x=0,b=h.length,S=b-1;x@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(u,m,x,b)=>{const S=x||b;return l[m]=!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 ks,gs=null;function vi(h,l){return[h[4*l],h[4*l+1],h[4*l+2],h[4*l+3]]}function ss(h,l,u,m){for(;l>1;h[x]>1;h[x]<=m?l=x+1:u=x}return l}function Ri(h){return h>0?1/(1.001-h):1+h}function as(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 Mn={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(!Mn.API_URL)return null;try{const h=new URL(Mn.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 Ta(){return new URL(Mn.DRACO_URL,Mn.API_URL).href}function vo(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(ks===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]);ks=WebAssembly.validate(h)}return ks}()?Mn.MESHOPT_SIMD_URL:Mn.MESHOPT_URL,Mn.API_URL).href}function co(){return new URL(Mn.BUILDING_GEN_URL,Mn.API_URL).href}function sc(h){return Mn.API_URL_REGEX.test(h)}function ac(h){return Mn.API_SPRITE_REGEX.test(h)}let wd,xl,oc,Sd,Tc,Td;function ou(){return wd==null&&(wd=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),wd}const Ol={now:()=>Sd!==void 0?Sd:performance.now(),setNow(h){Sd=h},restoreNow(){Sd=void 0},frame(h){const l=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(l)}},getImageData(h,l=0){const{width:u,height:m}=h;Tc||(Tc=document.createElement("canvas"));const x=Tc.getContext("2d",{willReadFrequently:!0});if(!x)throw new Error("failed to create canvas 2d context");return(u>Tc.width||m>Tc.height)&&(Tc.width=u,Tc.height=m),x.clearRect(-l,-l,u+2*l,m+2*l),x.drawImage(h,0,0,u,m),x.getImageData(-l,-l,u+2*l,m+2*l)},resolveURL:h=>(xl||(xl=document.createElement("a")),xl.href=h,xl.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(oc==null&&(oc=window.matchMedia("(prefers-reduced-motion: reduce)")),oc.matches)},hasCanvasFingerprintNoise(){if(Td!==void 0)return Td;if(!ou())return Td=!1,!1;const h=new OffscreenCanvas(85,1),l=h.getContext("2d",{willReadFrequently:!0});let u=0;for(let x=0;x0?`?${b}`:""}`}const jm="mapbox-tiles";let mv=500,pv=50;const gT=["language","worldview","jobid"];let Ed;function VC(){try{return caches}catch{}}function gv(){const h=VC();h&&Ed==null&&(Ed=h.open(jm))}let yT=1/0;const yv={supported:!1,testSupport:function(h){!xT&&rg&&(lu?ng(h):km=h)}};let km,rg,xT=!1,lu=!1;const _T=typeof self<"u"?self:{};function ng(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,rg),h.isContextLost())return;yv.supported=!0}catch{}h.deleteTexture(l),xT=!0}_T.document&&(rg=_T.document.createElement("img"),rg.onload=function(){km&&ng(km),km=null,lu=!0},rg.onerror=function(){xT=!0,km=null},rg.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Lx={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Lx);class vT extends Error{constructor(l,u,m){u===401&&sc(m)&&(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=m}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function bT(h){return typeof h=="object"&&h!==null&&"status"in h&&h.status===404}const Qn=Pi()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,ig=function(h,l){return/^file:/.test(u=h.url)||/^file:/.test(Qn())&&!/^\w+:/.test(u)?function(m,x){const b=new XMLHttpRequest;b.open(m.method||"GET",m.url,!0),m.type==="arrayBuffer"&&(b.responseType="arraybuffer");for(const S in m.headers)b.setRequestHeader(S,m.headers[S]);return m.type==="json"&&(b.responseType="text",b.setRequestHeader("Accept","application/json")),b.withCredentials=m.credentials==="include",b.onerror=()=>{x(new Error(b.statusText))},b.onload=()=>{if((b.status>=200&&b.status<300||b.status===0)&&b.response!==null){let S=b.response;if(m.type==="json")try{S=JSON.parse(b.response)}catch(C){return x(C)}const j=new Headers;b.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(C=>{const O=C.split(": "),z=O.shift(),U=O.join(": ");j.append(z,U)}),x(null,S,j)}else x(new vT(b.statusText,b.status,m.url))},b.send(m.body),{cancel:()=>b.abort()}}(h,l):function(m,x){const b=new AbortController,S=new Request(m.url,{method:m.method||"GET",body:m.body,credentials:m.credentials,headers:m.headers,referrer:Qn(),referrerPolicy:m.referrerPolicy,signal:b.signal});let j=!1,C=!1;const O=(z=S.url).indexOf("sku=")>0&&sc(z);var z;m.type==="json"&&S.headers.set("Accept","application/json");const U=(K,X,J)=>{if(C)return;if(K&&K.message!=="SecurityError"&&Br(K.toString()),X&&J)return q(X);const ne=Date.now();fetch(S).then(ae=>{if(ae.ok){const he=O?ae.clone():null;return q(ae,he,ne)}return x(new vT(ae.statusText,ae.status,m.url))}).catch(ae=>{ae.name!=="AbortError"&&x(new Error(`${ae.message} ${m.url}`))})},q=(K,X,J)=>{(m.type==="arrayBuffer"?K.arrayBuffer():m.type==="json"?K.json():K.text()).then(ne=>{C||(X&&J&&function(ae,he,ce){if(gv(),Ed==null)return;const ye=Ms(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 ke=Ee.headers.get("expires");if(!ke||new Date(ke).getTime()-ce<42e4)return;let He=pT(ae.url,{persistentParams:gT});if(he.status===206){const Ue=ae.headers.get("Range");if(!Ue)return;Ee.status=200,He=Rx(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;gv(),Ed!=null&&Ed.then(Ue=>Ue.put(He,$e)).catch(Ue=>Br(Ue.message))}(S,X,J),j=!0,x(null,ne,K.headers))}).catch(ne=>{C||x(new Error(ne.message))})};return O?function(K,X){if(gv(),Ed==null)return X(null);Ed.then(J=>{let ne=pT(K.url,{persistentParams:gT});const ae=K.headers.get("Range");ae&&(ne=Rx(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),ke=Ms(ye.headers.get("cache-control")||"");return Number(Ee)>Date.now()&&!ke["no-cache"]}(he);J.delete(ne).catch(X),ce&&J.put(ne,he.clone()).catch(X),X(null,he,ce)}).catch(X)}).catch(X)}(S,U):U(null,null),{cancel:()=>{C=!0,j||b.abort()}}}(h,l);var u},sg=function(h,l){return ig(Object.assign(h,{type:"arrayBuffer"}),l)};function XF(h){const l=document.createElement("a");return l.href=h,l.protocol===location.protocol&&l.host===location.host}let xv,ff;xv=[],ff=0;const ag=function(h,l){if(yv.supported&&(h.headers||(h.headers={}),h.headers.accept="image/webp,*/*"),ff>=Mn.MAX_PARALLEL_IMAGE_REQUESTS){const b={requestParameters:h,callback:l,cancelled:!1,cancel(){this.cancelled=!0}};return xv.push(b),b}ff++;let u=!1;const m=()=>{if(!u)for(u=!0,ff--;xv.length&&ff{m(),b?l(b):S&&function(C,O){const z=new Blob([new Uint8Array(C)],{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,(C,O)=>l(C,O,j))});return{cancel:()=>{x.cancel(),m()}}};var Dx,_v,qC,Cm={exports:{}},GC={exports:{}},wT={exports:{}},QF=function(){if(qC)return Cm.exports;qC=1;var h=(Dx||(Dx=1,GC.exports=function(u,m){var x,b,S,j,C,O,z,U;for(b=u.length-(x=3&u.length),S=m,C=3432918353,O=461845907,U=0;U>>16)*C&65535)<<16)&4294967295)<<15|z>>>17))*O+(((z>>>16)*O&65535)<<16)&4294967295)<<13|S>>>19))+((5*(S>>>16)&65535)<<16)&4294967295))+(((j>>>16)+58964&65535)<<16);switch(z=0,x){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)))*C+(((z>>>16)*C&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}),GC.exports),l=(_v||(_v=1,wT.exports=function(u,m){for(var x,b=u.length,S=m^b,j=0;b>=4;)x=1540483477*(65535&(x=255&u.charCodeAt(j)|(255&u.charCodeAt(++j))<<8|(255&u.charCodeAt(++j))<<16|(255&u.charCodeAt(++j))<<24))+((1540483477*(x>>>16)&65535)<<16),S=1540483477*(65535&S)+((1540483477*(S>>>16)&65535)<<16)^(x=1540483477*(65535&(x^=x>>>24))+((1540483477*(x>>>16)&65535)<<16)),b-=4,++j;switch(b){case 3:S^=(255&u.charCodeAt(j+2))<<16;case 2:S^=(255&u.charCodeAt(j+1))<<8;case 1:S=1540483477*(65535&(S^=255&u.charCodeAt(j)))+((1540483477*(S>>>16)&65535)<<16)}return S=1540483477*(65535&(S^=S>>>13))+((1540483477*(S>>>16)&65535)<<16),(S^=S>>>15)>>>0}),wT.exports);return Cm.exports=h,Cm.exports.murmur3=h,Cm.exports.murmur2=l,Cm.exports}(),mf=ts(QF);class Ou{constructor(l,...u){Object.assign(this,u[0]||{}),this.type=l}}class og extends Ou{constructor(l,u={}){super("error",Object.assign({error:l},u))}}function cu(h,l,u){u[h]&&u[h].indexOf(l)!==-1||(u[h]=u[h]||[],u[h].push(l))}function vv(h,l,u){if(u&&u[h]){const m=u[h].indexOf(l);m!==-1&&u[h].splice(m,1)}}class Mx{on(l,u){return this._listeners=this._listeners||{},cu(l,u,this._listeners),this}off(l,u){return vv(l,u,this._listeners),vv(l,u,this._oneTimeListeners),this}once(l,u){return u?(this._oneTimeListeners=this._oneTimeListeners||{},cu(l,u,this._oneTimeListeners),this):new Promise(m=>{this.once(l,m)})}fire(l,u){const m=typeof l=="string"?new Ou(l,u):l,x=m.type;if(this.listens(x)){m.target=this;const b=this._listeners&&this._listeners[x]?this._listeners[x].slice():[];for(const C of b)C.call(this,m);const S=this._oneTimeListeners&&this._oneTimeListeners[x]?this._oneTimeListeners[x].slice():[];for(const C of S)vv(x,C,this._oneTimeListeners),C.call(this,m);const j=this._eventedParent;if(j){const C=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(m,C),j.fire(m)}}else m instanceof og&&console.error(m.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 lc{constructor(l){typeof l=="string"?this.name=l:(this.name=l.name,this.iconsetId=l.iconsetId)}static from(l){return new lc(l)}static toString(l){return l.iconsetId?`${l.name}${l.iconsetId}`:l.name}static parse(l){const[u,m]=l.split("");return new lc({name:u,iconsetId:m})}static isEqual(l,u){return l.name===u.name&&l.iconsetId===u.iconsetId}toString(){return lc.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var ST,bv={},TT=function(){if(ST)return bv;ST=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 m(b){return(S=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:S>1?1:S;var S}function x(b,S,j){return j<0?j+=1:j>1&&(j-=1),6*j<1?b+(S-b)*j*6:2*j<1?S:3*j<2?b+(S-b)*(2/3-j)*6:b}try{bv.parseCSSColor=function(b){var S,j=b.replace(/ /g,"").toLowerCase();if(j in h)return h[j].slice();if(j[0]==="#")return j.length===4?(S=parseInt(j.substr(1),16))>=0&&S<=4095?[(3840&S)>>4|(3840&S)>>8,240&S|(240&S)>>4,15&S|(15&S)<<4,1]:null:j.length===7&&(S=parseInt(j.substr(1),16))>=0&&S<=16777215?[(16711680&S)>>16,(65280&S)>>8,255&S,1]:null;var C=j.indexOf("("),O=j.indexOf(")");if(C!==-1&&O+1===j.length){var z=j.substr(0,C),U=j.substr(C+1,O-(C+1)).split(","),q=1;switch(z){case"rgba":if(U.length!==4)return null;q=m(U.pop());case"rgb":return U.length!==3?null:[u(U[0]),u(U[1]),u(U[2]),q];case"hsla":if(U.length!==4)return null;q=m(U.pop());case"hsl":if(U.length!==3)return null;var K=(parseFloat(U[0])%360+360)%360/360,X=m(U[1]),J=m(U[2]),ne=J<=.5?J*(X+1):J+X-J*X,ae=2*J-ne;return[l(255*x(ae,ne,K+1/3)),l(255*x(ae,ne,K)),l(255*x(ae,ne,K-1/3)),q];default:return null}}return null}}catch{}return bv}();class Zn{constructor(l,u,m,x=1){this.r=l,this.g=u,this.b=m,this.a=x}static parse(l){if(!l)return;if(l instanceof Zn)return l;if(typeof l!="string")return;const u=TT.parseCSSColor(l);return u?new Zn(u[0]/255,u[1]/255,u[2]/255,u[3]):void 0}toString(){const[l,u,m,x]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*l)},${Math.round(255*u)},${Math.round(255*m)},${x})`}toNonPremultipliedRenderColor(l){const{r:u,g:m,b:x,a:b}=this;return new wv(l,u,m,x,b)}toPremultipliedRenderColor(l){const{r:u,g:m,b:x,a:b}=this;return new lg(l,u*b,m*b,x*b,b)}clone(){return new Zn(this.r,this.g,this.b,this.a)}}class ET{constructor(l,u,m,x,b,S=!1){if(this.premultiplied=!1,this.premultiplied=S,l){const j=l.image.height,C=j*j;this.premultiplied?(u=b===0?0:u/b*(j-1),m=b===0?0:m/b*(j-1),x=b===0?0:x/b*(j-1)):(u*=j-1,m*=j-1,x*=j-1),u=Math.max(0,Math.min(j-1,u)),m=Math.max(0,Math.min(j-1,m)),x=Math.max(0,Math.min(j-1,x));const O=Math.floor(u),z=Math.floor(m),U=Math.floor(x),q=Math.ceil(u),K=Math.ceil(m),X=Math.ceil(x),J=u-O,ne=m-z,ae=x-U,he=l.image.data,ce=4*(O+z*C+U*j),ye=4*(O+z*C+X*j),Ee=4*(O+K*C+U*j),ke=4*(O+K*C+X*j),He=4*(q+z*C+U*j),$e=4*(q+z*C+X*j),Ge=4*(q+K*C+U*j),Ue=4*(q+K*C+X*j);this.r=Xr(Xr(Xr(he[ce],he[ye],ae),Xr(he[Ee],he[ke],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[ke+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[ke+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=m,this.b=x,this.a=b}toArray(){const{r:l,g:u,b:m,a:x}=this;return[255*l,255*u,255*m,x]}toHslaArray(){let{r:l,g:u,b:m,a:x}=this;if(this.premultiplied){if(x===0)return[0,0,0,0];const X=1/x;l*=X,u*=X,m*=X}const b=Math.min(Math.max(l,0),1),S=Math.min(Math.max(u,0),1),j=Math.min(Math.max(m,0),1),C=Math.min(b,S,j),O=Math.max(b,S,j),z=O-C,U=.5*(C+O);if(z===0)return[0,0,100*U,x];const q=U>.5?z/(2-O-C):z/(O+C);let K;switch(O){case b:K=60*((S-j)/z+(SXr(m,l[x],u))}Zn.black=new Zn(0,0,0,1),Zn.white=new Zn(1,1,1,1),Zn.transparent=new Zn(0,0,0,0),Zn.red=new Zn(1,0,0,1),Zn.blue=new Zn(0,0,1,1);var Sv=Object.freeze({__proto__:null,array:Fu,color:function(h,l,u){return new Zn(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 uu extends Error{constructor(l,u){super(u),this.message=u,this.key=l}}class Im{constructor(l,u=[]){this.parent=l,this.bindings={};for(const[m,x]of u)this.bindings[m]=x}concat(l){return new Im(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 fh={kind:"null"},Dr={kind:"number"},di={kind:"string"},mi={kind:"boolean"},_l={kind:"color"},pf={kind:"object"},pi={kind:"value"},Nm={kind:"collator"},Ox={kind:"formatted"},Fx={kind:"resolvedImage"};function Xo(h,l){return{kind:"array",itemType:h,N:l}}function ua(h){if(h.kind==="array"){const l=ua(h.itemType);return typeof h.N=="number"?`array<${l}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${l}>`}return h.kind}const JF=[fh,Dr,di,mi,_l,Ox,pf,Xo(pi),Fx];function Bx(h,l){if(l.kind==="error")return null;if(h.kind==="array"){if(l.kind==="array"&&(l.N===0&&l.itemType.kind==="value"||!Bx(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 JF)if(!Bx(u,l))return null}}return`Expected ${ua(h)} but found ${ua(l)} instead.`}function AT(h,l){return l.some(u=>u.kind===h.kind)}function cg(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 mh(h,l){return h.kind==="array"&&l.kind==="array"?h.N===l.N&&mh(h.itemType,l.itemType):h.kind===l.kind}class jT{constructor(l,u,m){this.sensitivity=l?u?"variant":"case":u?"accent":"base",this.locale=m,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 zx{constructor(l,u,m,x,b){this.text=l.normalize?l.normalize():l,this.image=u,this.scale=m,this.fontStack=x,this.textColor=b}}class Lo{constructor(l){this.sections=l}static fromString(l){return new Lo([new zx(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 Lo?l:Lo.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 x=u.image.getPrimary().id.toString();l.push(["image",x]);continue}l.push(u.text);const m={};u.fontStack&&(m["text-font"]=["literal",u.fontStack.split(",")]),u.scale&&(m["font-scale"]=u.scale),u.textColor&&(m["text-color"]=["rgba"].concat(u.textColor.toNonPremultipliedRenderColor(null).toArray())),l.push(m)}return l}}class du{constructor(l,u={}){this.id=lc.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,m,x,b;try{({id:u,params:m,sx:x,sy:b}=JSON.parse(l)||{})}catch{return null}return u?new du(u,{params:m,sx:x,sy:b}):null}scaleSelf(l,u=l){return this.sx*=l,this.sy*=u,this}}class Fl{constructor(l,u,m,x,b=!1){this.primaryId=lc.from(l),this.primaryOptions=u,m&&(this.secondaryId=lc.from(m)),this.secondaryOptions=x,this.available=b}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new du(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new du(this.secondaryId,this.secondaryOptions):null}static from(l){return typeof l=="string"?Fl.build({name:l}):l}static build(l,u,m,x){return!l||typeof l=="object"&&!("name"in l)?null:new Fl(l,m,u,x)}}function HC(h,l,u,m){return typeof h=="number"&&h>=0&&h<=255&&typeof l=="number"&&l>=0&&l<=255&&typeof u=="number"&&u>=0&&u<=255?m===void 0||typeof m=="number"&&m>=0&&m<=1?null:`Invalid rgba value [${[h,l,u,m].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof m=="number"?[h,l,u,m]:[h,l,u]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function ug(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof Zn||h instanceof jT||h instanceof Lo||h instanceof Fl)return!0;if(Array.isArray(h)){for(const l of h)if(!ug(l))return!1;return!0}if(typeof h=="object"){for(const l in h)if(!ug(h[l]))return!1;return!0}return!1}function Cs(h){if(h===null)return fh;if(typeof h=="string")return di;if(typeof h=="boolean")return mi;if(typeof h=="number")return Dr;if(h instanceof Zn)return _l;if(h instanceof jT)return Nm;if(h instanceof Lo)return Ox;if(h instanceof Fl)return Fx;if(Array.isArray(h)){const l=h.length;let u;for(const m of h){const x=Cs(m);if(u){if(u===x)continue;u=pi;break}u=x}return Xo(u||pi,l)}return pf}function Kr(h){const l=typeof h;return h===null?"":l==="string"||l==="number"||l==="boolean"?String(h):h instanceof Lo||h instanceof Fl||h instanceof Zn?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(!ug(l[1]))return u.error("invalid value");const m=l[1];let x=Cs(m);const b=u.expectedType;return x.kind!=="array"||x.N!==0||!b||b.kind!=="array"||typeof b.N=="number"&&b.N!==0||(x=b),new Ir(x,m)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Zn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Lo?this.value.serialize():this.value}}class Qs{constructor(l){this.name="ExpressionEvaluationError",this.message=l}toJSON(){return this.message}}const Qr={string:di,number:Dr,boolean:mi,object:pf};class Ec{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 m,x=1;const b=l[0];if(b==="array"){let j,C;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);j=Qr[O],x++}else j=pi;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);C=l[2],x++}m=Xo(j,C)}else m=Qr[b];const S=[];for(;xl.outputDefined())}serialize(){const l=this.type,u=[l.kind];if(l.kind==="array"){const m=l.itemType;if(m.kind==="string"||m.kind==="number"||m.kind==="boolean"){u.push(m.kind);const x=l.N;(typeof x=="number"||this.args.length>1)&&u.push(x)}}return u.concat(this.args.map(m=>m.serialize()))}}class Pm{constructor(l){this.type=Ox,this.sections=l}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const m=l[1];if(!Array.isArray(m)&&typeof m=="object")return u.error("First argument must be an image or text section.");const x=[];let b=!1;for(let S=1;S<=l.length-1;++S){const j=l[S];if(b&&typeof j=="object"&&!Array.isArray(j)){b=!1;let C=null;if(j["font-scale"]&&(C=u.parseObjectValue(j["font-scale"],S,"font-scale",Dr),!C))return null;let O=null;if(j["text-font"]&&(O=u.parseObjectValue(j["text-font"],S,"text-font",Xo(di)),!O))return null;let z=null;if(j["text-color"]&&(z=u.parseObjectValue(j["text-color"],S,"text-color",_l),!z))return null;const U=x[x.length-1];U.scale=C,U.font=O,U.textColor=z}else{const C=u.parse(l[S],S,pi);if(!C)return null;const O=C.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,x.push({content:C,scale:null,font:null,textColor:null})}}return new Pm(x)}evaluate(l){return new Lo(this.sections.map(u=>{const m=u.content.evaluate(l);return mh(Cs(m),Fx)?new zx("",m,null,null,null):new zx(Kr(m),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 m={};u.scale&&(m["font-scale"]=u.scale.serialize()),u.font&&(m["text-font"]=u.font.serialize()),u.textColor&&(m["text-color"]=u.textColor.serialize()),l.push(m)}return l}}class Gr{constructor(l,u,m,x){this._imageWarnHistory={},this.type=Fx,this.namePrimary=l,this.nameSecondary=u,m&&(this.paramsPrimary=m.params,this.iconsetIdPrimary=m.iconset?m.iconset.id:void 0),x&&(this.paramsSecondary=x.params,this.iconsetIdSecondary=x.iconset?x.iconset.id:void 0)}static parse(l,u){if(l.length<2)return u.error("Expected two or more arguments.");let m=1;const x=[];function b(){if(mlc.isEqual(S,b)),x.available){const S=x.getSecondary()?x.getSecondary().id:null;S&&(x.available=l.availableImages.some(j=>lc.isEqual(j,S)))}}return x}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 m={};if(u&&(m.iconset={id:u}),l){m.params={};for(const x in l)l[x]&&(m.params[x]=l[x].serialize())}return Object.keys(m).length>0?m: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 $x(h){return Ev(h)?"string":Ux(h)?"number":Vx(h)?"boolean":Array.isArray(h)?"array":h===null?"null":Tv(h)?"object":typeof h}function Tv(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function Ev(h){return typeof h=="string"||h instanceof String}function Ux(h){return typeof h=="number"||h instanceof Number}function Vx(h){return typeof h=="boolean"||h instanceof Boolean}const e5={"to-boolean":mi,"to-color":_l,"to-number":Dr,"to-string":di};class Bu{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 m=l[0],x=[];let b=fh;if(m==="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=Xo(u.expectedType.itemType,S)}else{if(!(S>0&&ug(l[1][0])))return null;b=Xo(Cs(l[1][0]),S)}for(let j=0;j4?`Invalid rbga value ${JSON.stringify(u)}: expected an array containing either three or four numeric values.`:HC(u[0],u[1],u[2],u[3]),!m))return new Zn(u[0]/255,u[1]/255,u[2]/255,u[3])}throw new Qs(m||`Could not parse color from value '${typeof u=="string"?u:String(JSON.stringify(u))}'`)}if(this.type.kind==="number"){let u=null;for(const m of this.args){if(u=m.evaluate(l),u===null)return 0;const x=Number(u);if(!isNaN(x))return x}throw new Qs(`Could not convert ${JSON.stringify(u)} to number.`)}return this.type.kind==="formatted"?Lo.fromString(Kr(this.args[0].evaluate(l))):this.type.kind==="resolvedImage"?Fl.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 Pm([{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 Rm=["Unknown","Point","LineString","Polygon"];class qx{constructor(l,u,m){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=m}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Rm[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:m,y:x}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(m*u-l[0])+this.featureDistanceData.bearing[1]*(x*u-l[1])}return 0}parseColor(l){let u=this._parseColorCache[l];return u||(u=this._parseColorCache[l]=Zn.parse(l)),u}getConfig(l){return this.options?this.options.get(l):null}}class Da{constructor(l,u,m,x,b){this.name=l,this.type=u,this._evaluate=m,this.args=x,this._overloadIndex=b}evaluate(l){if(!this._evaluate){const u=Da.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 m=l[0],x=Da.definitions[m];if(!x)return u.error(`Unknown expression "${m}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(x)?x[0]:x.type,S=Array.isArray(x)?[[x[1],x[2]]]:x.overloads,j=[];let C=null,O=-1;for(const[z,U]of S){if(Array.isArray(z)&&z.length!==l.length-1)continue;j.push(z),O++,C=new Rv(u.registry,u.path,null,u.scope,void 0,u._scope,u.options,u.iconImageUseTheme);const q=[];let K=!1;for(let X=1;Xq)).map(gf).join(" | "),U=[];for(let q=1;qu;){if(m-u>600){const C=m-u+1,O=l-u+1,z=Math.log(C),U=.5*Math.exp(2*z/3),q=.5*Math.sqrt(z*U*(C-U)/C)*(O-C/2<0?-1:1);WC(h,l,Math.max(u,Math.floor(l-O*U/C+q)),Math.min(m,Math.floor(l+(C-O)*U/C+q)),x)}const b=h[l];let S=u,j=m;for(Gx(h,u,l),x(h[m],b)>0&&Gx(h,u,m);S0;)j--}x(h[u],b)===0?Gx(h,u,j):(j++,Gx(h,j,m)),j<=l&&(u=j+1),l<=j&&(m=j-1)}}function Gx(h,l,u){const m=h[l];h[l]=h[u],h[u]=m}function jv(h,l){return hl?1:0}function KC(h){let l=0;for(let u,m,x=0,b=h.length,S=b-1;x=l[2]||h[1]<=l[1]||h[3]>=l[3])}function t5(h,l,u){const m=h[0]-l[0],x=h[1]-l[1],b=h[0]-u[0],S=h[1]-u[1];return m*S-b*x===0&&m*b<=0&&x*S<=0}function kT(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 dg(h,l,u=!1){let m=!1;for(let x=0,b=l.length;x0&&j<0||S<0&&j>0}function Wx(h,l,u,m){return(x=[m[0]-u[0],m[1]-u[1]])[0]*(b=[l[0]-h[0],l[1]-h[1]])[1]-x[1]*b[0]!==0&&!(!YC(h,l,u,m)||!YC(u,m,h,l));var x,b}function CT(h){const l=new Ot(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),u=new Ot(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const m of h[0])l.x>m.x&&(l.x=m.x),l.y>m.y&&(l.y=m.y),u.xu[2]){const x=.5*m;let b=h[0]-u[0]>x?-m:u[0]-h[0]>x?m:0;b===0&&(b=h[0]-u[2]>x?-m:u[2]-h[0]>x?m:0),h[0]+=b}zu(l,h)}function PT(h,l,u,m){const x=Math.pow(2,m.z)*yf,b=[m.x*yf,m.y*yf],S=[];if(!h)return S;for(const j of h)for(const C of j){const O=[C.x+b[0],C.y+b[1]];hu(O,l,u,x),S.push(O)}return S}function RT(h,l,u,m){const x=Math.pow(2,m.z)*yf,b=[m.x*yf,m.y*yf],S=[];if(!h)return S;for(const C of h){const O=[];for(const z of C){const U=[z.x+b[0],z.y+b[1]];zu(l,U),O.push(U)}S.push(O)}if(l[2]-l[0]<=x/2){(j=l)[0]=j[1]=1/0,j[2]=j[3]=-1/0;for(const C of S)for(const O of C)hu(O,l,u,x)}var j;return S}class xf{constructor(l,u){this.type=mi,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(ug(l[1])){const m=l[1];if(m.type==="FeatureCollection")for(let x=0;xu)return Cv(b,S,(u-(m-j))/j)}return l[l.length-1]}pointToSegmentDistance(l,u,m){let[x,b]=u,S=Ac(m[0]-x)*this.kx,j=(m[1]-b)*this.ky;if(S!==0||j!==0){const C=(Ac(l[0]-x)*this.kx*S+(l[1]-b)*this.ky*j)/(S*S+j*j);C>1?(x=m[0],b=m[1]):C>0&&(x+=S/this.kx*C,b+=j/this.ky*C)}return S=Ac(l[0]-x)*this.kx,j=(l[1]-b)*this.ky,Math.sqrt(S*S+j*j)}pointOnLine(l,u){let m=1/0,x=l[0][0],b=l[0][1],S=0,j=0;for(let C=0;C1?(O=l[C+1][0],z=l[C+1][1]):K>0&&(O+=U/this.kx*K,z+=q/this.ky*K)),U=Ac(u[0]-O)*this.kx,q=(u[1]-z)*this.ky;const X=U*U+q*q;Xb.index||x.index===b.index&&x.t>b.t){const O=x;x=b,b=O}const S=[x.point],j=x.index+1,C=b.index;!MT(m[j],S[0])&&j<=C&&S.push(m[j]);for(let O=j+1;O<=C;O++)S.push(m[O]);return MT(m[C],b.point)||S.push(b.point),S}lineSliceAlong(l,u,m){let x=0;const b=[];for(let S=0;Sl&&b.length===0&&b.push(Cv(j,C,(l-(x-O))/O)),x>=u)return b.push(Cv(j,C,(u-(x-O))/O)),b;x>l&&b.push(C)}return b}bufferPoint(l,u){const m=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-m,l[0]+x,l[1]+m]}bufferBBox(l,u){const m=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-m,l[2]+x,l[3]+m]}insideBBox(l,u){return Ac(l[0]-u[0])>=0&&Ac(l[0]-u[2])<=0&&l[1]>=u[1]&&l[1]<=u[3]}}function MT(h,l){return h[0]===l[0]&&h[1]===l[1]}function Cv(h,l,u){const m=Ac(l[0]-h[0]);return[h[0]+m*u,h[1]+(l[1]-h[1])*u]}function Ac(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}class Yx{constructor(l=[],u=(m,x)=>mx?1:0){if(this.data=l,this.length=this.data.length,this.compare=u,this.length>0)for(let m=(this.length>>1)-1;m>=0;m--)this._down(m)}push(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:m}=this,x=u[l];for(;l>0;){const b=l-1>>1,S=u[b];if(m(x,S)>=0)break;u[l]=S,l=b}u[l]=x}_down(l){const{data:u,compare:m}=this,x=this.length>>1,b=u[l];for(;l=0)break;u[l]=u[S],l=S}u[l]=b}}var ar=8192;function XC(h,l){return l.dist-h.dist}function QC(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=Dm(h);if(l){if(u===2)return[h,null];const m=Math.floor(u/2);return[[h[0],h[0]+m],[h[0]+m,h[1]]]}{if(u===1)return[h,null];const m=Math.floor(u/2)-1;return[[h[0],h[0]+m],[h[0]+m+1,h[1]]]}}function _f(h,l){const u=[1/0,1/0,-1/0,-1/0];if(!$u(l,h.length))return u;for(let m=l[0];m<=l[1];++m)zu(u,h[m]);return u}function Zx(h){const l=[1/0,1/0,-1/0,-1/0];for(let u=0;ul[2]&&(m=h[0]-l[2]),h[1]>l[3]&&(x=h[1]-l[3]),h[3]=m)return m;if(Hx(x,b)){if(nI(h,l))return 0}else if(nI(l,h))return 0;let S=m;for(const j of h)for(let C=0,O=j.length,z=O-1;C=b)continue;const z=O.range1;if(Dm(z)<=j){if(!$u(z,h.length))return NaN;if(l){const U=os(h,z,u,m);if((b=Math.min(b,U))===0)return b}else for(let U=z[0];U<=z[1];++U){const q=a5(h[U],u,m);if((b=Math.min(b,q))===0)return b}}else{const U=mg(z,l);if(U[0]!==null){const q=pg(_f(h,U[0]),C,m);q=S)continue;const U=z.range1,q=z.range2;if(Dm(U)<=C&&Dm(q)<=O){if(!$u(U,h.length)||!$u(q,u.length))return NaN;if(l&&m?S=Math.min(S,s5(h,U,u,q,x)):l||m?l&&!m?S=Math.min(S,tI(u,q,h,U,x)):!l&&m&&(S=Math.min(S,tI(h,U,u,q,x))):S=Math.min(S,rI(h,U,u,q,x)),S===0)return S}else{const K=mg(U,l),X=mg(q,m);Iv(j,S,x,h,u,K[0],X[0]),Iv(j,S,x,h,u,K[0],X[1]),Iv(j,S,x,h,u,K[1],X[0]),Iv(j,S,x,h,u,K[1],X[1])}}return S}function FT(h,l,u,m,x=1/0){let b=x;const S=_f(h,[0,h.length-1]);for(const j of u)if(!(b!==1/0&&pg(S,_f(j,[0,j.length-1]),m)>=b)&&(b=Math.min(b,iI(h,l,j,!0,m,b)),b===0))return b;return b}function Nv(h,l,u,m,x=1/0){let b=x;const S=_f(h,[0,h.length-1]);for(const j of u){if(b!==1/0&&pg(S,Zx(j),m)>=b)continue;const C=l5(h,l,j,m,b);if(isNaN(C))return C;if((b=Math.min(b,C))===0)return b}return b}function BT(h){return h==="Point"||h==="MultiPoint"||h==="LineString"||h==="MultiLineString"||h==="Polygon"||h==="MultiPolygon"}class Mm{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(ug(l[1])){const m=l[1];if(m.type==="FeatureCollection"){for(let x=0;x{l&&!Om(u)&&(l=!1)}),l}function gg(h){if(h instanceof Da&&h.name==="feature-state")return!1;let l=!0;return h.eachChild(u=>{l&&!gg(u)&&(l=!1)}),l}function Ad(h,l){if(h instanceof Da&&l.indexOf(h.name)>=0)return!1;let u=!0;return h.eachChild(m=>{u&&!Ad(m,l)&&(u=!1)}),u}function sI(h,l,u){return[h,l,u].filter(Boolean).join("")}function zT(h,l){switch(h){case"string":return Kr(l);case"number":return+l;case"boolean":return!!l;case"color":return Zn.parse(l);case"formatted":return Lo.fromString(Kr(l));case"resolvedImage":return Fl.build(Kr(l))}return l}function aI(h,l,u,m){return m!==void 0&&(h=m*Math.round(h/m)),l!==void 0&&hu&&(h=u),h}class yg{constructor(l,u,m,x=!1){this.type=l,this.key=u,this.scope=m,this.featureConstant=x}static parse(l,u){let m=u.expectedType;if(m==null&&(m=pi),l.length<2||l.length>3)return u.error("Invalid number of arguments for 'config' expression.");const x=u.parse(l[1],1);if(!(x instanceof Ir))return u.error("Key name of 'config' expression must be a string literal.");let b,S=!0;const j=Kr(x.value);if(l.length>=3){const C=u.parse(l[2],2);if(!(C instanceof Ir))return u.error("Scope of 'config' expression must be a string literal.");b=Kr(C.value)}if(u.options){const C=sI(j,b,u._scope),O=u.options.get(C);O&&(S=Om(O.value||O.default))}return new yg(m,j,b,S)}evaluate(l){const u=sI(this.key,this.scope,l.scope),m=l.getConfig(u);if(!m)return null;const{type:x,value:b,values:S,minValue:j,maxValue:C,stepValue:O}=m,z=m.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 x&&(U=zT(x,U)),U===void 0||j===void 0&&C===void 0&&O===void 0||(typeof U=="number"?U=aI(U,j,C,O):Array.isArray(U)&&(U=U.map(q=>typeof q=="number"?aI(q,j,C,O):q))),b!==void 0&&U!==void 0&&S&&!S.includes(U)&&(U=z,x&&(U=zT(x,U))),(x&&x!==this.type||U!==void 0&&!mh(Cs(U),this.type))&&(U=zT(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 m=l[1];return u.scope.has(m)?new Pv(m,u.scope.get(m)):u.error(`Unknown variable "${m}". Make sure "${m}" 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 Rv{constructor(l,u=[],m,x=new Im,b=[],S,j,C){this.registry=l,this.path=u,this.key=u.map(O=>typeof O=="string"?`['${O}']`:`[${O}]`).join(""),this.scope=x,this.errors=b,this.expectedType=m,this._scope=S,this.options=j,this.iconImageUseTheme=C}parse(l,u,m,x,b={}){return u||m?this.concat(u,null,m,x)._parse(l,b):this._parse(l,b)}parseObjectValue(l,u,m,x,b,S={}){return this.concat(u,m,x,b)._parse(l,S)}_parse(l,u){function m(x,b,S){return S==="assert"?new Ec(b,[x]):S==="coerce"?new Bu(b,[x]):x}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 x=typeof l[0]=="string"?this.registry[l[0]]:void 0;if(x){let b=x.parse(l,this);if(!b)return null;if(this.expectedType){const S=this.expectedType,j=b.type;if(S.kind!=="string"&&S.kind!=="number"&&S.kind!=="boolean"&&S.kind!=="object"&&S.kind!=="array"||j.kind!=="value")if(S.kind!=="color"&&S.kind!=="formatted"&&S.kind!=="resolvedImage"||j.kind!=="value"&&j.kind!=="string"){if(this.checkSubtype(S,j))return null}else b=m(b,S,u.typeAnnotation||"coerce");else b=m(b,S,u.typeAnnotation||"assert")}if(!(b instanceof Ir)&&b.type.kind!=="resolvedImage"&&$T(b)){const S=new qx(this._scope,this.options,this.iconImageUseTheme);try{b=new Ir(b.type,b.evaluate(S))}catch(j){return this.error(j.message),null}}return b}return Bu.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,m,x){let b=typeof l=="number"?this.path.concat(l):this.path;b=typeof u=="string"?b.concat(u):b;const S=x?this.scope.concat(x):this.scope;return new Rv(this.registry,b,m||null,S,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(l,...u){const m=`${this.key}${u.map(x=>`[${x}]`).join("")}`;this.errors.push(new uu(m,l))}checkSubtype(l,u){const m=Bx(l,u);return m&&this.error(m),m}}function $T(h){if(h instanceof Pv)return $T(h.boundExpression);if(h instanceof Da&&h.name==="error"||h instanceof Av||h instanceof xf||h instanceof Mm||h instanceof yg)return!1;const l=h instanceof Bu||h instanceof Ec;let u=!0;return h.eachChild(m=>{u=l?u&&$T(m):u&&m instanceof Ir}),!!u&&Om(h)&&Ad(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 Lv(h,l){const u=h.length-1;let m,x,b=0,S=u,j=0;for(;b<=S;)if(j=Math.floor((b+S)/2),m=h[j],x=h[j+1],m<=l){if(j===u||ll))throw new Qs("Input is not a number.");S=j-1}return 0}class Xx{constructor(l,u,m){this.type=l,this.input=u,this.labels=[],this.outputs=[];for(const[x,b]of m)this.labels.push(x),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 m=u.parse(l[1],1,Dr);if(!m)return null;const x=[];let b=null;u.expectedType&&u.expectedType.kind!=="value"&&(b=u.expectedType);for(let S=1;S=j)return u.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',O);const U=u.parse(C,z,b);if(!U)return null;b=b||U.type,x.push([j,U])}return new Xx(b,m,x)}evaluate(l){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return m[0].evaluate(l);const b=u.length;return x>=u[b-1]?m[b-1].evaluate(l):m[Lv(u,x)].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 oI=.95047,lI=1.08883,cI=4/29,xg=6/29,uI=3*xg*xg,c5=xg*xg*xg,u5=Math.PI/180,d5=180/Math.PI;function UT(h){return h>c5?Math.pow(h,1/3):h/uI+cI}function VT(h){return h>xg?h*h*h:uI*(h-cI)}function Qx(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function _g(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function qT(h){const l=_g(h.r),u=_g(h.g),m=_g(h.b),x=UT((.4124564*l+.3575761*u+.1804375*m)/oI),b=UT((.2126729*l+.7151522*u+.072175*m)/1);return{l:116*b-16,a:500*(x-b),b:200*(b-UT((.0193339*l+.119192*u+.9503041*m)/lI)),alpha:h.a}}function dI(h){let l=(h.l+16)/116,u=isNaN(h.a)?l:l+h.a/500,m=isNaN(h.b)?l:l-h.b/200;return l=1*VT(l),u=oI*VT(u),m=lI*VT(m),new Zn(Qx(3.2404542*u-1.5371385*l-.4985314*m),Qx(-.969266*u+1.8760108*l+.041556*m),Qx(.0556434*u-.2040259*l+1.0572252*m),h.alpha)}function h5(h,l,u){const m=l-h;return h+u*(m>180||m<-180?m-360*Math.round(m/360):m)}const Jx={forward:qT,reverse:dI,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)}}},vg={forward:function(h){const{l,a:u,b:m}=qT(h),x=Math.atan2(m,u)*d5;return{h:x<0?x+360:x,c:Math.sqrt(u*u+m*m),l,alpha:h.a}},reverse:function(h){const l=h.h*u5,u=h.c;return dI({l:h.l,a:Math.cos(l)*u,b:Math.sin(l)*u,alpha:h.alpha})},interpolate:function(h,l,u){return{h:h5(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 GT=Object.freeze({__proto__:null,hcl:vg,lab:Jx});class Do{constructor(l,u,m,x,b){this.type=l,this.operator=u,this.interpolation=m,this.input=x,this.labels=[],this.outputs=[];for(const[S,j]of b)this.labels.push(S),this.outputs.push(j)}static interpolationFactor(l,u,m,x){let b=0;if(l.name==="exponential")b=Dv(u,l.base,m,x);else if(l.name==="linear")b=Dv(u,1,m,x);else if(l.name==="cubic-bezier"){const S=l.controlPoints;b=new Zo(S[0],S[1],S[2],S[3]).solve(Dv(u,1,m,x))}return b}static parse(l,u){let[m,x,b,...S]=l;if(!Array.isArray(x)||x.length===0)return u.error("Expected an interpolation type expression.",1);if(x[0]==="linear")x={name:"linear"};else if(x[0]==="exponential"){const O=x[1];if(typeof O!="number")return u.error("Exponential interpolation requires a numeric base.",1,1);x={name:"exponential",base:O}}else{if(x[0]!=="cubic-bezier")return u.error(`Unknown interpolation type ${String(x[0])}`,1,0);{const O=x.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);x={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 j=[];let C=null;m==="interpolate-hcl"||m==="interpolate-lab"?C=_l:u.expectedType&&u.expectedType.kind!=="value"&&(C=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 X=u.parse(U,K,C);if(!X)return null;C=C||X.type,j.push([z,X])}return C.kind==="number"||C.kind==="color"||C.kind==="array"&&C.itemType.kind==="number"&&typeof C.N=="number"?new Do(C,m,x,b,j):u.error(`Type ${ua(C)} is not interpolatable.`)}evaluate(l){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return m[0].evaluate(l);const b=u.length;if(x>=u[b-1])return m[b-1].evaluate(l);const S=Lv(u,x),j=Do.interpolationFactor(this.interpolation,x,u[S],u[S+1]),C=m[S].evaluate(l),O=m[S+1].evaluate(l);return this.operator==="interpolate"?Sv[this.type.kind.toLowerCase()](C,O,j):this.operator==="interpolate-hcl"?vg.reverse(vg.interpolate(vg.forward(C),vg.forward(O),j)):Jx.reverse(Jx.interpolate(Jx.forward(C),Jx.forward(O),j))}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 m=0;mBx(x,j.type));return new e0(S?pi:m,b)}evaluate(l){let u,m=null,x=0;for(const b of this.args){if(x++,m=b.evaluate(l),m&&m instanceof Fl&&!m.available&&(u||(u=m),m=null,x===this.args.length))return u;if(m!==null)break}return m}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 Mv{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 m=[];for(let b=1;b=m.length)throw new Qs("Array index out of bounds: index exceeds array size");if(u!==Math.floor(u))throw new Qs("Array index must be an integer. Use at-interpolated for fractional indices");return m[u]}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class r0{constructor(l,u,m){this.type=l,this.index=u,this.input=m}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const m=u.parse(l[1],1,Dr),x=u.parse(l[2],2,Xo(u.expectedType||pi));return m&&x?new r0(x.type.itemType,m,x):null}evaluate(l){const u=this.index.evaluate(l),m=this.input.evaluate(l);if(u<0)throw new Qs(`Array index out of bounds: ${u} < 0.`);if(u>m.length-1)throw new Qs(`Array index out of bounds: ${u} > ${m.length-1}.`);if(u===Math.floor(u))return m[u];const x=Math.floor(u),b=Math.ceil(u),S=m[x],j=m[b];if(typeof S!="number"||typeof j!="number")throw new Qs(`Cannot interpolate between non-number values at index ${u}.`);const C=u-x;return S*(1-C)+j*C}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class n0{constructor(l,u){this.type=mi,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 m=u.parse(l[1],1,pi),x=u.parse(l[2],2,pi);return m&&x?AT(m.type,[mi,di,Dr,fh,pi])?new n0(m,x):(u.error(`Expected first argument to be of type boolean, string, number or null, but found ${ua(m.type)} instead`),null):null}evaluate(l){const u=this.needle.evaluate(l),m=this.haystack.evaluate(l);if(m==null)return!1;if(!cg(u,["boolean","string","number","null"]))throw new Qs(`Expected first argument to be of type boolean, string, number or null, but found ${ua(Cs(u))} instead.`);if(!cg(m,["string","array"]))throw new Qs(`Expected second argument to be of type array or string, but found ${ua(Cs(m))} instead.`);return m.indexOf(u)>=0}eachChild(l){l(this.needle),l(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Ov{constructor(l,u,m){this.type=Dr,this.needle=l,this.haystack=u,this.fromIndex=m}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 m=u.parse(l[1],1,pi),x=u.parse(l[2],2,pi);if(!m||!x)return null;if(!AT(m.type,[mi,di,Dr,fh,pi]))return u.error(`Expected first argument to be of type boolean, string, number or null, but found ${ua(m.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new Ov(m,x,b):null}return new Ov(m,x)}evaluate(l){const u=this.needle.evaluate(l),m=this.haystack.evaluate(l);if(!cg(u,["boolean","string","number","null"]))throw new Qs(`Expected first argument to be of type boolean, string, number or null, but found ${ua(Cs(u))} instead.`);if(!cg(m,["string","array"]))throw new Qs(`Expected second argument to be of type array or string, but found ${ua(Cs(m))} instead.`);if(this.fromIndex){const x=this.fromIndex.evaluate(l);return m.indexOf(u,x)}return m.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 HT{constructor(l,u,m,x,b,S){this.inputType=l,this.type=u,this.input=m,this.cases=x,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 m,x;u.expectedType&&u.expectedType.kind!=="value"&&(x=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 X=="number"&&Math.floor(X)!==X)return q.error("Numeric branch labels must be integer values.");if(m){if(q.checkSubtype(m,Cs(X)))return null}else m=Cs(X);if(b[String(X)]!==void 0)return q.error("Branch labels must be unique.");b[String(X)]=S.length}const K=u.parse(U,O,x);if(!K)return null;x=x||K.type,S.push(K)}const j=u.parse(l[1],1,pi);if(!j)return null;const C=u.parse(l[l.length-1],l.length-1,x);return C?j.type.kind!=="value"&&u.concat(1).checkSubtype(m,j.type)?null:new HT(m,x,j,b,S,C):null}evaluate(l){const u=this.input.evaluate(l);return(mh(Cs(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(),m=[],x={};for(const S of u){const j=x[this.cases[S]];j===void 0?(x[this.cases[S]]=m.length,m.push([this.cases[S],[S]])):m[j][1].push(S)}const b=S=>this.inputType.kind==="number"?Number(S):S;for(const[S,j]of m)l.push(j.length===1?b(j[0]):j.map(b)),l.push(this.outputs[S].serialize());return l.push(this.otherwise.serialize()),l}}class Fv{constructor(l,u,m){this.type=l,this.branches=u,this.otherwise=m}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 m;u.expectedType&&u.expectedType.kind!=="value"&&(m=u.expectedType);const x=[];for(let S=1;Su.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["case"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class i0{constructor(l,u,m,x){this.type=l,this.input=u,this.beginIndex=m,this.endIndex=x}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 m=u.parse(l[1],1,pi),x=u.parse(l[2],2,Dr);if(!m||!x)return null;if(!AT(m.type,[Xo(pi),di,pi]))return u.error(`Expected first argument to be of type array or string, but found ${ua(m.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new i0(m.type,m,x,b):null}return new i0(m.type,m,x)}evaluate(l){const u=this.input.evaluate(l),m=this.beginIndex.evaluate(l);if(!cg(u,["string","array"]))throw new Qs(`Expected first argument to be of type array or string, but found ${ua(Cs(u))} instead.`);if(this.endIndex){const x=this.endIndex.evaluate(l);return u.slice(m,x)}return u.slice(m)}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 WT{constructor(l,u){this.type=Xo(di),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 m=u.parse(l[1],1,di),x=u.parse(l[2],2,di);return m&&x?new WT(m,x):void 0}evaluate(l){const u=this.str.evaluate(l),m=this.delimiter.evaluate(l);return u.split(m)}eachChild(l){l(this.str),l(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function hI(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 fI(h,l,u,m){return m.compare(l,u)===0}function Fm(h,l,u){const m=h!=="=="&&h!=="!=";return class pve{constructor(b,S,j){this.type=mi,this.lhs=b,this.rhs=S,this.collator=j,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 j=b[0];let C=S.parse(b[1],1,pi);if(!C)return null;if(!hI(j,C.type))return S.concat(1).error(`"${j}" comparisons are not supported for type '${ua(C.type)}'.`);let O=S.parse(b[2],2,pi);if(!O)return null;if(!hI(j,O.type))return S.concat(2).error(`"${j}" comparisons are not supported for type '${ua(O.type)}'.`);if(C.type.kind!==O.type.kind&&C.type.kind!=="value"&&O.type.kind!=="value")return S.error(`Cannot compare types '${ua(C.type)}' and '${ua(O.type)}'.`);m&&(C.type.kind==="value"&&O.type.kind!=="value"?C=new Ec(O.type,[C]):C.type.kind!=="value"&&O.type.kind==="value"&&(O=new Ec(C.type,[O])));let z=null;if(b.length===4){if(C.type.kind!=="string"&&O.type.kind!=="string"&&C.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,Nm),!z)return null}return new pve(C,O,z)}evaluate(b){const S=this.lhs.evaluate(b),j=this.rhs.evaluate(b);if(m&&this.hasUntypedArgument){const C=Cs(S),O=Cs(j);if(C.kind!==O.kind||C.kind!=="string"&&C.kind!=="number")throw new Qs(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${C.kind}, ${O.kind}) instead.`)}if(this.collator&&!m&&this.hasUntypedArgument){const C=Cs(S),O=Cs(j);if(C.kind!=="string"||O.kind!=="string")return l(b,S,j)}return this.collator?u(b,S,j,this.collator.evaluate(b)):l(b,S,j)}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 mI=Fm("==",function(h,l,u){return l===u},fI),Bv=Fm("!=",function(h,l,u){return l!==u},function(h,l,u,m){return!fI(0,l,u,m)}),f5=Fm("<",function(h,l,u){return l",function(h,l,u){return l>u},function(h,l,u,m){return m.compare(l,u)>0}),m5=Fm("<=",function(h,l,u){return l<=u},function(h,l,u,m){return m.compare(l,u)<=0}),p5=Fm(">=",function(h,l,u){return l>=u},function(h,l,u,m){return m.compare(l,u)>=0});class zv{constructor(l,u,m,x,b,S){this.type=di,this.number=l,this.locale=u,this.currency=m,this.unit=x,this.minFractionDigits=b,this.maxFractionDigits=S}static parse(l,u){if(l.length!==3)return u.error("Expected two arguments.");const m=u.parse(l[1],1,Dr);if(!m)return null;const x=l[2];if(typeof x!="object"||Array.isArray(x))return u.error("NumberFormat options argument must be an object.");let b=null;if(x.locale&&(b=u.parseObjectValue(x.locale,2,"locale",di),!b))return null;let S=null;if(x.currency&&(S=u.parseObjectValue(x.currency,2,"currency",di),!S))return null;let j=null;if(x.unit&&(j=u.parseObjectValue(x.unit,2,"unit",di),!j))return null;let C=null;if(x["min-fraction-digits"]&&(C=u.parseObjectValue(x["min-fraction-digits"],2,"min-fraction-digits",Dr),!C))return null;let O=null;return x["max-fraction-digits"]&&(O=u.parseObjectValue(x["max-fraction-digits"],2,"max-fraction-digits",Dr),!O)?null:new zv(m,b,S,j,C,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 $v{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 m=u.parse(l[1],1);return m?m.type.kind!=="array"&&m.type.kind!=="string"&&m.type.kind!=="value"?(u.error(`Expected argument of type string or array, but found ${ua(m.type)} instead.`),null):new $v(m):null}evaluate(l){const u=this.input.evaluate(l);if(typeof u=="string"||Array.isArray(u))return u.length;throw new Qs(`Expected value to be of type string or array, but found ${ua(Cs(u))} instead.`)}eachChild(l){l(this.input)}outputDefined(){return!1}serialize(){const l=["length"];return this.eachChild(u=>{l.push(u.serialize())}),l}}function gI(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 bg={"==":mI,"!=":Bv,">":pI,"<":f5,">=":p5,"<=":m5,array:Ec,at:t0,"at-interpolated":r0,boolean:Ec,case:Fv,coalesce:e0,collator:Av,format:Pm,image:Gr,in:n0,"index-of":Ov,interpolate:Do,"interpolate-hcl":Do,"interpolate-lab":Do,length:$v,let:Mv,literal:Ir,match:HT,number:Ec,"number-format":zv,object:Ec,slice:i0,step:Xx,string:Ec,"to-boolean":Bu,"to-color":Bu,"to-number":Bu,"to-string":Bu,var:Pv,within:xf,distance:Mm,config:yg,split:WT};function yI(h,[l,u,m,x]){l=l.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.evaluate(h):1,S=HC(l,u,m,b);if(S)throw new Qs(S);return new Zn(l/255,u/255,m/255,b)}function xI(h,[l,u,m,x]){l=l.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.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,m,b);if(S)throw new Qs(S);const j=`hsla(${l}, ${u}%, ${m}%, ${b})`,C=Zn.parse(j);if(!C)throw new Qs(`Failed to parse HSLA color: ${j}`);return C}function s0(h,l){return h in l}function Uv(h,l){const u=l[h];return u===void 0?null:u}function vf(h){return{type:h}}function Vv(h){if(h instanceof yg)return new Set([h.key]);let l=new Set;return h.eachChild(u=>{l=new Set([...l,...Vv(u)])}),l}function qv(h){if(h instanceof Da&&h.name==="is-active-floor")return!0;let l=!1;return h.eachChild(u=>{!l&&qv(u)&&(l=!0)}),l}function _I(h){return{result:"success",value:h}}function bf(h){return{result:"error",value:h}}function a0(h,l){return!!h&&!!h.parameters&&h.parameters.indexOf(l)>-1}function Gv(h){return h["property-type"]==="data-driven"}function vI(h){return a0(h.expression,"measure-light")}function KT(h){return a0(h.expression,"zoom")}function Hv(h){return!!h.expression&&h.expression.interpolated}function YT(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function bI(h){return h}function wI(h,l){const u=l.type==="color",m=h.stops&&typeof h.stops[0][0]=="object",x=m||!(m||h.property!==void 0),b=h.type||(Hv(l)?"exponential":"interval");if(u&&((h=Object.assign({},h)).stops&&(h.stops=h.stops.map(O=>[O[0],Zn.parse(O[1])])),h.default=Zn.parse(h.default?h.default:l.default)),h.colorSpace&&h.colorSpace!=="rgb"&&!GT[h.colorSpace])throw new Error(`Unknown color space: ${h.colorSpace}`);let S,j,C;if(b==="exponential")S=SI;else if(b==="interval")S=y5;else if(b==="categorical"){S=g5,j=Object.create(null);for(const O of h.stops)j[O[0]]=O[1];C=typeof h.stops[0][0]}else{if(b!=="identity")throw new Error(`Unknown function type "${b}"`);S=TI}if(m){const O={},z=[];for(let K=0;KK[0]),evaluate:({zoom:K},X)=>SI({stops:U,base:h.base},l,K).evaluate(K,X)}}if(x){const O=b==="exponential"?{name:"exponential",base:h.base!==void 0?h.base:1}:null;return{kind:"camera",interpolationType:O,interpolationFactor:Do.interpolationFactor.bind(void 0,O),zoomStops:h.stops.map(z=>z[0]),evaluate:({zoom:z})=>S(h,l,z,j,C)}}return{kind:"source",evaluate(O,z){const U=z&&z.properties?z.properties[h.property]:void 0;return U===void 0?jd(h.default,l.default):S(h,l,U,j,C)}}}function jd(h,l,u){return h!==void 0?h:l!==void 0?l:u!==void 0?u:void 0}function g5(h,l,u,m,x){return jd(typeof u===x?m[u]:void 0,h.default,l.default)}function y5(h,l,u){if(!Ux(u))return jd(h.default,l.default);const m=h.stops.length;if(m===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[m-1][0])return h.stops[m-1][1];const x=Lv(h.stops.map(b=>b[0]),u);return h.stops[x][1]}function SI(h,l,u){const m=h.base!==void 0?h.base:1;if(!Ux(u))return jd(h.default,l.default);const x=h.stops.length;if(x===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[x-1][0])return h.stops[x-1][1];const b=Lv(h.stops.map(z=>z[0]),u),S=function(z,U,q,K){const X=K-q,J=z-q;return X===0?0:U===1?J/X:(Math.pow(U,J)-1)/(Math.pow(U,X)-1)}(u,m,h.stops[b][0],h.stops[b+1][0]),j=h.stops[b][1],C=h.stops[b+1][1];let O=Sv[l.type]||bI;if(h.colorSpace&&h.colorSpace!=="rgb"){const z=GT[h.colorSpace];O=(U,q)=>z.reverse(z.interpolate(z.forward(U),z.forward(q),S))}return typeof j.evaluate=="function"?{evaluate(...z){const U=j.evaluate.apply(void 0,z),q=C.evaluate.apply(void 0,z);if(U!==void 0&&q!==void 0)return O(U,q,S)}}:O(j,C,S)}function TI(h,l,u){return l.type==="color"?u=Zn.parse(u):l.type==="formatted"?u=Lo.fromString(u.toString()):l.type==="resolvedImage"?u=Fl.build(u.toString()):$x(u)===l.type||l.type==="enum"&&l.values[u]||(u=void 0),jd(u,h.default,l.default)}Da.register(bg,{error:[{kind:"error"},[di],(h,[l])=>{throw new Qs(l.evaluate(h))}],typeof:[di,[pi],(h,[l])=>ua(Cs(l.evaluate(h)))],"to-rgba":[Xo(Dr,4),[_l],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Xo(Dr,4),[_l],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[_l,[Dr,Dr,Dr],yI],rgba:[_l,[Dr,Dr,Dr,Dr],yI],hsl:[_l,[Dr,Dr,Dr],xI],hsla:[_l,[Dr,Dr,Dr,Dr],xI],has:{type:mi,overloads:[[[di],(h,[l])=>s0(l.evaluate(h),h.properties())],[[di,pf],(h,[l,u])=>s0(l.evaluate(h),u.evaluate(h))]]},get:{type:pi,overloads:[[[di],(h,[l])=>Uv(l.evaluate(h),h.properties())],[[di,pf],(h,[l,u])=>Uv(l.evaluate(h),u.evaluate(h))]]},"feature-state":[pi,[di],(h,[l])=>Uv(l.evaluate(h),h.featureState||{})],properties:[pf,[],h=>h.properties()],"geometry-type":[di,[],h=>h.geometryType()],worldview:[di,[],h=>h.globals.worldview||""],"is-active-floor":[mi,vf(di),(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(m=>{const x=m.evaluate(h);return u.has(x)})}],id:[pi,[],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,[di],(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:[pi,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Dr,vf(Dr),(h,l)=>{let u=0;for(const m of l)u+=m.evaluate(h);return u}],"*":[Dr,vf(Dr),(h,l)=>{let u=1;for(const m of l)u*=m.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,vf(Dr),(h,l)=>Math.min(...l.map(u=>u.evaluate(h)))],max:[Dr,vf(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-==":[mi,[di,pi],(h,[l,u])=>h.properties()[l.value]===u.value],"filter-id-==":[mi,[pi],(h,[l])=>h.id()===l.value],"filter-type-==":[mi,[di],(h,[l])=>h.geometryType()===l.value],"filter-<":[mi,[di,pi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m{const u=h.id(),m=l.value;return typeof u==typeof m&&u":[mi,[di,pi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m>x}],"filter-id->":[mi,[pi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u>m}],"filter-<=":[mi,[di,pi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m<=x}],"filter-id-<=":[mi,[pi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u<=m}],"filter->=":[mi,[di,pi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m>=x}],"filter-id->=":[mi,[pi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u>=m}],"filter-has":[mi,[pi],(h,[l])=>l.value in h.properties()],"filter-has-id":[mi,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[mi,[Xo(di)],(h,[l])=>l.value.indexOf(h.geometryType())>=0],"filter-id-in":[mi,[Xo(pi)],(h,[l])=>l.value.indexOf(h.id())>=0],"filter-in-small":[mi,[di,Xo(pi)],(h,[l,u])=>u.value.indexOf(h.properties()[l.value])>=0],"filter-in-large":[mi,[di,Xo(pi)],(h,[l,u])=>function(m,x,b,S){for(;b<=S;){const j=b+S>>1;if(x[j]===m)return!0;x[j]>m?S=j-1:b=j+1}return!1}(h.properties()[l.value],u.value,0,u.value.length-1)],all:{type:mi,overloads:[[[mi,mi],(h,[l,u])=>l.evaluate(h)&&u.evaluate(h)],[vf(mi),(h,l)=>{for(const u of l)if(!u.evaluate(h))return!1;return!0}]]},any:{type:mi,overloads:[[[mi,mi],(h,[l,u])=>l.evaluate(h)||u.evaluate(h)],[vf(mi),(h,l)=>{for(const u of l)if(u.evaluate(h))return!0;return!1}]]},"!":[mi,[mi],(h,[l])=>!l.evaluate(h)],"is-supported-script":[mi,[di],(h,[l])=>{const u=h.globals&&h.globals.isSupportedScript;return!u||u(l.evaluate(h))}],upcase:[di,[di],(h,[l])=>l.evaluate(h).toUpperCase()],downcase:[di,[di],(h,[l])=>l.evaluate(h).toLowerCase()],concat:[di,vf(pi),(h,l)=>l.map(u=>Kr(u.evaluate(h))).join("")],"resolved-locale":[di,[Nm],(h,[l])=>l.evaluate(h).resolvedLocale()],random:[Dr,[Dr,Dr,pi],(h,l)=>{const[u,m,x]=l.map(S=>S.evaluate(h));if(u>m||u===m)return u;let b;if(typeof x=="string")b=function(S){let j=0;if(S.length===0)return j;for(let C=0;CJSON.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 o0(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&h[0]in bg}function wf(h,l,u,m,x){const b=new Rv(bg,[],l?function(j){const C={color:_l,string:di,number:Dr,enum:di,boolean:mi,formatted:Ox,resolvedImage:Fx};return j.type==="array"?Xo(C[j.value]||pi,j.length):C[j.type]}(l):void 0,void 0,void 0,u,m,x),S=b.parse(h,void 0,void 0,void 0,l&&l.type==="string"?{typeAnnotation:"coerce"}:void 0);return S?_I(new Wv(S,l,u,m,x)):bf(b.errors)}class wg{constructor(l,u,m,x){this.kind=l,this._styleExpression=u,this.isLightConstant=m,this.isLineProgressConstant=x,this.isStateDependent=l!=="constant"&&!gg(u.expression),this.configDependencies=Vv(u.expression),this.isIndoorDependent=qv(u.expression)}evaluateWithoutErrorHandling(l,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,m,x,b,S)}evaluate(l,u,m,x,b,S,j){return this._styleExpression.evaluate(l,u,m,x,b,S,void 0,void 0,j)}}class Bm{constructor(l,u,m,x,b,S){this.kind=l,this.zoomStops=m,this._styleExpression=u,this.isStateDependent=l!=="camera"&&!gg(u.expression),this.isIndoorDependent=qv(u.expression),this.isLightConstant=b,this.isLineProgressConstant=S,this.configDependencies=Vv(u.expression),this.interpolationType=x}evaluateWithoutErrorHandling(l,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,m,x,b,S)}evaluate(l,u,m,x,b,S){return this._styleExpression.evaluate(l,u,m,x,b,S)}interpolationFactor(l,u,m){return this.interpolationType?Do.interpolationFactor(this.interpolationType,l,u,m):0}}function ZT(h,l,u,m,x){if((h=wf(h,l,u,m,x)).result==="error")return h;const b=h.value.expression,S=Om(b);if(!S&&!Gv(l))return bf([new uu("","data expressions not supported")]);const j=Ad(b,["zoom","pitch","distance-from-center"]);if(!j&&!KT(l))return bf([new uu("","zoom expressions not supported")]);const C=Ad(b,["measure-light"]);if(!C&&!vI(l))return bf([new uu("","measure-light expression not supported")]);const O=Ad(b,["line-progress"]);if(!O&&!function(q){return a0(q.expression,"line-progress")}(l))return bf([new uu("","line-progress expression not supported")]);const z=l.expression&&l.expression.relaxZoomRestriction,U=Uu(b);return U||j||z?U instanceof uu?bf([U]):U instanceof Do&&!Hv(l)?bf([new uu("",'"interpolate" expressions cannot be used with this property')]):_I(U?new Bm(S&&O?"camera":"composite",h.value,U.labels,U instanceof Do?U.interpolation:void 0,C,O):new wg(S&&O?"constant":"source",h.value,C,O)):bf([new uu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Kv{constructor(l,u){this._parameters=l,this._specification=u,Object.assign(this,wI(this._parameters,this._specification))}static deserialize(l){return new Kv(l._parameters,l._specification)}static serialize(l){return{_parameters:l._parameters,_specification:l._specification}}}function Uu(h){let l=null;if(h instanceof Mv)l=Uu(h.result);else if(h instanceof e0){for(const u of h.args)if(l=Uu(u),l)break}else(h instanceof Xx||h instanceof Do)&&h.input instanceof Da&&h.input.name==="zoom"&&(l=h);return l instanceof uu||h.eachChild(u=>{const m=Uu(u);m instanceof uu?l=m:l&&m&&l!==m&&(l=new uu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),l}var XT,EI,l0=function(){if(EI)return XT;EI=1,XT=l;var h=3;function l(u,m,x){var b=this.cells=[];if(u instanceof ArrayBuffer){this.arrayBuffer=u;var S=new Int32Array(this.arrayBuffer);u=S[0],this.d=(m=S[1])+2*(x=S[2]);for(var j=0;j=q[J+0]&&b>=q[J+1])?(C[X]=!0,j.push(U[X])):C[X]=!1}}},l.prototype._forEachCell=function(u,m,x,b,S,j,C,O){for(var z=this._convertToCellCoord(u),U=this._convertToCellCoord(m),q=this._convertToCellCoord(x),K=this._convertToCellCoord(b),X=z;X<=q;X++)for(var J=U;J<=K;J++){var ne=this.d*J+X;if((!O||O(this._convertFromCellCoord(X),this._convertFromCellCoord(J),this._convertFromCellCoord(X+1),this._convertFromCellCoord(J+1)))&&S.call(this,u,m,x,b,ne,j,C,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,m=h+this.cells.length+1+1,x=0,b=0;b=0||(x[b]=gh(h[b],l)));h instanceof Error&&(x.message=h.message)}if(x.$name)throw new Error("$name property is reserved for worker serialization logic.");return m!=="Object"&&(x.$name=m),x}throw new Error("can't serialize object of type "+typeof h)}function Sf(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||c0(h)||h instanceof ImageBitmap||ArrayBuffer.isView(h)||h instanceof ImageData)return h;if(Array.isArray(h))return h.map(Sf);if(typeof h=="object"){const l=h.$name||"Object";if(l==="Map"){const x=h.entries||[],b=new Map;for(let S=0;Sh>=1536&&h<=1791,Yv=h=>h>=1872&&h<=1919,Zv=h=>h>=2208&&h<=2303,Xv=h=>h>=11904&&h<=12031,yh=h=>h>=12032&&h<=12255,QT=h=>h>=12272&&h<=12287,u0=h=>h>=12288&&h<=12351,d0=h=>h>=12352&&h<=12447,$m=h=>h>=12448&&h<=12543,JT=h=>h>=12544&&h<=12591,Qv=h=>h>=12704&&h<=12735,kd=h=>h>=12736&&h<=12783,jI=h=>h>=12784&&h<=12799,kI=h=>h>=12800&&h<=13055,CI=h=>h>=13056&&h<=13311,eE=h=>h>=13312&&h<=19903,Jv=h=>h>=19968&&h<=40959,h0=h=>h>=40960&&h<=42127,tE=h=>h>=42128&&h<=42191,rE=h=>h>=44032&&h<=55215,eb=h=>h>=63744&&h<=64255,nE=h=>h>=64336&&h<=65023,II=h=>h>=65040&&h<=65055,iE=h=>h>=65072&&h<=65103,NI=h=>h>=65104&&h<=65135,sE=h=>h>=65136&&h<=65279,aE=h=>h>=65280&&h<=65519;function oE(h){for(const l of h)if(lE(l.charCodeAt(0)))return!0;return!1}function x5(h){for(const l of h)if(!_5(l.charCodeAt(0)))return!1;return!0}function _5(h){return!(AI(h)||Yv(h)||Zv(h)||nE(h)||sE(h))}function v5(h){return!(h<11904||!(Qv(h)||JT(h)||iE(h)||eb(h)||CI(h)||Xv(h)||kd(h)||u0(h)||eE(h)||Jv(h)||kI(h)||aE(h)||d0(h)||QT(h)||yh(h)||jI(h)||$m(h)||II(h)||tE(h)||h0(h)))}function lE(h){return!(h!==746&&h!==747&&(h<4352||!(Qv(h)||JT(h)||iE(h)&&!(h>=65097&&h<=65103)||eb(h)||CI(h)||Xv(h)||kd(h)||!(!u0(h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||eE(h)||Jv(h)||kI(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)||rE(h)||d0(h)||QT(h)||(l=>l>=12688&&l<=12703)(h)||yh(h)||jI(h)||$m(h)&&h!==12540||!(!aE(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)||II(h)||(l=>l>=19904&&l<=19967)(h)||h0(h)||tE(h))))}function PI(h){return h===12312||h===12313||h===12316||h===12540||h===12448}function Um(h){return!(lE(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)||u0(l)||$m(l)||(u=>u>=57344&&u<=63743)(l)||iE(l)||NI(l)||aE(l)||l===8734||l===8756||l===8757||l>=9984&&l<=10087||l>=10102&&l<=10131||l===65532||l===65533)}(h))}function RI(h){return AI(h)||Yv(h)||Zv(h)||nE(h)||sE(h)}function cE(h){return h>=1424&&h<=2303||nE(h)||sE(h)}function tb(h,l){return!(!l&&cE(h)||h>=2304&&h<=3583||h>=3840&&h<=4255||(u=>u>=6016&&u<=6143)(h))}function b5(h){for(const l of h)if(cE(l.charCodeAt(0)))return!0;return!1}const cc={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Cd=null,Qo=cc.unavailable,jc=null;const LI=function(h){h&&typeof h=="string"&&h.indexOf("NetworkError")>-1&&(Qo=cc.error),Cd&&Cd(h)};function uE(){dE.fire(new Ou("pluginStateChange",{pluginStatus:Qo,pluginURL:jc}))}const dE=new Mx,hE=function(){return Qo},DI=function(){if(Qo!==cc.deferred||!jc)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Qo=cc.loading,uE(),jc&&sg({url:jc},h=>{h?LI(h):(Qo=cc.loaded,uE())})},xh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Qo===cc.loaded||xh.applyArabicShaping!=null,isLoading:()=>Qo===cc.loading,setState(h){Qo=h.pluginStatus,jc=h.pluginURL},isParsing:()=>Qo===cc.parsing,isParsed:()=>Qo===cc.parsed,getPluginURL:()=>jc},MI=function(){xh.isLoading()||xh.isLoaded()||hE()!=="deferred"||DI()};class ri{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,m){for(const x of u)if(!tb(x.charCodeAt(0),m))return!1;return!0}(l,xh.isLoaded())}}class Tg{constructor(l,u,m,x,b){this.property=l,this.value=u,this.expression=function(S,j,C,O,z){if(YT(S))return new Kv(S,j);if(o0(S)||Array.isArray(S)&&S.length>0){const U=ZT(S,j,C,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"&&j.type==="color"&&(U=Zn.parse(S)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>U}}}(u===void 0?l.specification.default:u,l.specification,m,x,b)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(l,u,m,x){return this.property.possiblyEvaluate(this,l,u,m,x)}}class rb{constructor(l,u,m,x){this.property=l,this.value=new Tg(l,void 0,u,m,x)}transitioned(l,u){return new Eg(this.property,this.value,u,Object.assign({},l.transition,this.transition),l.now)}untransitioned(){return new Eg(this.property,this.value,null,{},0)}}class nb{constructor(l,u,m,x){this._properties=l,this._values=Object.create(l.defaultTransitionablePropertyValues),this._scope=u,this._options=m,this._iconImageUseTheme=x,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(l){return mr(this._values[l].value.value)}setValue(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new rb(this._values[l].property,this._scope,this._options,this._iconImageUseTheme)),this._values[l].value=new Tg(this._values[l].property,u===null?void 0:mr(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 m=this._properties.properties;if(l)for(const x in l){const b=l[x];if(x.endsWith("-transition")){const S=x.slice(0,-11);m[S]&&this.setTransition(S,b)}else m.hasOwnProperty(x)&&this.setValue(x,b)}}getTransition(l){return mr(this._values[l].transition)}setTransition(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new rb(this._values[l].property)),this._values[l].transition=mr(u)||void 0}serialize(){const l={};for(const u of Object.keys(this._values)){const m=this.getValue(u);m!==void 0&&(l[u]=m);const x=this.getTransition(u);x!==void 0&&(l[`${u}-transition`]=x)}return l}transitioned(l,u){const m=new fE(this._properties);for(const x of Object.keys(this._values))m._values[x]=this._values[x].transitioned(l,u._values[x]);return m}untransitioned(){const l=new fE(this._properties);for(const u of Object.keys(this._values))l._values[u]=this._values[u].untransitioned();return l}isIndoorDependent(){return this._isIndoorDependent}}class Eg{constructor(l,u,m,x,b){const S=x.delay||0,j=x.duration||0;b=b||0,this.property=l,this.value=u,this.begin=b+S,this.end=this.begin+j,l.specification.transition&&(x.delay||x.duration)&&(this.prior=m)}possiblyEvaluate(l,u,m){const x=l.now||0,b=this.value.possiblyEvaluate(l,u,m),S=this.prior;if(S){if(x>this.end)return this.prior=null,b;if(this.value.isDataDriven())return this.prior=null,b;if(x":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 OI(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function ib(h){if(Array.isArray(h))return h.map(ib);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const l={};for(const u in h)l[u]=ib(h[u]);return l}return OI(h)}function pE(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(!pE(l)&&typeof l!="boolean")return!1;return!0;default:return!0}}function sb(h,l="",u=null,m="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};pE(h)||(h=ab(h));const x=h;let b=!0;try{b=function(z){if(!jg(z))return z;let U=ib(z);return BI(U),U=FI(U),U}(x)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(x,null,2)} `)}let S=null,j=null;if(m!=="background"&&m!=="sky"&&m!=="slot"){j=nt[`filter_${m}`];const z=wf(b,j,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 C=null,O=null;if(b!==x){const z=wf(x,j,l,u);if(z.result==="error")throw new Error(z.value.map(U=>`${U.key}: ${U.message}`).join(", "));C=(U,q,K,X,J)=>z.value.evaluate(U,q,{},K,void 0,void 0,X,J),O=!Om(z.value.expression)}return{filter:S,dynamicFilter:C||void 0,needGeometry:$I(b),needFeature:!!O}}function FI(h){if(!Array.isArray(h))return h;const l=function(u){if(zI.has(u[0])){for(let m=1;mFI(u))}function BI(h){let l=!1;const u=[];if(h[0]==="case"){for(let m=1;m",">=","<","<=","to-boolean"]);function w5(h,l){return hl?1:0}function $I(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let l=1;l"||l==="<="||l===">="?ob(h[1],h[2],l):l==="any"?(u=h.slice(1),["any"].concat(u.map(ab))):l==="all"?["all"].concat(h.slice(1).map(ab)):l==="none"?["all"].concat(h.slice(1).map(ab).map(f0)):l==="in"?gE(h[1],h.slice(2)):l==="!in"?f0(gE(h[1],h.slice(2))):l==="has"?vh(h[1]):l!=="!has"||f0(vh(h[1]));var u}function ob(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 gE(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(w5)]]:["filter-in-small",h,["literal",l]]}}function vh(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function f0(h){return["!",h]}const m0="";function qm(h,l){return l?`${h}${m0}${l}`:h}function UI(h){const l=h.indexOf(m0);return l>=0?h.slice(l+1):""}let VI;const yE=()=>VI||(VI=new rs({"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 xE;const _E=()=>xE||(xE=new rs({"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:_l,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 S5{constructor(l,u,m,x,b,S){this._conditionSpec=l,this._propertiesSpec=m;const j=wf(l,nt.appearance.condition);if(j.result==="success"&&(this.condition=j.value),this.name=u,m){this.layoutProperties=new _h(yE()),this.unevaluatedLayout=new mE(yE(),x,b,S),this.paintProperties=new _h(_E()),this.unevaluatedPaint=new mE(_E(),x,b,"");for(const C in m)C in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(C,m[C]):C in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(C,m[C])}}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,m){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(l,void 0,u,m)),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():{},m=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},x=Object.assign({},u,m);return Object.keys(x).length>0&&(l.properties=x),l}hasIconLayoutProperties(){const l=this.hasLayoutProperty("icon-image"),u=this.hasLayoutProperty("icon-size"),m=this.hasLayoutProperty("icon-offset"),x=this.hasLayoutProperty("icon-rotate");return l||u||m||x}hasTextLayoutProperties(){const l=this.hasLayoutProperty("text-size"),u=this.hasLayoutProperty("text-offset"),m=this.hasLayoutProperty("text-rotate");return l||u||m}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 vE="-transition",T5=new Set(["fill","line","background","hillshade","raster"]);class Jo extends Mx{constructor(l,u,m,x,b,S){if(super(),this.id=l.id,this.fqid=qm(this.id,m),this.type=l.type,this.scope=m,this.lut=x,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 j=wf(this.filter,nt[`filter_${l.type}`]);j.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...j.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||j.value.isIndoorDependent)}if(l.slot&&(this.slot=l.slot),l.appearances&&this.setAppearances(l.appearances),u.layout&&(this._unevaluatedLayout=new mE(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 nb(u.paint,this.scope,b);for(const j in l.paint)this.setPaintProperty(j,l.paint[j]);for(const j in l.layout)this.setLayoutProperty(j,l.layout[j]);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 _h(u.paint)}}}onAdd(l){}onRemove(l){}isDraped(l){return!this.is3D(!0)&&T5.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 m=this._unevaluatedLayout;m._properties.properties[l]&&(m.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...m.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||m.isIndoorDependent(),l==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(l){this.appearances=[],l.forEach(u=>{this.appearances.push(new S5(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(vE)?this._transitionablePaint.getTransition(l.slice(0,-11)):this._transitionablePaint.getValue(l)}isPaintProperty(l){return!!this._transitionablePaint._properties.properties[l]}setPaintProperty(l,u){const m=this._transitionablePaint,x=m._properties.properties;if(l.endsWith(vE)){const U=l.slice(0,-11);return x[U]&&m.setTransition(U,u||void 0),!1}if(!x[l])return!1;const b=m._values[l],S=b.value.isDataDriven(),j=b.value;m.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...m.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||m.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(l);const C=m._values[l].value,O=C.isDataDriven(),z=l.endsWith("pattern")||l==="line-dasharray";return O||S||z||this._handleOverridablePaintPropertyUpdate(l,j,C)}_handleSpecialPaintPropertyUpdate(l){}getProgramIds(){return null}getDefaultProgramParams(l,u,m){return null}_handleOverridablePaintPropertyUpdate(l,u,m){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())),Pt(l,(u,m)=>!(u===void 0||m==="layout"&&!Object.keys(u).length||m==="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 Vm&&Gv(u.property.specification)&&(u.value.kind==="source"||u.value.kind==="composite")&&u.value.isStateDependent)return!0}for(const l of this.appearances)if(!gg(l.condition.expression))return!0;return!1}compileFilter(l){this._filterCompiled||(this._featureFilter=sb(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,m){return{}}queryRadius(l){}queryIntersectsFeature(l,u,m,x,b,S,j,C,O,z){}}const lb={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class p0{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 E5=new ArrayBuffer(0);class Vi{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=E5),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,m=0;return{members:h.map(x=>{const b=lb[x.type].BYTES_PER_ELEMENT,S=u=qI(u,Math.max(l,b)),j=x.components||1;return m=Math.max(m,b),u+=b*j,{name:x.name,type:x.type,components:j,offset:S}}),size:qI(u,Math.max(m,l)),alignment:l}}function qI(h,l){return Math.ceil(h/l)*l}class uc extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.int16[x+0]=u,this.int16[x+1]=m,l}}uc.prototype.bytesPerElement=4,br(uc,"StructArrayLayout2i4");class Id extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,l}}Id.prototype.bytesPerElement=6,br(Id,"StructArrayLayout3i6");class bo extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,l}}bo.prototype.bytesPerElement=8,br(bo,"StructArrayLayout2i2ui8");class kc extends Vi{_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}}kc.prototype.bytesPerElement=4,br(kc,"StructArrayLayout1f4");class bE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=4*l,S=2*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.float32[S+1]=x,l}}bE.prototype.bytesPerElement=8,br(bE,"StructArrayLayout2i1f8");class wE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=4*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,l}}wE.prototype.bytesPerElement=8,br(wE,"StructArrayLayout3i8");class SE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=m,this.int16[S+2]=x,this.int16[S+3]=b,l}}SE.prototype.bytesPerElement=8,br(SE,"StructArrayLayout4i8");class TE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const j=5*l;return this.int16[j+0]=u,this.int16[j+1]=m,this.int16[j+2]=x,this.int16[j+3]=b,this.int16[j+4]=S,l}}TE.prototype.bytesPerElement=10,br(TE,"StructArrayLayout5i10");class g0 extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j){const C=this.length;return this.resize(C+1),this.emplace(C,l,u,m,x,b,S,j)}emplace(l,u,m,x,b,S,j,C){const O=6*l,z=12*l,U=3*l;return this.int16[O+0]=u,this.int16[O+1]=m,this.uint8[z+4]=x,this.uint8[z+5]=b,this.uint8[z+6]=S,this.uint8[z+7]=j,this.float32[U+2]=C,l}}g0.prototype.bytesPerElement=12,br(g0,"StructArrayLayout2i4ub1f12");class fu extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.float32[b+0]=u,this.float32[b+1]=m,this.float32[b+2]=x,l}}fu.prototype.bytesPerElement=12,br(fu,"StructArrayLayout3f12");class Nd extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const j=6*l,C=3*l;return this.uint16[j+0]=u,this.uint16[j+1]=m,this.uint16[j+2]=x,this.uint16[j+3]=b,this.float32[C+2]=S,l}}Nd.prototype.bytesPerElement=12,br(Nd,"StructArrayLayout4ui1f12");class kg extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.uint16[S+0]=u,this.uint16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,l}}kg.prototype.bytesPerElement=8,br(kg,"StructArrayLayout4ui8");class cb extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,j){const C=6*l;return this.int16[C+0]=u,this.int16[C+1]=m,this.int16[C+2]=x,this.int16[C+3]=b,this.int16[C+4]=S,this.int16[C+5]=j,l}}cb.prototype.bytesPerElement=12,br(cb,"StructArrayLayout6i12");class EE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j,C,O,z,U,q){const K=this.length;return this.resize(K+1),this.emplace(K,l,u,m,x,b,S,j,C,O,z,U,q)}emplace(l,u,m,x,b,S,j,C,O,z,U,q,K){const X=12*l;return this.int16[X+0]=u,this.int16[X+1]=m,this.int16[X+2]=x,this.int16[X+3]=b,this.uint16[X+4]=S,this.uint16[X+5]=j,this.uint16[X+6]=C,this.uint16[X+7]=O,this.int16[X+8]=z,this.int16[X+9]=U,this.int16[X+10]=q,this.int16[X+11]=K,l}}EE.prototype.bytesPerElement=24,br(EE,"StructArrayLayout4i4ui4i24");class AE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,j){const C=10*l,O=5*l;return this.int16[C+0]=u,this.int16[C+1]=m,this.int16[C+2]=x,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=j,l}}AE.prototype.bytesPerElement=20,br(AE,"StructArrayLayout3i3f20");class bh extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.float32[S+0]=u,this.float32[S+1]=m,this.float32[S+2]=x,this.float32[S+3]=b,l}}bh.prototype.bytesPerElement=16,br(bh,"StructArrayLayout4f16");class y0 extends Vi{_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}}y0.prototype.bytesPerElement=4,br(y0,"StructArrayLayout1ul4");class mu extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.uint16[x+0]=u,this.uint16[x+1]=m,l}}mu.prototype.bytesPerElement=4,br(mu,"StructArrayLayout2ui4");class ub extends Vi{_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,m,x,b,S,j,C,O,z,U,q,K){const X=this.length;return this.resize(X+1),this.emplace(X,l,u,m,x,b,S,j,C,O,z,U,q,K)}emplace(l,u,m,x,b,S,j,C,O,z,U,q,K,X){const J=20*l,ne=10*l;return this.int16[J+0]=u,this.int16[J+1]=m,this.int16[J+2]=x,this.int16[J+3]=b,this.int16[J+4]=S,this.float32[ne+3]=j,this.float32[ne+4]=C,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]=X,l}}ub.prototype.bytesPerElement=40,br(ub,"StructArrayLayout5i4f1i1ul2ui40");class x0 extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j){const C=this.length;return this.resize(C+1),this.emplace(C,l,u,m,x,b,S,j)}emplace(l,u,m,x,b,S,j,C){const O=8*l;return this.int16[O+0]=u,this.int16[O+1]=m,this.int16[O+2]=x,this.int16[O+4]=b,this.int16[O+5]=S,this.int16[O+6]=j,this.int16[O+7]=C,l}}x0.prototype.bytesPerElement=16,br(x0,"StructArrayLayout3i2i2i16");class jE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const j=4*l,C=8*l;return this.float32[j+0]=u,this.float32[j+1]=m,this.float32[j+2]=x,this.int16[C+6]=b,this.int16[C+7]=S,l}}jE.prototype.bytesPerElement=16,br(jE,"StructArrayLayout2f1f2i16");class _0 extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,j){const C=20*l,O=5*l;return this.uint8[C+0]=u,this.uint8[C+1]=m,this.float32[O+1]=x,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=j,l}}_0.prototype.bytesPerElement=20,br(_0,"StructArrayLayout2ub4f20");class vs extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.uint16[b+0]=u,this.uint16[b+1]=m,this.uint16[b+2]=x,l}}vs.prototype.bytesPerElement=6,br(vs,"StructArrayLayout3ui6");class db extends Vi{_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,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee){const ke=this.length;return this.resize(ke+1),this.emplace(ke,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee)}emplace(l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee,ke){const He=30*l,$e=15*l,Ge=60*l;return this.int16[He+0]=u,this.int16[He+1]=m,this.int16[He+2]=x,this.float32[$e+2]=b,this.float32[$e+3]=S,this.uint16[He+8]=j,this.uint16[He+9]=C,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]=X,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]=ke,l}}db.prototype.bytesPerElement=60,br(db,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class kE extends Vi{_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,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee,ke,He,$e,Ge,Ue,Ve,yt,wt,jt,It,kt,Bt){const mt=this.length;return this.resize(mt+1),this.emplace(mt,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee,ke,He,$e,Ge,Ue,Ve,yt,wt,jt,It,kt,Bt)}emplace(l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee,ke,He,$e,Ge,Ue,Ve,yt,wt,jt,It,kt,Bt,mt){const Ct=20*l,Lt=40*l,Ut=80*l;return this.float32[Ct+0]=u,this.float32[Ct+1]=m,this.int16[Lt+4]=x,this.int16[Lt+5]=b,this.int16[Lt+6]=S,this.int16[Lt+7]=j,this.int16[Lt+8]=C,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]=X,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]=ke,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[Ct+14]=yt,this.float32[Ct+15]=wt,this.float32[Ct+16]=jt,this.float32[Ct+17]=It,this.float32[Ct+18]=kt,this.uint8[Ut+76]=Bt,this.uint16[Lt+39]=mt,l}}kE.prototype.bytesPerElement=80,br(kE,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class hb extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,j){const C=6*l;return this.float32[C+0]=u,this.float32[C+1]=m,this.float32[C+2]=x,this.float32[C+3]=b,this.float32[C+4]=S,this.float32[C+5]=j,l}}hb.prototype.bytesPerElement=24,br(hb,"StructArrayLayout6f24");class Gm extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const j=5*l;return this.float32[j+0]=u,this.float32[j+1]=m,this.float32[j+2]=x,this.float32[j+3]=b,this.float32[j+4]=S,l}}Gm.prototype.bytesPerElement=20,br(Gm,"StructArrayLayout5f20");class v0 extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j){const C=this.length;return this.resize(C+1),this.emplace(C,l,u,m,x,b,S,j)}emplace(l,u,m,x,b,S,j,C){const O=7*l;return this.float32[O+0]=u,this.float32[O+1]=m,this.float32[O+2]=x,this.float32[O+3]=b,this.float32[O+4]=S,this.float32[O+5]=j,this.float32[O+6]=C,l}}v0.prototype.bytesPerElement=28,br(v0,"StructArrayLayout7f28");class CE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j,C,O,z,U){const q=this.length;return this.resize(q+1),this.emplace(q,l,u,m,x,b,S,j,C,O,z,U)}emplace(l,u,m,x,b,S,j,C,O,z,U,q){const K=11*l;return this.float32[K+0]=u,this.float32[K+1]=m,this.float32[K+2]=x,this.float32[K+3]=b,this.float32[K+4]=S,this.float32[K+5]=j,this.float32[K+6]=C,this.float32[K+7]=O,this.float32[K+8]=z,this.float32[K+9]=U,this.float32[K+10]=q,l}}CE.prototype.bytesPerElement=44,br(CE,"StructArrayLayout11f44");class IE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j,C,O){const z=this.length;return this.resize(z+1),this.emplace(z,l,u,m,x,b,S,j,C,O)}emplace(l,u,m,x,b,S,j,C,O,z){const U=9*l;return this.float32[U+0]=u,this.float32[U+1]=m,this.float32[U+2]=x,this.float32[U+3]=b,this.float32[U+4]=S,this.float32[U+5]=j,this.float32[U+6]=C,this.float32[U+7]=O,this.float32[U+8]=z,l}}IE.prototype.bytesPerElement=36,br(IE,"StructArrayLayout9f36");class Hm extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.float32[x+0]=u,this.float32[x+1]=m,l}}Hm.prototype.bytesPerElement=8,br(Hm,"StructArrayLayout2f8");class NE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=6*l;return this.uint32[3*l+0]=u,this.uint16[S+2]=m,this.uint16[S+3]=x,this.uint16[S+4]=b,l}}NE.prototype.bytesPerElement=12,br(NE,"StructArrayLayout1ul3ui12");class Wm extends Vi{_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}}Wm.prototype.bytesPerElement=2,br(Wm,"StructArrayLayout1ui2");class PE extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne){const ae=this.length;return this.resize(ae+1),this.emplace(ae,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne)}emplace(l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae){const he=16*l;return this.float32[he+0]=u,this.float32[he+1]=m,this.float32[he+2]=x,this.float32[he+3]=b,this.float32[he+4]=S,this.float32[he+5]=j,this.float32[he+6]=C,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]=X,this.float32[he+13]=J,this.float32[he+14]=ne,this.float32[he+15]=ae,l}}PE.prototype.bytesPerElement=64,br(PE,"StructArrayLayout16f64");class fb extends Vi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,j){const C=this.length;return this.resize(C+1),this.emplace(C,l,u,m,x,b,S,j)}emplace(l,u,m,x,b,S,j,C){const O=10*l,z=5*l;return this.uint16[O+0]=u,this.uint16[O+1]=m,this.uint16[O+2]=x,this.uint16[O+3]=b,this.float32[z+2]=S,this.float32[z+3]=j,this.float32[z+4]=C,l}}fb.prototype.bytesPerElement=20,br(fb,"StructArrayLayout4ui3f20");class mb extends Vi{_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}}mb.prototype.bytesPerElement=2,br(mb,"StructArrayLayout1i2");class pb extends Vi{_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}}pb.prototype.bytesPerElement=1,br(pb,"StructArrayLayout1ub1");class GI extends p0{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]}}GI.prototype.size=40;class RE extends ub{get(l){return new GI(this,l)}}br(RE,"CollisionBoxArray");class HI extends p0{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}}HI.prototype.size=60;class WI extends db{get(l){return new HI(this,l)}}br(WI,"PlacedSymbolArray");class b0 extends p0{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]}}b0.prototype.size=80;class KI extends kE{get(l){return new b0(this,l)}}br(KI,"SymbolInstanceArray");class YI extends kc{getoffsetX(l){return this.float32[1*l+0]}}br(YI,"GlyphOffsetArray");class w0 extends uc{getx(l){return this.int16[2*l+0]}gety(l){return this.int16[2*l+1]}}br(w0,"SymbolLineVertexArray");class ZI extends p0{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]}}ZI.prototype.size=12;class LE extends NE{get(l){return new ZI(this,l)}}br(LE,"FeatureIndexArray");class XI extends mu{geta_centroid_pos0(l){return this.uint16[2*l+0]}geta_centroid_pos1(l){return this.uint16[2*l+1]}}br(XI,"FillExtrusionCentroidArray");class DE extends p0{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]}}DE.prototype.size=6;class ME extends Id{get(l){return new DE(this,l)}}br(ME,"FillExtrusionWallArray");const QI=Pn([{name:"a_pos",components:2,type:"Int16"}],4),A5=Pn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),j5=Pn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class ji{constructor(l=[]){this.segments=l}_prepareSegment(l,u,m,x,b){let S=this.segments[this.segments.length-1];return l>ji.MAX_VERTEX_ARRAY_LENGTH&&Br(`Max vertices per segment is ${ji.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${l}`),(!S||S.vertexLength+l>ji.MAX_VERTEX_ARRAY_LENGTH||S.sortKey!==x||b!==void 0&&S&&S.batchIndex!==void 0&&S.batchIndex!==b)&&(S={vertexOffset:u,primitiveOffset:m,vertexLength:0,primitiveLength:0},x!==void 0&&(S.sortKey=x),b!==void 0&&(S.batchIndex=b),this.segments.push(S)),S}prepareSegment(l,u,m,x,b){return this._prepareSegment(l,u.length,m.length,x,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,m,x){return new ji([{vertexOffset:l,primitiveOffset:u,vertexLength:m,primitiveLength:x,vaos:{},sortKey:0}])}}function gb(h,l){return 256*(h=fe(Math.floor(h),0,255))+fe(Math.floor(l),0,255)}ji.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,br(ji,"SegmentVector");const k5=Pn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),C5=Pn([{name:"a_pattern_b",components:4,type:"Uint16"}]),I5=Pn([{name:"a_dash",components:4,type:"Uint16"}]);class S0{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(l,u,m,x){this.ids.push(OE(l)),this.positions.push(u,m,x)}eachPosition(l,u){const m=OE(l);let x=0,b=this.ids.length-1;for(;x>1;this.ids[S]>=m?b=S:x=S+1}for(;this.ids[x]===m;)u(this.positions[3*x],this.positions[3*x+1],this.positions[3*x+2]),x++}static serialize(l,u){const m=new Float64Array(l.ids),x=new Uint32Array(l.positions);return T0(m,x,0,m.length-1),u&&(u.add(m.buffer),u.add(x.buffer)),{ids:m,positions:x}}static deserialize(l){const u=new S0;let m;u.ids=l.ids,u.positions=l.positions;for(const x of u.ids)x!==m&&u.uniqueIds.push(x),m=x;return u.indexed=!0,u}}function OE(h){const l=+h;return Number.isSafeInteger(l)?l:mf(String(h))}function T0(h,l,u,m){for(;u>1];let b=u-1,S=m+1;for(;;){do b++;while(h[b]x);if(b>=S)break;Cc(h,b,S),Cc(l,3*b,3*S),Cc(l,3*b+1,3*S+1),Cc(l,3*b+2,3*S+2)}S-u`u_${b}`),this.type=m,this.context=x}setUniform(l,u,m,x,b){const S=x.constantOr(this.value);u.set(l,b,S instanceof Zn?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 P5(l):new da(l)}}class ${constructor(l,u){this.uniformNames=u.map(m=>`u_${m}`),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,m,x,b){let S=null;b!=="u_pattern"&&b!=="u_dash"||(S=this.pattern),b==="u_pattern_b"&&(S=this.patternTransition),b==="u_pixel_ratio"&&(S=this.pixelRatio),S&&u.set(l,b,S)}getBinding(l,u){return u==="u_pattern"||u==="u_pattern_b"||u==="u_dash"?new N5(l):new da(l)}}class H{constructor(l,u,m,x){this.expression=l,this.type=m,this.maxValue=0,this.paintVertexAttributes=u.map(b=>({name:`a_${b}`,type:"Float32",components:m==="color"?2:1,offset:0})),this.paintVertexArray=new x}populatePaintArray(l,u,m,x,b,S,j,C){const O=this.paintVertexArray.length,z=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new ri(0,{brightness:S,worldview:C}),u,{},b,x,j):this.expression.kind==="constant"&&this.expression.value,U=L(this.lutExpression,u,{},x,b,S,j,C);this.paintVertexArray.resize(l),this._setPaintValue(O,l,z,U?null:this.context.lut)}updatePaintArray(l,u,m,x,b,S,j,C){const O=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:j,worldview:C},m,x,void 0,b):this.expression.kind==="constant"&&this.expression.value,z=L(this.lutExpression,m,x,b,void 0,j,void 0,C);this._setPaintValue(l,u,O,z?null:this.context.lut)}_setPaintValue(l,u,m,x){if(this.type==="color"){const b=N(m.toPremultipliedRenderColor(x));for(let S=l;S`u_${j}_t`),this.type=m,this.useIntegerZoom=x,this.context=b,this.maxValue=0,this.paintVertexAttributes=u.map(j=>({name:`a_${j}`,type:"Float32",components:m==="color"?4:2,offset:0})),this.paintVertexArray=new S}populatePaintArray(l,u,m,x,b,S,j,C){const O=this.expression.evaluate(new ri(this.context.zoom,{brightness:S,worldview:C}),u,{},b,x,j),z=this.expression.evaluate(new ri(this.context.zoom+1,{brightness:S,worldview:C}),u,{},b,x,j),U=L(this.lutExpression,u,{},x,b,S,j,C),q=this.paintVertexArray.length;this.paintVertexArray.resize(l),this._setPaintValue(q,l,O,z,U?null:this.context.lut)}updatePaintArray(l,u,m,x,b,S,j,C){const O=this.expression.evaluate({zoom:this.context.zoom,brightness:j,worldview:C},m,x,void 0,b),z=this.expression.evaluate({zoom:this.context.zoom+1,brightness:j,worldview:C},m,x,void 0,b),U=L(this.lutExpression,m,x,b,void 0,j,void 0,C);this._setPaintValue(l,u,O,z,U?null:this.context.lut)}_setPaintValue(l,u,m,x,b){if(this.type==="color"){const S=N(m.toPremultipliedRenderColor(b)),j=N(x.toPremultipliedRenderColor(b));for(let C=l;C!0){this.binders={},this._buffers=[],this.context=u;const x=[],b=l;for(const S in l.paint._values){const j=b.paint.get(S);if(S.endsWith("-use-theme")||!m(S)||!(j instanceof Vm&&Gv(j.property.specification)))continue;const C=oe(S,l.type),O=j.value,z=j.property.specification.type,U=!!j.property.useIntegerZoom,q=S==="line-dasharray"||S.endsWith("pattern"),K=b.paint.get(`${S}-use-theme`),X=S==="line-dasharray"&&b.layout.get("line-cap").value.kind!=="constant"||K&&K.value.kind!=="constant";if(O.kind!=="constant"||X)if(O.kind==="source"||X||q){const J=Ne(S,z,"source");this.binders[S]=q?new te(O,C,z,J,l.id):new H(O,C,z,J),x.push(`/a_${S}`)}else{const J=Ne(S,z,"composite");this.binders[S]=new Y(O,C,z,U,u,J),x.push(`/z_${S}`)}else this.binders[S]=q?new $(O.value,C):new F(O.value,C,z,u),x.push(`/u_${S}`);K&&(this.binders[S].lutExpression=K.value)}this.cacheKey=x.sort().join("")}getMaxValue(l){const u=this.binders[l];return u instanceof H||u instanceof Y?u.maxValue:0}populatePaintArrays(l,u,m,x,b,S,j,C){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,m,x,b,S,j,C)}}setConstantPatternPositions(l,u){for(const m in this.binders){const x=this.binders[m];x instanceof $&&x.setConstantPatternPositions(l,u)}}getPatternTransitionVertexBuffer(l){const u=this.binders[l];return u instanceof te?u.paintTransitionVertexBuffer:null}updatePaintArrays(l,u,m,x,b,S,j,C,O,z){let U=!1;const q=Object.keys(l),K=q.length!==0&&!C,X=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 X){const ce=l[he.toString()];u.eachPosition(he,(ye,Ee,ke)=>{const He=x.feature(ye);ne.updatePaintArray(Ee,ke,He,ce,S,j,O,z)})}if(!K)for(const he of m.uniqueIds){const ce=l[he.toString()];m.eachPosition(he,(ye,Ee,ke)=>{const He=x.feature(ye);ne.updatePaintArray(Ee,ke,He,ce,S,j,O,z)})}U=!0}}return U}defines(){const l=[];for(const u in this.binders){const m=this.binders[u];(m instanceof F||m instanceof $)&&l.push(...m.uniformNames.map(x=>`#define HAS_UNIFORM_${x}`))}return l}getPaintVertexBuffers(){return this._buffers}getUniforms(l){const u=[];for(const m in this.binders){const x=this.binders[m];if(x instanceof F||x instanceof $||x instanceof Y)for(const b of x.uniformNames)u.push({name:b,property:m,binding:x.getBinding(l,b)})}return u}setUniforms(l,u,m,x,b){for(const{name:S,property:j,binding:C}of m)this.binders[j].setUniform(l,C,b,x.get(j),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 m=this.binders[u];(m instanceof H||m instanceof Y||m instanceof te)&&m.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,m=()=>!0){this.programConfigurations={};for(const x of l)this.programConfigurations[x.id]=new ee(x,u,m);this.needsUpload=!1,this._featureMap=new S0,this._featureMapWithoutIds=new S0,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(l,u,m,x,b,S,j,C,O){for(const z in this.programConfigurations)this.programConfigurations[z].populatePaintArrays(l,u,x,b,S,j,C,O);u.id!==void 0?this._featureMap.add(u.id,m,this._bufferOffset,l):(this._featureMapWithoutIds.add(this._idlessCounter,m,this._bufferOffset,l),this._idlessCounter+=1),this._bufferOffset=l,this.needsUpload=!0}updatePaintArrays(l,u,m,x,b,S,j,C){for(const O of m)this.needsUpload=this.programConfigurations[O.id].updatePaintArrays(l,this._featureMap,this._featureMapWithoutIds,u,O,x,b,S,j||0,C)||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 ge={"line-pattern":{source:Nd,composite:Nd},"fill-pattern":{source:Nd,composite:Nd},"fill-extrusion-pattern":{source:Nd,composite:Nd},"line-dasharray":{source:kg,composite:kg}},pe={color:{source:Hm,composite:bh},number:{source:kc,composite:Hm}};function Ne(h,l,u){const m=ge[h];return m&&m[u]||pe[l][u]}br(F,"ConstantBinder"),br($,"PatternConstantBinder"),br(H,"SourceExpressionBinder"),br(te,"PatternCompositeBinder"),br(Y,"CompositeExpressionBinder"),br(ee,"ProgramConfiguration",{omit:["_buffers"]}),br(ie,"ProgramConfigurationSet");const Le=ar/Math.PI/2,xe=64,Ze=[xe,32,16],ze=-Le,Ke=Le;function De(h,l,u,m=Le){return u=Yn(u),[h*Math.sin(u)*m,-l*m,h*Math.cos(u)*m]}function Be(h,l,u){return De(Math.cos(Yn(h)),Math.sin(Yn(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,m=this.lat*u,x=l.lat*u,b=Math.sin(m)*Math.sin(x)+Math.cos(m)*Math.cos(x)*Math.cos((l.lng-this.lng)*u);return qe*Math.acos(Math.min(b,1))}toBounds(l=0){const u=360*l/40075017,m=u/Math.cos(Math.PI/180*this.lat);return new xt({lng:this.lng-m,lat:this.lat-u},{lng:this.lng+m,lat:this.lat+u})}toEcef(l){return Be(this.lat,this.lng,Le+l*Le/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,m=this._ne;let x,b;if(l instanceof Qe)x=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(x=l._sw,b=l._ne,!x||!b)return this}return u||m?(u.lng=Math.min(x.lng,u.lng),u.lat=Math.min(x.lat,u.lat),m.lng=Math.max(b.lng,m.lng),m.lat=Math.max(b.lat,m.lat)):(this._sw=new Qe(x.lng,x.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:m}=Qe.convert(l);let x=this._sw.lng<=u&&u<=this._ne.lng;return this._sw.lng>this._ne.lng&&(x=this._sw.lng>=u&&u>=this._ne.lng),this._sw.lat<=m&&m<=this._ne.lat&&x}static convert(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 bt(h,l){return h*ft(gt(l))}const St=85.051129;function rr(h){return Math.cos(Yn(fe(h,-85.051129,St)))}function Ht(h,l){const u=fe(l,0,25.5),m=Math.pow(2,u);return rr(h)*st/(512*m)}function Wt(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<=C?(Lr(h,l,u,O,z,b,U,j,C),Lr(h,O,z,m,x,U,S,j,C)):h.push(S)}function yr(h,l,u){let m=h[0],x=m.x,b=m.y;l(m);const S=[m];for(let j=1;jh.x+1||mh.y+1)&&Br("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function Ur(h,l,u){const m=h.loadGeometry(),x=h.extent,b=ar/x;if(l&&u&&u.projection.isReprojectedInTileSpace){const S=1<{const K=et((l.x+q.x/x)/S),X=gt((l.y+q.y/x)/S),J=z.project(K,X);q.x=(J.x*j-C)*x,q.y=(J.y*j-O)*x};for(let q=0;q=x||X.y<0||X.y>=x||(U(X),K.push(X));m[q]=K}}for(const S of m)for(const j of S)bn(j,b);return m}function wn(h,l){return{type:h.type,id:h.id,properties:h.properties,geometry:l?Ur(h):[]}}class tn{constructor(l,u,m,x,b){this.properties={},this.extent=m,this.type=0,this.id=void 0,this._pbf=l,this._geometry=-1,this._keys=x,this._values=b,l.readFields(qn,this,u)}loadGeometry(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos,m=[];let x,b=1,S=0,j=0,C=0;for(;l.pos>3}if(S--,b===1||b===2)j+=l.readSVarint(),C+=l.readSVarint(),b===1&&(x&&m.push(x),x=[]),x&&x.push(new Ot(j,C));else{if(b!==7)throw new Error(`unknown command ${b}`);x&&x.push(x[0].clone())}}return x&&m.push(x),m}bbox(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos;let m=1,x=0,b=0,S=0,j=1/0,C=-1/0,O=1/0,z=-1/0;for(;l.pos>3}if(x--,m===1||m===2)b+=l.readSVarint(),S+=l.readSVarint(),bC&&(C=b),Sz&&(z=S);else if(m!==7)throw new Error(`unknown command ${m}`)}return[j,O,C,z]}toGeoJSON(l,u,m){const x=this.extent*Math.pow(2,m),b=this.extent*l,S=this.extent*u,j=this.loadGeometry();function C(q){return[360*(q.x+b)/x-180,360/Math.PI*Math.atan(Math.exp((1-2*(q.y+S)/x)*Math.PI))-90]}function O(q){return q.map(C)}let z;if(this.type===1){const q=[];for(const X of j)q.push(X[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=j.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(X){const J=X.length;if(J<=1)return[X];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 ki(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(m){let x=null;const b=m.readVarint()+m.pos;for(;m.pos>3;x=S===1?m.readString():S===2?m.readFloat():S===3?m.readDouble():S===4?m.readVarint64():S===5?m.readVarint():S===6?m.readSVarint():S===7?m.readBoolean():null}if(x==null)throw new Error("unknown feature value");return x}(u))}class Jn{constructor(l,u){this.layers=l.readFields(gn,{},u)}}function gn(h,l,u){if(h===3){const m=new Zi(u,u.readVarint()+u.pos);m.length&&(l[m.name]=m)}}const yn="3d_elevation_id",Ci="level";class ns{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,m){return this.get(l,!0,u,m)}optional(l,u,m){return this.get(l,!1,u,m)}success(){return this._valid}get(l,u,m,x){const b=this.feature.properties.hasOwnProperty(l)?+this.feature.properties[l]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?m(x?x(b):b):u&&(this._valid=!1),this}}class ei{constructor(l,u){this.featureFunc=l,this.vertexFunc=u}parseFeature(l,u,m){return this.featureFunc(l,u,m)}parseVertex(l,u,m){return this.vertexFunc(l,u,m)}}const on=new ei((h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).optional("fixed_height_relative",m=>{u.constantHeight=m},wi.decodeRelativeHeight).geometry(m=>{u.bounds=m},CT).success(),(h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height_relative",m=>{u.height=m},wi.decodeRelativeHeight).geometry(m=>{u.position=m},wi.getPoint).success()),Ki=new ei((h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).optional("fixed_height",m=>{u.constantHeight=m},wi.decodeMetricHeight).geometry(m=>{u.bounds=m},CT).success(),(h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height",m=>{u.height=m},wi.decodeMetricHeight).geometry(m=>{u.position=m},wi.getPoint).success());class wi{static getPoint(l){return Fn(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"?Ki:void 0:on}static parse(l){const u=[],m=[],x=l.length,b=new ns;for(let S=0;S=0);if(b===0)return 0;b!==l.length&&(u=!1)}return u?2:1}function ha(h,l){for(const u of h.projections){const m=Js(l,h.points[0],u.axis);if(u.projection[1]m[1])return 0}return 1}function qa(h,l){let u=0;const m=[0,0,0,0];for(let x=0;x=0&&u++;return u}class dc{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=oi.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 m of this.frustumEdges){const x=[0,-m[2],m[1]],b=[m[2],0,-m[0]];this.projections.push({axis:x,projection:Js(this.points,this.points[0],x)}),this.projections.push({axis:b,projection:Js(this.points,this.points[0],b)})}}static fromInvProjectionMatrix(l,u,m,x){const b=Math.pow(2,m),S=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(O=>{const z=hr([],O,l),U=1/z[3]/u*b;return(q=z)[0]=(K=z)[0]*(X=[U,U,x?1/z[3]:U,U])[0],q[1]=K[1]*X[1],q[2]=K[2]*X[2],q[3]=K[3]*X[3],q;var q,K,X}),j=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(O=>{const z=pt([],er([],tr([],S[O[0]],S[O[1]]),tr([],S[O[2]],S[O[1]]))),U=-Nt(z,S[O[1]]);return z.concat(U)}),C=[];for(let O=0;OO[1]||O[0]>C[1])return 0}return 1}containsPoint(l){for(const u of this.planes){const m=u[3];if(Nt([u[0],u[1],u[2]],l)+m<0)return!1}return!0}}class oi{static fromPoints(l){const u=[1/0,1/0,1/0],m=[-1/0,-1/0,-1/0];for(const x of l)Se(u,u,x),ve(m,m,x);return new oi(u,m)}static fromTileIdAndHeight(l,u,m){const x=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])]}}br(oi,"Aabb");class Ic{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,m=u[1],x=-u[0],b=(l.extent+1)*this.metersToTile;return[new Ot(Math.trunc(l.position[0]+m*b),Math.trunc(l.position[1]+x*b)),new Ot(Math.trunc(l.position[0]-m*b),Math.trunc(l.position[1]-x*b))]}next(){this.index++}valid(){return this.index{return j.a0?We(C,C,1/O):be(C,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(l){if(this.edges.length===0)return;let u=0,m=Number.POSITIVE_INFINITY,x=0;const[b,S,j,C,O,z,U]=this._tmpVec2;As(U,l.x,l.y);const q=new Os(U,null);for(let K=0;K0?Zr(C,j)/ye:0,ke=fe(Ee,0,1),He=Math.abs((Ee-ke)*this.edgeProps[K].len);_o(O,U,ne),As(z,J[1],-J[0]);const $e=He+Math.abs(Zr(O,z));$e=0;--S){const j=this.edges[S].a,C=this.edges[S].b,{position:O,height:z,extent:U}=this.vertices[j],{position:q,height:K,extent:X}=this.vertices[C],J=this.vertexProps[j].dir,ne=this.vertexProps[C].dir;if(be(u,O[0]/l,O[1]/l,z),be(m,q[0]/l,q[1]/l,K),be(x,J[1],-J[0],0),We(x,x,U),be(b,ne[1],-ne[0],0),We(b,b,X),this.distSqLines(Ae(u[0]+.5*x[0],u[1]+.5*x[1],u[2]+.5*x[2]),Ae(m[0]-.5*b[0],m[1]-.5*b[1],m[2]-.5*b[2]),Ae(u[0]-.5*x[0],u[1]-.5*x[1],u[2]-.5*x[2]),Ae(m[0]+.5*b[0],m[1]+.5*b[1],m[2]+.5*b[2]))<=.0025000000000000005)continue;const ae=this.vertices.length,he=Sa(Cr(),O,q);this.vertices.push({position:Yr(he,he,.5),height:.5*(z+K),extent:.5*(U+X)});const ce=Sa(Cr(),J,ne);this.vertexProps.push({dir:xn(ce,ce)}),this.edges.splice(S,1),this.edgeProps.splice(S,1),this.edges.push({a:j,b:ae}),this.edges.push({a:ae,b:C});const ye=_o(Cr(),this.vertices[ae].position,O),Ee=hn(ye),ke={vec:ye,dir:Yr(Cr(),ye,1/Ee),len:Ee};this.edgeProps.push(ke),this.edgeProps.push(ke)}}distSqLines(l,u,m,x){const b=Pe(we(),u,l),S=Pe(we(),x,m),j=Pe(we(),l,m),C=Nt(b,b),O=Nt(b,S),z=Nt(b,j),U=Nt(S,S),q=Nt(S,j),K=C*U-O*O;if(K===0)return Et(vt(b,m,x,Nt(j,S)/Nt(S,S)),l);const X=(C*q-O*z)/K;return Et(vt(b,l,u,(O*q-z*U)/K),vt(S,m,x,X))}}class Li{static parseFrom(l,u){const m=wi.parse(l);if(!m)return[];let{vertices:x,features:b}=m;const S=1/Dt(u);b.sort((z,U)=>z.id-U.id),x.sort((z,U)=>z.id-U.id||z.idx-U.idx),x=x.filter((z,U,q)=>U===q.findIndex(K=>K.id===z.id&&K.idx===z.idx));const j=new Array;let C=0;const O=x.length;for(const z of b){if(z.constantHeight){j.push(new Nc(z.id,z.bounds,z.constantHeight));continue}for(;C!==O&&x[C].idx.id===m)}}class $i{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,m){const x=this.constantElevation(u,m);return x??(l.x=l.x*this.zScale+this.xOffset,l.y=l.y*this.zScale+this.yOffset,this.computeBiasedHeight(u.pointElevation(l),m))}computeBiasedHeight(l,u){return u<=0?l:l+u*Oe(0,u,l>=0?l:Math.abs(.5*l))}}br(Nc,"ElevationFeature");class gi{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 uc,this.indexArray=new vs,this.segments=new ji,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 kc),this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){const b=this.layers[0],S=[];let j=null;b.type==="circle"&&(j=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,X=wn(O,K);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),X,m))continue;const J=j?j.evaluate(X,{},m):void 0,ne={id:z,properties:O.properties,type:O.type,sourceLayerIndex:q,index:U,geometry:K?X.geometry:Ur(O,m,x),patterns:{},sortKey:J};S.push(ne)}j&&S.sort((O,z)=>O.sortKey-z.sortKey);let C=null;x.projection.name==="globe"&&(this.globeExtVertexArray=new cb,C=x.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,m,C,u.brightness,u.elevationFeatures),u.featureIndex.insert(K,z,U,q,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(l,u,m,x,b,S,j){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,j,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,QI.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,j5.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,A5.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,m,x,b,S,j,C){let O;this.elevationMode!=="none"&&(O=Li.getElevationFeature(l,C));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 X=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,l.sortKey),J=X.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 Ot(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),X.vertexLength+=4,X.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,m,{},x,b,j,void 0,this.worldview)}addCircleVertex(l,u,m,x){this.layoutVertexArray.emplaceBack(2*l+(m+1)/2,2*u+(x+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(Tf(h,l))return!0;for(let m=0;m1?u:u.sub(l)._mult(x)._add(l))}function Ig(h,l){let u,m,x,b=!1;for(let S=0;Sl.y!=x.y>l.y&&l.x<(x.x-m.x)*(l.y-m.y)/(x.y-m.y)+m.x&&(b=!b)}return b}function Bl(h,l){let u=!1;for(let m=0,x=h.length-1;ml.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 Ef(h,l,u,m,x){for(const S of h)if(l<=S.x&&u<=S.y&&m>=S.x&&x>=S.y)return!0;const b=[new Ot(l,u),new Ot(l,x),new Ot(m,x),new Ot(m,u)];if(h.length>2){for(const S of b)if(Bl(h,S))return!0}for(let S=0;Sx.x&&l.x>x.x||h.yx.y&&l.y>x.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 jf(h,l,u,m,x,b){let S=l.y-h.y,j=h.x-l.x;if(b=b||0){const C=S*S+j*j;if(C===0)return!0;const O=Math.sqrt(C);S/=O,j/=O}return!((u.x-h.x)*S+(u.y-h.y)*j-b<0||(m.x-h.x)*S+(m.y-h.y)*j-b<0||(x.x-h.x)*S+(x.y-h.y)*j-b<0)}function xb(h,l,u,m,x,b,S){return!(jf(h,l,m,x,b,S)||jf(l,u,m,x,b,S)||jf(u,h,m,x,b,S)||jf(m,x,h,l,u,S)||jf(x,b,h,l,u,S)||jf(b,m,h,l,u,S))}function Ng(h,l,u){const m=l.paint.get(h).value;return m.kind==="constant"?m.value:u.programConfigurations.get(l.id).getMaxValue(h)}function JI(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function MK(h,l,u,m,x){if(!l[0]&&!l[1])return h;const b=Ot.convert(l)._mult(x);u==="viewport"&&b._rotate(-m);const S=[];for(let j=0;j>u&&l.y===this.y>>u}url(l,u){const m=function(b,S,j){const C=2**j,O=2*Math.PI*6378137,z=O*(b/C-.5),U=O*(.5-(S+1)/C);return`${z},${U},${z+O/C},${U+O/C}`}(this.x,this.y,this.z),x=function(b,S,j){let C,O="";for(let z=b;z>0;z--)C=1<this.canonical.z?new vl(l,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new vl(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 _b(this.wrap*+u,l,this.canonical.z,this.canonical.x,this.canonical.y);{const m=this.canonical.z-l;return _b(this.wrap*+u,l,l,this.canonical.x>>m,this.canonical.y>>m)}}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 vl(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const u=this.canonical.z+1,m=2*this.canonical.x,x=2*this.canonical.y;return[new vl(u,this.wrap,u,m,x),new vl(u,this.wrap,u,m+1,x),new vl(u,this.wrap,u,m,x+1),new vl(u,this.wrap,u,m+1,x+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 vl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new vl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<1?null:function(m,x,b,S){const j=Math.sin(b);return m*(Math.sin((1-S)*b)/j)+x*(Math.sin(S*b)/j)}(h.a[l],h.b[l],h.angle,fe(u,0,1))+h.center[l]}function kf(h){if(h.z<=1)return pje[h.z+2*h.y+h.x];const l=L5(rN(h));return oi.fromPoints(l)}function Zm(h,l,u){return We(h,h,1-u),rt(h,h,l,u)}function VK(h,l){const u=Xm(l.zoom);if(u===0)return kf(h);const m=rN(h),x=L5(m),b=Rt(m.getWest())*l.worldSize,S=Rt(m.getEast())*l.worldSize,j=Ft(m.getNorth())*l.worldSize,C=Ft(m.getSouth())*l.worldSize,O=[b,j,0],z=[S,j,0],U=[b,C,0],q=[S,C,0],K=D([],l.globeMatrix);return or(O,O,K),or(z,z,K),or(U,U,K),or(q,q,K),x[0]=Zm(x[0],U,u),x[1]=Zm(x[1],q,u),x[2]=Zm(x[2],z,u),x[3]=Zm(x[3],O,u),oi.fromPoints(x)}function qK(h,l,u){for(const m of h)or(m,m,l),We(m,m,u)}function GK(h,l,u,m){const x=l/h.worldSize,b=h.globeMatrix;if(u.z<=1){const Ge=kf(u).getCorners();return qK(Ge,b,x),oi.fromPoints(Ge)}const S=rN(u,m),j=L5(S,Le+tN(h._tileCoverLift));qK(j,b,x);const C=Number.MAX_VALUE,O=[-C,-C,-C],z=[C,C,C];if(S.contains(h.center)){for(const Ve of j)Se(z,z,Ve),ve(O,O,Ve);O[2]=0;const Ge=h.point,Ue=[Ge.x*x,Ge.y*x,0];return Se(z,z,Ue),ve(O,O,Ue),new oi(z,O)}if(h._tileCoverLift>0){for(const Ge of j)Se(z,z,Ge),ve(O,O,Ge);return new oi(z,O)}const U=[b[12]*x,b[13]*x,b[14]*x],q=S.getCenter(),K=fe(h.center.lat,-85.051129,St),X=fe(q.lat,-85.051129,St),J=Rt(h.center.lng),ne=Ft(K);let ae=J-Rt(q.lng);const he=ne-Ft(X);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]*x,b[5]*x,b[6]*x],-Math.sin(Yn(he>=0?S.getSouth():S.getNorth()))*Le));const ye=j[ce],Ee=j[(ce+1)%4],ke=new gje(ye,Ee,U),He=[R5(ke,0)||ye[0],R5(ke,1)||ye[1],R5(ke,2)||ye[2]],$e=Xm(h.zoom);if($e>0){const Ge=function({x:Ve,y:yt,z:wt},jt,It,kt,Bt){const mt=1/(1<.5?_r=-1:ir<-.5&&(_r=1),Ct=((Ct+_r)*jt-(kt*=jt))*It+kt,Lt=((Lt+_r)*jt-kt)*It+kt,Ut=(Ut*jt-(Bt*=jt))*It+Bt,Kt=(Kt*jt-Bt)*It+Bt,[[Ct,Kt,0],[Lt,Kt,0],[Lt,Ut,0],[Ct,Ut,0]]}(u,l,h._pixelsPerMercatorPixel,J,ne);for(let Ve=0;VeMath.PI/2*1.01}const ZK=Yn(85),yje=Math.cos(ZK),xje=Math.sin(ZK),_je=k(),XK=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 QK(h,l,u,m,x,b,S,j,C){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(C*=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(j),X=x&&u.elevation?u.elevation.exaggeration()*x.getElevationAt(K.x,K.y,!0):0,J=u.projection.projectTilePoint(K.x,K.y,O);if(X>0){const ce=u.projection.upVector(O,K.x,K.y);J.x+=ce[0]*z*X,J.y+=ce[1]*z*X,J.z+=ce[2]*z*X}const ne=b?K:vje(J.x,J.y,J.z,m),ae=b?h.tilespaceRays.map(ce=>wje(ce,X)):h.queryGeometry.screenGeometry,he=hr([],[J.x,J.y,J.z,1],m);if(!S&&b?C*=he[3]/u.cameraToCenterDistance:S&&!b&&(C*=u.cameraToCenterDistance/he[3]),b){const ce=gt((q.y/ar+O.y)/(1<h.width||x.height>h.height||u.x>h.width-x.width||u.y>h.height-x.height)throw new RangeError("out of range source coordinates for image copy");if(x.width>l.width||x.height>l.height||m.x>l.width-x.width||m.y>l.height-x.height)throw new RangeError("out of range destination coordinates for image copy");const C=h.data,O=l.data,z=b===4&&j;for(let U=0;U{l[h.evaluationKey]=C;const O=h.expression.evaluate(l),z=O?O.toNonPremultipliedRenderColor(null):null;z&&(x.data[S+j+0]=Math.floor(255*z.r),x.data[S+j+1]=Math.floor(255*z.g),x.data[S+j+2]=Math.floor(255*z.b),x.data[S+j+3]=Math.floor(255*z.a))};if(h.clips)for(let S=0,j=0;S80*u){j=h[0],C=h[1];let z=j,U=C;for(let q=u;qz&&(z=K),X>U&&(U=X)}O=Math.max(z-j,U-C),O=O!==0?32767/O:0}return UE(b,S,u,j,C,O,0),S}function lY(h,l,u,m,x){let b;if(x===function(S,j,C,O){let z=0;for(let U=j,q=C-O;U0)for(let S=l;S=l;S-=m)b=hY(S/m|0,h[S],h[S+1],b);return b&&bb(b,b.next)&&(GE(b),b=b.next),b}function k0(h,l){if(!h)return h;l||(l=h);let u,m=h;do if(u=!1,m.steiner||!bb(m,m.next)&&Ga(m.prev,m,m.next)!==0)m=m.next;else{if(GE(m),m=l=m.prev,m===m.next)break;u=!0}while(u||m!==l);return l}function UE(h,l,u,m,x,b,S){if(!h)return;!S&&b&&function(C,O,z,U){let q=C;do q.z===0&&(q.z=B5(q.x,q.y,O,z,U)),q.prevZ=q.prev,q.nextZ=q.next,q=q.next;while(q!==C);q.prevZ.nextZ=null,q.prevZ=null,function(K){let X,J=1;do{let ne,ae=K;K=null;let he=null;for(X=0;ae;){X++;let ce=ae,ye=0;for(let ke=0;ke0||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(X>1)}(q)}(h,m,x,b);let j=h;for(;h.prev!==h.next;){const C=h.prev,O=h.next;if(b?kje(h,m,x,b):jje(h))l.push(C.i,h.i,O.i),GE(h),h=O.next,j=O.next;else if((h=O)===j){S?S===1?UE(h=Cje(k0(h),l),l,u,m,x,b,2):S===2&&Ije(h,l,u,m,x,b):UE(k0(h),l,u,m,x,b,1);break}}}function jje(h){const l=h.prev,u=h,m=h.next;if(Ga(l,u,m)>=0)return!1;const x=l.x,b=u.x,S=m.x,j=l.y,C=u.y,O=m.y,z=Math.min(x,b,S),U=Math.min(j,C,O),q=Math.max(x,b,S),K=Math.max(j,C,O);let X=m.next;for(;X!==l;){if(X.x>=z&&X.x<=q&&X.y>=U&&X.y<=K&&VE(x,j,b,C,S,O,X.x,X.y)&&Ga(X.prev,X,X.next)>=0)return!1;X=X.next}return!0}function kje(h,l,u,m){const x=h.prev,b=h,S=h.next;if(Ga(x,b,S)>=0)return!1;const j=x.x,C=b.x,O=S.x,z=x.y,U=b.y,q=S.y,K=Math.min(j,C,O),X=Math.min(z,U,q),J=Math.max(j,C,O),ne=Math.max(z,U,q),ae=B5(K,X,l,u,m),he=B5(J,ne,l,u,m);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>=X&&ce.y<=ne&&ce!==x&&ce!==S&&VE(j,z,C,U,O,q,ce.x,ce.y)&&Ga(ce.prev,ce,ce.next)>=0||(ce=ce.prevZ,ye.x>=K&&ye.x<=J&&ye.y>=X&&ye.y<=ne&&ye!==x&&ye!==S&&VE(j,z,C,U,O,q,ye.x,ye.y)&&Ga(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>=X&&ce.y<=ne&&ce!==x&&ce!==S&&VE(j,z,C,U,O,q,ce.x,ce.y)&&Ga(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>=X&&ye.y<=ne&&ye!==x&&ye!==S&&VE(j,z,C,U,O,q,ye.x,ye.y)&&Ga(ye.prev,ye,ye.next)>=0)return!1;ye=ye.nextZ}return!0}function Cje(h,l){let u=h;do{const m=u.prev,x=u.next.next;!bb(m,x)&&uY(m,u,u.next,x)&&qE(m,x)&&qE(x,m)&&(l.push(m.i,u.i,x.i),GE(u),GE(u.next),u=h=x),u=u.next}while(u!==h);return k0(u)}function Ije(h,l,u,m,x,b){let S=h;do{let j=S.next.next;for(;j!==S.prev;){if(S.i!==j.i&&Dje(S,j)){let C=dY(S,j);return S=k0(S,S.next),C=k0(C,C.next),UE(S,l,u,m,x,b,0),void UE(C,l,u,m,x,b,0)}j=j.next}S=S.next}while(S!==h)}function Nje(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 Pje(h,l){const u=function(x,b){let S=b;const j=x.x,C=x.y;let O,z=-1/0;if(bb(x,S))return S;do{if(bb(x,S.next))return S.next;if(C<=S.y&&C>=S.next.y&&S.next.y!==S.y){const J=S.x+(C-S.y)*(S.next.x-S.x)/(S.next.y-S.y);if(J<=j&&J>z&&(z=J,O=S.x=S.x&&S.x>=q&&j!==S.x&&cY(CO.x||S.x===O.x&&Rje(O,S)))&&(O=S,X=J)}S=S.next}while(S!==U);return O}(h,l);if(!u)return l;const m=dY(u,h);return k0(m,m.next),k0(u,u.next)}function Rje(h,l){return Ga(h.prev,h,l.prev)<0&&Ga(l.next,h,h.next)<0}function B5(h,l,u,m,x){return(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-u)*x|0)|h<<8))|h<<4))|h<<2))|h<<1))|(l=1431655765&((l=858993459&((l=252645135&((l=16711935&((l=(l-m)*x|0)|l<<8))|l<<4))|l<<2))|l<<1))<<1}function Lje(h){let l=h,u=h;do(l.x=(h-S)*(b-j)&&(h-S)*(m-j)>=(u-S)*(l-j)&&(u-S)*(b-j)>=(x-S)*(m-j)}function VE(h,l,u,m,x,b,S,j){return!(h===S&&l===j)&&cY(h,l,u,m,x,b,S,j)}function Dje(h,l){return h.next.i!==l.i&&h.prev.i!==l.i&&!function(u,m){let x=u;do{if(x.i!==u.i&&x.next.i!==u.i&&x.i!==m.i&&x.next.i!==m.i&&uY(x,x.next,u,m))return!0;x=x.next}while(x!==u);return!1}(h,l)&&(qE(h,l)&&qE(l,h)&&function(u,m){let x=u,b=!1;const S=(u.x+m.x)/2,j=(u.y+m.y)/2;do x.y>j!=x.next.y>j&&x.next.y!==x.y&&S<(x.next.x-x.x)*(j-x.y)/(x.next.y-x.y)+x.x&&(b=!b),x=x.next;while(x!==u);return b}(h,l)&&(Ga(h.prev,h,l.prev)||Ga(h,l.prev,l))||bb(h,l)&&Ga(h.prev,h,h.next)>0&&Ga(l.prev,l,l.next)>0)}function Ga(h,l,u){return(l.y-h.y)*(u.x-l.x)-(l.x-h.x)*(u.y-l.y)}function bb(h,l){return h.x===l.x&&h.y===l.y}function uY(h,l,u,m){const x=sN(Ga(h,l,u)),b=sN(Ga(h,l,m)),S=sN(Ga(u,m,h)),j=sN(Ga(u,m,l));return x!==b&&S!==j||!(x!==0||!iN(h,u,l))||!(b!==0||!iN(h,m,l))||!(S!==0||!iN(u,h,m))||!(j!==0||!iN(u,l,m))}function iN(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 sN(h){return h>0?1:h<0?-1:0}function qE(h,l){return Ga(h.prev,h,h.next)<0?Ga(h,l,h.next)>=0&&Ga(h,h.prev,l)>=0:Ga(h,l,h.prev)<0||Ga(h,h.next,l)<0}function dY(h,l){const u=z5(h.i,h.x,h.y),m=z5(l.i,l.x,l.y),x=h.next,b=l.prev;return h.next=l,l.prev=h,u.next=x,x.prev=u,m.next=u,u.prev=m,b.next=m,m.prev=b,m}function hY(h,l,u,m){const x=z5(h,l,u);return m?(x.next=m.next,x.prev=m,m.next.prev=x,m.next=x):(x.prev=x,x.next=x),x}function GE(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 z5(h,l,u){return{i:h,x:l,y:u,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function HE(h,l){const u=h.length;if(u<=1)return[h];const m=[];let x,b;for(let S=0;S1)for(let S=0;S=ar&&u>=ar}static evaluate(l){if(l.length===0)return new Qm;let u=[];for(const C of l)u.push(...C.portals);if(u.length===0)return new Qm;for(const C of u){const O=C.va,z=C.vb;(Qm.isOnBorder(O.x,z.x)||Qm.isOnBorder(O.y,z.y))&&(C.type="border")}const m=u.filter(C=>C.type!=="unevaluated"),x=u.filter(C=>C.type==="unevaluated");if(x.length===0)return new Qm;x.sort((C,O)=>C.hash===O.hash?C.isTunnel===O.isTunnel?0:C.isTunnel?-1:1:C.hashC.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new ie(u,{zoom:m,lut:x},b=>b!=="fill-bridge-guard-rail-color")}addVertices(l,u){const m=this.unevalVertices.length;for(let x=0;x=b.min.x&&U.x<=b.max.x&&U.y>=b.min.y&&U.y<=b.max.y||q.x>=b.min.x&&q.x<=b.max.x&&q.y>=b.min.y&&q.y<=b.max.y||Af(U,q,j))||this.isOnBorder(U.x,q.x)||this.isOnBorder(U.y,q.y))continue;const K=Pc.computeEdgeHash(this.unevalVertices[O],this.unevalVertices[z]);let X,J=this.vertexHashLookup.get(Pc.computePosHash(U));J!=null?X=J.next:(J=this.vertexHashLookup.get(Pc.computePosHash(q)),X=J!=null?J.prev:K),this.unevalEdges.push({polygonIdx:l,a:O,b:z,hash:K,portalHash:X,isTunnel:x,type:"unevaluated",featureInfo:S})}}addPortalCandidates(l,u,m,x,b){if(u.length!==0){this.vertexHashLookup.clear();for(const S of u){if(S.length===0)continue;const j=S[0];let C=Pc.computeEdgeHash(j[j.length-2],j[j.length-1]);for(let O=0;O({vertexOffset:0,primitiveOffset:this.indexArray.length}),m=q=>{q.primitiveLength=this.indexArray.length-q.primitiveOffset},x=new Oje(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(l.portals,this.unevalEdges);const b=u(),S=u(),j=u(),C=(q,K)=>{q.sort((J,ne)=>J.type===K&&ne.type!==K?-1:J.type!==K&&ne.type===K?1:0);const X=q.findIndex(J=>J.type!==K);return X>=0?X:q.length};let O=0;this.unevalEdges.length>0&&(O=C(this.unevalEdges,"none"),this.constructBridgeStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},this.tileToMeters)),m(j);const z=u(),U=u();if(this.unevalEdges.length>0){const q=this.unevalEdges.splice(O),K=C(q,"tunnel")+O;this.unevalEdges.push(...q),this.constructTunnelStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},{min:O,max:K})}m(z),x.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),m(U),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),m(S),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),m(b),this.maskSegments=ji.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.depthSegments=ji.simpleSegment(0,S.primitiveOffset,0,S.primitiveLength),this.renderableBridgeSegments=ji.simpleSegment(0,j.primitiveOffset,0,j.primitiveLength),this.renderableTunnelSegments=ji.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.shadowCasterSegments=ji.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(l,u,m,x,b,S,j,C){this.bridgeProgramConfigurations.updatePaintArrays(l,u,b,m,x,S,j,C),this.tunnelProgramConfigurations.updatePaintArrays(l,u,b,m,x,S,j,C)}upload(l){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=l.createVertexBuffer(this.vertexPositions,Eje.members),this.vertexBufferNormal=l.createVertexBuffer(this.vertexNormals,Aje.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,m,x,b){const S=(j,C)=>{for(let O=0;Obe(It,u[kt].x,u[kt].y,m[kt]*C),U=we(),q=we(),K=we(),X=we(),J=we(),ne=(It,kt)=>{const Bt=j.get(Pc.computePosHash(u[kt])),mt=Bt.from,Ct=Bt.to;if(!mt||!Ct)return;z(U,mt),z(q,kt),z(K,Ct),cr(X),xr(U,q)||(tr(J,q,U),pt(X,J)),xr(K,q)||(tr(J,K,q),me(X,X,pt(J,J)));const Lt=lt(X);return Lt>0?We(It,X,1/Lt):void 0};let ae=Number.POSITIVE_INFINITY;this.sortSubarray(x,b.min,b.max,(It,kt)=>It.featureInfo.featureIndex-kt.featureInfo.featureIndex);const he=we(),ce=we(),ye=we(),Ee=we(),ke=we(),He=we(),$e=we(),Ge=we(),Ue=we(),Ve=[we(),we(),we(),we()],yt=[we(),we(),we(),we()],wt=[{coord:new Ot(0,0),height:0},{coord:new Ot(0,0),height:0}],jt=(It,kt)=>It>kt;for(let It=b.min;Itae.featureInfo.featureIndex-he.featureInfo.featureIndex;this.sortSubarray(x,b.min,b.max,C),this.sortSubarray(x,S.min,S.max,C);const O=ae=>pt(ae,ae),z=[{coord:new Ot(0,0),height:0},{coord:new Ot(0,0),height:0}],U=(ae,he)=>aej.hash===C.hash?C.polygonIdx-j.polygonIdx:C.hash>j.hash?1:-1);let m=0,x=0,b=0,S=u[m].polygonIdx;do x++,(x===u.length||u[m].hash!==u[x].hash)&&((x-m===1||u[x-1].polygonIdx!==S)&&(bO.portalHashz.hash?j++:z.hash>O.portalHash?C++:(O.type=z.type,j++)}}}isOnBorder(l,u){return l<=0&&u<=0||l>=ar&&u>=ar}addFeatureSection(l,u,m,x){return l!==u&&(u=l,m.push({featureIndex:l,vertexStart:x.getVertexCount()}),x.clearVertexLookup()),u}sortSubarray(l,u,m,x){const b=l.slice(u,m);b.sort(x),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(Pc.computePosHash(l))<<32n|BigInt(Pc.computePosHash(u))}static computePosHash(l){return((65535&l.x)<<16|65535&l.y)>>>0}}function Fje(h,l){return h>l?1:h0))return u;u=u.left}}return null}contains(l){for(var u=this._root,m=this._compare;u;){var x=m(l,u.key);if(x===0)return!0;u=x<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 m=this.minNode(u.right);m.parent!==u&&(this.replace(m,m.right),m.right=u.right,m.right.parent=m),this.replace(u,m),m.left=u.left,m.left.parent=m}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}removeNode(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 m=u.left,x=u.right,b=null;m&&(m.parent=null,b=this.maxNode(m),this.splay(b),this._root=b),x&&(m?b.right=x:this._root=x,x.parent=b),this._size--}}pop(){var 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,m=[],x=!1,b=0;!x;)u?(m.push(u),u=u.left):m.length>0?(l(u=m.pop(),b++),u=u.right):x=!0;return this}range(l,u,m,x){const b=[],S=this._compare;let j,C=this._root;for(;b.length!==0||C;)if(C)b.push(C),C=C.left;else{if(C=b.pop(),j=S(C.key,u),j>0)break;if(S(C.key,l)>=0&&m.call(x,C))return this;C=C.right}return this}keys(){for(var l=this._root,u=[],m=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),m.push(l.key),l=l.right):x=!0;return m}values(){for(var l=this._root,u=[],m=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),m.push(l.data),l=l.right):x=!0;return m}at(l){for(var u=this._root,m=[],x=!1,b=0;!x;)if(u)m.push(u),u=u.left;else if(m.length>0){if(u=m.pop(),b===l)return u;b++,u=u.right}else x=!0;return null}load(l=[],u=[],m=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const x=l.length;return m&&G5(l,u,0,x-1,this._compare),this._root=q5(null,l,u,0,x),this._size=x,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,m,x,b){return new V5(m,b).load(l,u,x)}}function q5(h,l,u,m,x){const b=x-m;if(b>0){const S=m+Math.floor(b/2),j={key:l[S],data:u[S],parent:h};return j.left=q5(j,l,u,m,S),j.right=q5(j,l,u,S+1,x),j}return null}function G5(h,l,u,m,x){if(u>=m)return;const b=h[u+m>>1];let S=u-1,j=m+1;for(;;){do S++;while(x(h[S],b)<0);do j--;while(x(h[j],b)>0);if(S>=j)break;let C=h[S];h[S]=h[j],h[j]=C,C=l[S],l[S]=l[j],l[j]=C}G5(h,l,u,j,x),G5(h,l,j+1,m,x)}const mY=11102230246251565e-32,fc=134217729,Bje=(3+8*mY)*mY;function H5(h,l,u,m,x){let b,S,j,C,O=l[0],z=m[0],U=0,q=0;z>O==z>-O?(b=O,O=l[++U]):(b=z,z=m[++q]);let K=0;if(UO==z>-O?(S=O+b,j=b-(S-O),O=l[++U]):(S=z+b,j=b-(S-z),z=m[++q]),b=S,j!==0&&(x[K++]=j);UO==z>-O?(S=b+O,C=S-b,j=b-(S-C)+(O-C),O=l[++U]):(S=b+z,C=S-b,j=b-(S-C)+(z-C),z=m[++q]),b=S,j!==0&&(x[K++]=j);for(;U0:(m[0]-l[0])*(u[1]-l[1])-(u[0]-l[0])*(m[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 Cf(h,l){return h[0]===l[0]&&h[1]===l[1]}function W5(h,l,u){const m=function(x,b,S,j,C,O){const z=(b-O)*(S-C),U=(x-C)*(j-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(X,J,ne,ae,he,ce,ye){let Ee,ke,He,$e,Ge,Ue,Ve,yt,wt,jt,It,kt,Bt,mt,Ct,Lt,Ut,Kt;const _r=X-he,ir=ne-he,nr=J-ce,Yt=ae-ce;mt=_r*Yt,Ue=fc*_r,Ve=Ue-(Ue-_r),yt=_r-Ve,Ue=fc*Yt,wt=Ue-(Ue-Yt),jt=Yt-wt,Ct=yt*jt-(mt-Ve*wt-yt*wt-Ve*jt),Lt=nr*ir,Ue=fc*nr,Ve=Ue-(Ue-nr),yt=nr-Ve,Ue=fc*ir,wt=Ue-(Ue-ir),jt=ir-wt,Ut=yt*jt-(Lt-Ve*wt-yt*wt-Ve*jt),It=Ct-Ut,Ge=Ct-It,wb[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,Bt=mt-(kt-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,wb[1]=Bt-(It+Ge)+(Ge-Lt),Kt=kt+It,Ge=Kt-kt,wb[2]=kt-(Kt-Ge)+(It-Ge),wb[3]=Kt;let pr=function($n,cn){let Vn=cn[0];for(let Sn=1;Sn<4;Sn++)Vn+=cn[Sn];return Vn}(0,wb),jr=22204460492503146e-32*ye;if(pr>=jr||-pr>=jr||(Ge=X-_r,Ee=X-(_r+Ge)+(Ge-he),Ge=ne-ir,He=ne-(ir+Ge)+(Ge-he),Ge=J-nr,ke=J-(nr+Ge)+(Ge-ce),Ge=ae-Yt,$e=ae-(Yt+Ge)+(Ge-ce),Ee===0&&ke===0&&He===0&&$e===0)||(jr=11093356479670487e-47*ye+Bje*Math.abs(pr),pr+=_r*$e+Yt*Ee-(nr*He+ir*ke),pr>=jr||-pr>=jr))return pr;mt=Ee*Yt,Ue=fc*Ee,Ve=Ue-(Ue-Ee),yt=Ee-Ve,Ue=fc*Yt,wt=Ue-(Ue-Yt),jt=Yt-wt,Ct=yt*jt-(mt-Ve*wt-yt*wt-Ve*jt),Lt=ke*ir,Ue=fc*ke,Ve=Ue-(Ue-ke),yt=ke-Ve,Ue=fc*ir,wt=Ue-(Ue-ir),jt=ir-wt,Ut=yt*jt-(Lt-Ve*wt-yt*wt-Ve*jt),It=Ct-Ut,Ge=Ct-It,Rc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,Bt=mt-(kt-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,Rc[1]=Bt-(It+Ge)+(Ge-Lt),Kt=kt+It,Ge=Kt-kt,Rc[2]=kt-(Kt-Ge)+(It-Ge),Rc[3]=Kt;const zr=H5(4,wb,4,Rc,pY);mt=_r*$e,Ue=fc*_r,Ve=Ue-(Ue-_r),yt=_r-Ve,Ue=fc*$e,wt=Ue-(Ue-$e),jt=$e-wt,Ct=yt*jt-(mt-Ve*wt-yt*wt-Ve*jt),Lt=nr*He,Ue=fc*nr,Ve=Ue-(Ue-nr),yt=nr-Ve,Ue=fc*He,wt=Ue-(Ue-He),jt=He-wt,Ut=yt*jt-(Lt-Ve*wt-yt*wt-Ve*jt),It=Ct-Ut,Ge=Ct-It,Rc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,Bt=mt-(kt-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,Rc[1]=Bt-(It+Ge)+(Ge-Lt),Kt=kt+It,Ge=Kt-kt,Rc[2]=kt-(Kt-Ge)+(It-Ge),Rc[3]=Kt;const Rr=H5(zr,pY,4,Rc,gY);mt=Ee*$e,Ue=fc*Ee,Ve=Ue-(Ue-Ee),yt=Ee-Ve,Ue=fc*$e,wt=Ue-(Ue-$e),jt=$e-wt,Ct=yt*jt-(mt-Ve*wt-yt*wt-Ve*jt),Lt=ke*He,Ue=fc*ke,Ve=Ue-(Ue-ke),yt=ke-Ve,Ue=fc*He,wt=Ue-(Ue-He),jt=He-wt,Ut=yt*jt-(Lt-Ve*wt-yt*wt-Ve*jt),It=Ct-Ut,Ge=Ct-It,Rc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,Bt=mt-(kt-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,Rc[1]=Bt-(It+Ge)+(Ge-Lt),Kt=kt+It,Ge=Kt-kt,Rc[2]=kt-(Kt-Ge)+(It-Ge),Rc[3]=Kt;const ln=H5(Rr,gY,4,Rc,yY);return yY[ln-1]}(x,b,S,j,C,O,K)}(h[0],h[1],l[0],l[1],u[0],u[1]);return m>0?-1:m<0?1:0}function Rg(h,l){const u=h.point,m=l.point;return u[0]>m[0]?1:u[0]m[1]?1:-1:function(x,b,S){return x.left!==b.left?x.left?1:-1:W5(S,x.otherEvent.point,b.otherEvent.point)!==0?x.isBelow(b.otherEvent.point)?-1:1:!x.isSubject&&b.isSubject?1:-1}(h,l,u)}function Lg(h,l,u){const m=new Sb(l,!1,h,h.isSubject),x=new Sb(l,!0,h.otherEvent,h.isSubject);return Cf(h.point,h.otherEvent.point)&&console.warn("what is that, a collapsed segment?",h),m.contourId=x.contourId=h.contourId,Rg(x,h.otherEvent)>0&&(h.otherEvent.left=!0,x.left=!1),h.otherEvent.otherEvent=x,h.otherEvent=m,u.push(x),u.push(m),u}function aN(h,l){return h[0]*l[1]-h[1]*l[0]}function K5(h,l){return h[0]*l[0]+h[1]*l[1]}function Y5(h,l,u){const m=function(C,O,z,U){const q=[O[0]-C[0],O[1]-C[1]],K=[U[0]-z[0],U[1]-z[1]];function X(He,$e,Ge){return[He[0]+$e*Ge[0],He[1]+$e*Ge[1]]}const J=[z[0]-C[0],z[1]-C[1]];let ne=aN(q,K),ae=ne*ne;const he=K5(q,q);if(ae>0){const He=aN(J,K)/ne;if(He<0||He>1)return null;const $e=aN(J,q)/ne;return $e<0||$e>1?null:He===0||He===1?[X(C,He,q)]:$e===0||$e===1?[X(z,$e,K)]:[X(C,He,q)]}if(ne=aN(J,q),ae=ne*ne,ae>0)return null;const ce=K5(q,J)/he,ye=ce+K5(q,K)/he,Ee=Math.min(ce,ye),ke=Math.max(ce,ye);return Ee<=1&&ke>=0?Ee===1?[X(C,Ee>0?Ee:0,q)]:ke===0?[X(C,ke<1?ke:1,q)]:[X(C,Ee>0?Ee:0,q),X(C,ke<1?ke:1,q)]:null}(h.point,h.otherEvent.point,l.point,l.otherEvent.point),x=m?m.length:0;if(x===0||x===1&&(Cf(h.point,l.point)||Cf(h.otherEvent.point,l.otherEvent.point))||x===2&&h.isSubject===l.isSubject)return 0;if(x===1)return!Cf(h.point,m[0])&&!Cf(h.otherEvent.point,m[0])&&Lg(h,m[0],u),!Cf(l.point,m[0])&&!Cf(l.otherEvent.point,m[0])&&Lg(l,m[0],u),1;const b=[];let S=!1,j=!1;return Cf(h.point,l.point)?S=!0:Rg(h,l)===1?b.push(l,h):b.push(h,l),Cf(h.otherEvent.point,l.otherEvent.point)?j=!0:Rg(h.otherEvent,l.otherEvent)===1?b.push(l.otherEvent,h.otherEvent):b.push(h.otherEvent,l.otherEvent),S&&j||S?(l.type=1,h.type=l.inOut===h.inOut?2:3,S&&!j&&Lg(b[1].otherEvent,b[0].point,u),2):j?(Lg(b[0],b[1].point,u),3):b[0]!==b[3].otherEvent?(Lg(b[0],b[1].point,u),Lg(b[1],b[2].point,u),3):(Lg(b[0],b[1].point,u),Lg(b[3].otherEvent,b[2].point,u),3)}function zje(h,l){if(h===l)return 0;if(W5(h.point,h.otherEvent.point,l.point)!==0||W5(h.point,h.otherEvent.point,l.otherEvent.point)!==0)return Cf(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 Rg(h,l)===1?1:-1}class $je{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Uje(h,l,u,m){let x,b=h+1,S=l[h].point;const j=l.length;for(bm;)b--;return b}function Vje(h,l,u){const m=new $je;if(h.prevInResult!=null){const x=h.prevInResult,b=x.outputContourId;if(x.resultTransition>0){const S=l[b];if(S.holeOf!=null){const j=S.holeOf;l[j].holeIds.push(u),m.holeOf=j,m.depth=l[b].depth}else l[b].holeIds.push(u),m.holeOf=b,m.depth=l[b].depth+1}else m.holeOf=null,m.depth=l[b].depth}else m.holeOf=null,m.depth=0;return m}const _Y=Math.max,vY=Math.min;let oN=0;function bY(h,l,u,m,x,b){let S,j,C,O,z,U;for(S=0,j=h.length-1;S0?U.left=!0:z.left=!0;const q=C[0],K=C[1];x[0]=vY(x[0],q),x[1]=vY(x[1],K),x[2]=_Y(x[2],q),x[3]=_Y(x[3],K),m.push(z),m.push(U)}}const lN=[];function wY(h,l,u){let m=h,x=l;typeof h[0][0][0]=="number"&&(m=[h]),typeof l[0][0][0]=="number"&&(x=[l]);let b=function(q,K,X){let J=null;return q.length*K.length===0&&(X===0?J=lN:X===2?J=q:(X===1||X===3)&&(J=q.length===0?K:q)),J}(m,x,u);if(b)return b===lN?null:b;const S=[1/0,1/0,-1/0,-1/0],j=[1/0,1/0,-1/0,-1/0],C=function(q,K,X,J,ne){const ae=new Yx(void 0,Rg);let he,ce,ye,Ee,ke,He;for(ye=0,Ee=q.length;yeJ[2]||J[0]>X[2]||X[1]>J[3]||J[1]>X[3])&&(ne===0?ae=lN:ne===2?ae=q:(ne===1||ne===3)&&(ae=q.concat(K))),ae}(m,x,S,j,u),b)return b===lN?null:b;const O=function(q,K,X,J,ne,ae){const he=new V5(zje),ce=[],ye=Math.min(J[2],ne[2]);let Ee,ke,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){ke=Ee=he.insert($e),He=he.minNode(),Ee=Ee!==He?he.prev(Ee):null,ke=he.next(ke);const Ge=Ee?Ee.key:null;let Ue;if(KE($e,Ge,ae),ke&&Y5($e,ke.key,q)===2&&(KE($e,Ge,ae),KE(ke.key,$e,ae)),Ee&&Y5(Ee.key,$e,q)===2){let Ve=Ee;Ve=Ve!==He?he.prev(Ve):null,Ue=Ve?Ve.key:null,KE(Ge,Ue,ae),KE($e,Ge,ae)}}else $e=$e.otherEvent,ke=Ee=he.find($e),Ee&&ke&&(Ee=Ee!==He?he.prev(Ee):null,ke=he.next(ke),he.remove($e),ke&&Ee&&Y5(Ee.key,ke.key,q))}return ce}(C,0,0,S,j,u),z=function(q){let K,X;const J=function(he){let ce,ye,Ee,ke,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 Ot(U,C+(U-j)/(O-j)*(z-C)))}:(S,j,C,O,z,U)=>{S.push(new Ot(j+(U-C)/(z-C)*(O-j),U))};for(const S of h){const j=[];for(const C of S){if(C.length<=2)continue;const O=[];for(let q=0;ql&&b(O,K,X,J,ne,l):ae>u?he=l&&b(O,K,X,J,ne,l),he>u&&ae<=u&&b(O,K,X,J,ne,u)}let z=C[C.length-1];const U=m===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]),j.push(O))}j.length&&x.push(j)}return x}function qje(h,l){const u=wY(Z5(h),Z5([l]),0);return u==null?[]:SY(u)}function Gje(h,l,u=0){let x=Z5(h,65536);const b=[];for(;l.valid();l.next()){const[S,j]=l.get();let C=S.x*65536,O=S.y*65536,z=j.x*65536,U=j.y*65536;const q=z-C,K=U-O,X=Math.hypot(q,K);if(X===0)continue;C-=q*u,O-=K*u,z+=q*u,U+=K*u;const J=Math.trunc(K/X*3),ne=-Math.trunc(q/X*3);b.push([[[C,O],[z,U],[z+J,U+ne],[C+J,O+ne],[C,O]]])}return b.length>0&&(x=wY(x,b,2)),SY(x,1/65536,128)}function Z5(h,l=1){return[h.map(u=>u.map(m=>[m.x*l,m.y*l]))]}function SY(h,l=1,u){return h.map(m=>m.map((x,b)=>{const S=x.map(j=>{let C=j[0],O=j[1];return u&&(C=Math.round(C/u)*u,O=Math.round(O/u)*u),new Ot(C*l,O*l)._round()});return b>0&&S.reverse(),S}))}class X5{constructor(l,u){this.layoutVertexArray=new uc,this.indexArray=new vs,this.lineIndexArray=new mu,this.triangleSegments=new ji,this.lineSegments=new ji,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.uploaded=!1,u&&(this.elevatedLayoutVertexArray=new kc)}update(l,u,m,x,b,S,j,C){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,j,C)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,Sje.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,Tje.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,m,x,b,S,j){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,u,m,x,b,S,void 0,j)}}class uN{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 X5(l,!1),this.elevationBufferData=new X5(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,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.hasPattern=$5("fill",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("fill-sort-key"),S=[];for(const{feature:j,id:C,index:O,sourceLayerIndex:z}of l){const U=this.layers[0]._featureFilter.needGeometry,q=wn(j,U);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,m))continue;const K=b?b.evaluate(q,{},m,u.availableImages):void 0,X={id:C,properties:j.properties,type:j.type,sourceLayerIndex:z,index:O,geometry:U?q.geometry:Ur(j,m,x),patterns:{},sortKey:K};S.push(X)}b&&S.sort((j,C)=>j.sortKey-C.sortKey);for(const j of S){const{geometry:C,index:O,sourceLayerIndex:z}=j;if(this.hasPattern){const U=U5("fill",this.layers,j,this.zoom,this.pixelRatio,u);this.patternFeatures.push(U)}else this.addFeature(j,C,O,m,{},u.availableImages,u.brightness,u.elevationFeatures);u.featureIndex.insert(l[O].feature,C,O,z,this.index)}}update(l,u,m,x,b,S,j){this.bufferData.update(l,u,m,x,b,S,j,this.worldview),this.elevationBufferData.update(l,u,m,x,b,S,j,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(l,u,m,x,b,S,j,this.worldview)}addFeatures(l,u,m,x,b,S){for(const j of this.patternFeatures)this.addFeature(j,j.geometry,j.index,u,m,x,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,m,x,b,S=[],j,C){const O=HE(u,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(l,O,x,m,C):this.addGeometry(O,this.bufferData),this.bufferData.populatePaintArrays(l,m,b,S,x,j,this.worldview),this.elevationBufferData.populatePaintArrays(l,m,b,S,x,j,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(l,u,m,x,b){this.elevatedStructures&&(this.elevatedStructures.construct(l),this.elevatedStructures.populatePaintArrays(u,m,x,b,this.worldview))}addElevatedRoadFeature(l,u,m,x,b){const S=new Array,j=Li.getElevationFeature(l,b);if(!j)return void this.addGeometry(u,this.bufferData);{const O=this.clipPolygonsToTile(u,1);O.length>0&&S.push({polygons:O,elevationFeature:j,elevationTileID:m})}const C={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(l,{},m),featureIndex:x};for(const O of S)if(O.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Pc(O.elevationTileID,this.layers,this.zoom,this.lut));const U=O.elevationFeature.isTunnel();let q=0;l.properties.hasOwnProperty(Ci)&&(q=+l.properties[Ci]),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 $i(m,O.elevationTileID);this.addElevatedGeometry(O.polygons,z,O.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,x,C)}}addElevatedGeometry(l,u,m,x,b,S){const j={elevation:m,elevationSampler:u,bias:x,index:b,featureInfo:S},[C,O]=this.addGeometry(l,this.elevationBufferData,j);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:C,max:O}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,C),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,O))}addGeometry(l,u,m){let x=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,S=null;m&&(S=m.elevationSampler.constantElevation(m.elevation,m.bias),S!=null&&(x=S,b=S));const j=(C,O,z)=>{if(m!=null)if(O.push(C),S!=null)u.elevatedLayoutVertexArray.emplaceBack(S),z.push(S);else{const U=m.elevationSampler.pointElevation(C,m.elevation,m.bias);u.elevatedLayoutVertexArray.emplaceBack(U),z.push(U),x=Math.min(x,U),b=Math.max(b,U)}};for(const C of l){let O=0;for(const ce of C)O+=ce.length;const z=u.triangleSegments.prepareSegment(O,u.layoutVertexArray,u.indexArray),U=z.vertexLength,q=[],K=[],X=[],J=[],ne=[],ae=u.layoutVertexArray.length;for(const ce of C){if(ce.length===0)continue;ce!==C[0]&&K.push(q.length/2);const ye=u.lineSegments.prepareSegment(ce.length,u.layoutVertexArray,u.lineIndexArray),Ee=ye.vertexLength;m&&ne.push(u.layoutVertexArray.length-ae),j(ce[0],X,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 ke=1;ke0&&m&&this.elevationMode==="hd-road-base"){const ce=m.elevation.isTunnel(),ye=m.elevation.safeArea,Ee=this.elevatedStructures.addVertices(X,J);this.elevatedStructures.addTriangles(he,Ee,ce);const ke=ne.length;if(ke>0){for(let He=0;He=m&&K.max.x<=b&&K.min.y>=x&&K.max.y<=S?C:O).push(q)}if(C.length===l.length)return l;const z=[new Ot(m,x),new Ot(b,x),new Ot(b,S),new Ot(m,S),new Ot(m,x)],U=C;for(const q of O)U.push(...qje(q,z));return U}}let TY,EY,AY,jY;br(uN,"FillBucket",{omit:["layers","patternFeatures"]}),br(X5,"FillBufferData"),br(Pc,"ElevatedStructures");class dN{constructor(l,u,m,x){if(this.triangleCount=u.length/3,this.min=new Ot(0,0),this.max=new Ot(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 m=If(l.x-this.min.x,this.xScale,this.cellsX),x=If(l.y-this.min.y,this.yScale,this.cellsY),b=this.cells[x*this.cellsX+m];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 x=If(l.x-this.min.x,this.xScale,this.cellsX),b=If(u.x-this.min.x,this.xScale,this.cellsX),S=If(l.y-this.min.y,this.yScale,this.cellsY),j=If(u.y-this.min.y,this.yScale,this.cellsY);for(let C=S;C<=j;C++)for(let O=x;O<=b;O++){const z=this.cells[C*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 m of this.footprints)u.push({footprint:m,id:l})}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){const b=[];for(const{feature:S,id:j,index:C,sourceLayerIndex:O}of l){const z=this.layers[0]._featureFilter.needGeometry,U=wn(S,z);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),U,m))continue;const q={id:j,properties:S.properties,type:S.type,sourceLayerIndex:O,index:C,geometry:z?U.geometry:Ur(S,m,x),patterns:{}};b.push(q)}for(const S of b){const{geometry:j,index:C,sourceLayerIndex:O}=S;this.addFeature(S,j,C,m,{},u.availableImages,u.brightness),u.featureIndex.insert(l[C].feature,j,C,O,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(l){}update(l,u,m,x,b,S,j){}destroy(){}addFeature(l,u,m,x,b,S=[],j){for(const C of HE(u,2)){const O=[],z=[],U=[],q=new Ot(1/0,1/0),K=new Ot(-1/0,-1/0);for(const ne of C)if(ne.length!==0){ne!==C[0]&&U.push(z.length/2);for(let ae=0;ael.max.x||h.max.xl.max.y||h.max.ynew Ot((C.x+b.x*ar)*j-S.x*ar,(C.y+b.y*ar)*j-S.y*ar))}return J5(u,x,h.indices,0,h.indices.length,0,0)}function RY(h,l,u,m){const x=Math.pow(2,m.z-u.z);return new Ot((h+u.x*ar)*x-m.x*ar,(l+u.y*ar)*x-m.y*ar)}function LY(h,l){const u=[];l.grid.queryPoint(h,u);const m=l.indices,x=l.vertices;for(let b=0;b0&&(m.length>1&&u.push(m),m=[])}return m.length>1&&u.push(m),u}const t4=tn.types,rke=["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"],nke=["fill-extrusion-flood-light-ground-radius"],ike=Math.pow(2,13),ske=Math.pow(2,15)-1,pN=new Ot(0,1),Jm=2147483648,gN=1073741824;function ZE(h,l,u,m,x,b,S,j){h.emplaceBack((l<<1)+S,(u<<1)+b,(Math.floor(m*ike)<<1)+x,Math.round(j))}function XE(h,l,u){h.emplaceBack(l.x*ar,l.y*ar,u?1:0)}function yN(h,l,u,m,x,b){h.emplaceBack(l.x,l.y,(u.x<<1)+m,(u.y<<1)+x,b)}function QE(h,l,u){h.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}class MY{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class r4{constructor(){this.centroidXY=new Ot(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 Ot(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ot(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ot(0,0)}span(){return new Ot(this.max.x-this.min.x,this.max.y-this.min.y)}}class n4{constructor(){this.acc=new Ot(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,m){this.accCount++,this.acc._add(u);let x=!!this.borders;u.xl.max.x&&(l.max.x=u.x,x=!0),u.yl.max.y&&(l.max.y=u.y,x=!0),((u.x===0||u.x===ar)&&u.x===m.x)!=((u.y===0||u.y===ar)&&u.y===m.y)&&this.processBorderOverlap(u,m),x&&this.checkBorderIntersection(u,m)}checkBorderIntersection(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 m=this.borders[l];um[1]&&(m[1]=u)}processBorderOverlap(l,u){if(l.x===u.x){if(l.y===u.y)return;const m=l.x===0?0:1;this.addBorderIntersection(m,u.y),this.addBorderIntersection(m,l.y)}else{const m=l.y===0?2:3;this.addBorderIntersection(m,u.x),this.addBorderIntersection(m,l.x)}}centroid(){return this.accCount===0?new Ot(0,0):new Ot(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 OY(h,l){const u=h.add(l)._unit(),m=fe(h.x*u.x+h.y*u.y,-1,1);var x,b,S;return S=Math.acos(m),Math.min(4,Math.max(-4,Math.tan(S)))/4*ske*((x=h).x*(b=l).y-x.y*b.x<0?-1:1)}const ake=[h=>h.x<0,h=>h.x>ar,h=>h.y<0,h=>h.y>ar];function oke(h,l,u,m){const x=[4];if(m===0)return x;u._mult(m);const b=h.sub(u),S=l.sub(u),j=[h,l,b,S];for(let C=0;C<4;C++)for(const O of j)if(ake[C](O)){x.push(C);break}return x}class i4{constructor(l){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new TE,this.indexArray=new vs,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>nke.includes(u)),this._segments=new ji,this.hiddenByLandmarkVertexArray=new pb,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new ji}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(l,u,m,x=!1){const b=l.length;if(b>2){let S=Math.max(0,this._segments.get().length-1);const j=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[S].length);let C;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];C=OY(O.sub(l[b-1])._perp()._unit(),z.sub(O)._perp()._unit())}for(let O=0;Ox.region-b.region);for(let m=0;mC+O,0);let j=0;for(let C=0;C<=4;C++){const O=S[C];if(O!==0){let z=this.regionSegments[C];z||(z=this.regionSegments[C]=new ji);const U={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+j,vertexLength:b.vertexLength,primitiveLength:O};z.get().push(U)}j+=O}for(let C=0;C0?this.hiddenByLandmarkVertexBuffer=l.createVertexBuffer(this.hiddenByLandmarkVertexArray,Xje.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 xN{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 vs,this.footprintVertices=new uc,this.footprintSegments=[],this.layoutVertexArray=new SE,this.centroidVertexArray=new XI,this.wallVertexArray=new ME,this.indexArray=new vs,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>rke.includes(u)),this.segments=new ji,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.groundEffect=new i4(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,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.features=[],this.hasPattern=$5("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(m),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:b,id:S,index:j,sourceLayerIndex:C}of l){const O=this.layers[0]._featureFilter.needGeometry,z=wn(b,O);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),z,m))continue;const U={id:S,sourceLayerIndex:C,index:j,geometry:O?z.geometry:Ur(b,m,x),properties:b.properties,type:b.type,patterns:{}},q=this.layoutVertexArray.length,K=t4[U.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:b.id,feature:U5("fill-extrusion",this.layers,U,this.zoom,this.pixelRatio,u)});else if(this.wallMode)for(const X of U.geometry)for(const J of DY(X,K))this.addFeature(b.id,U,[J],j,m,{},u.availableImages,x,u.brightness);else this.addFeature(b.id,U,U.geometry,j,m,{},u.availableImages,x,u.brightness);u.featureIndex.insert(b,U.geometry,j,C,this.index,q)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(l,u,m,x,b,S){for(const{featureId:j,feature:C}of this.features){const O=t4[C.type]==="Polygon",{geometry:z}=C;if(this.wallMode)for(const U of z)for(const q of DY(U,O))this.addFeature(j,C,[q],C.index,u,m,x,b,S);else this.addFeature(j,C,z,C.index,u,m,x,b,S)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(l,u,m,x,b,S,j){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,j,this.worldview),this.groundEffect.update(l,u,b,m,x,S,j,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,Jje),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.wallVertexBuffer=l.createVertexBuffer(this.wallVertexArray,Zje.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=l.createVertexBuffer(this.layoutVertexExtArray,Qje.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,Yje.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,m,x,b,S,j,C,O){const z=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(u,{})/this.tileToMeter,U=[new Ot(0,0),new Ot(ar,ar)],q=C.projection,K=q.name==="globe",X=this.wallMode||t4[u.type]==="Polygon",J=new n4;J.centroidDataIndex=this.centroidData.length;const ne=new r4;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 cb),this.wallMode){if(K)return void Br("Non zero fill-extrusion-line-width is not yet supported on globe.");if(m.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 Yt=0;const pr=nr.length;for(let jr=0;jr=0})(Ue)||(Ue=Ue.reverse());const wt={geometry:[],joinNormals:[],indices:[]},jt=[],It=[],kt=[];let Bt=Ue.length;for(;Bt>=2&&Ue[Bt-1].equals(Ue[Bt-2]);)Bt--;if(Bt<(Ve?3:2))return wt;let mt,Ct,Lt,Ut,Kt,_r=0;for(;_r0;let Rr="miter";const ln=2;Rr==="miter"&&jr>ln&&(Rr="bevel"),Rr==="bevel"&&(jr>100&&(Rr="flipbevel"),jr{const ni=new Ot(cn.x,cn.y),Hn=new Ot(cn.x,cn.y);ni.x+=Vn.x*fs,ni.y+=Vn.y*fs,Hn.x-=Vn.x*Math.max(Sn,1),Hn.y-=Vn.y*Math.max(Sn,1),kt.push(Vn),jt.push(ni),It.push(Hn)};if(Rr==="miter")Yt._mult(jr),$n(mt,Yt,0,0);else if(Rr==="flipbevel")Yt=Kt.mult(-1),$n(mt,Yt,0,0),$n(mt,Yt.mult(-1),0,0);else{const cn=-Math.sqrt(jr*jr-1),Vn=zr?cn:0,Sn=zr?0:cn;Ct&&$n(mt,Ut,Vn,Sn),Lt&&$n(mt,Kt,Vn,Sn)}}wt.geometry=[...jt,...It.reverse(),jt[0]],wt.joinNormals=[...kt,...kt.reverse(),kt[kt.length-1]];const ir=wt.geometry.length-1;for(let nr=0;nrUe<(Ve.length-1)/2||Ue===Ve.length-1,Ee=this.wallMode?[m]:HE(m,500);for(let Ue=Ee.length-1;Ue>=0;Ue--){const Ve=Ee[Ue];(Ve.length===0||cke(Ve[0]))&&Ee.splice(Ue,1)}let ke;if(K)ke=qY(Ee,U,b);else{ke=[];for(const Ue of Ee)ke.push({polygon:Ue,bounds:U})}const He=X?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 ke){let yt=0,wt=0;for(const Bt of Ue)X&&!Bt[0].equals(Bt[Bt.length-1])&&Bt.push(Bt[0]),wt+=X?Bt.length-1:Bt.length;const jt=this.segments.prepareSegment((X?5:4)*wt,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},kt=new MY;if(kt.vertexOffset=this.footprintVertices.length,kt.indexOffset=3*this.footprintIndices.length,kt.ringIndices=[],X){const Bt=[],mt=[];yt=jt.vertexLength;for(let Lt=0;Lt4&&$Y(mt[mt.length-2],mt[0],mt[1]),Lt=He?lke(mt[mt.length-2],mt[0],mt[1],He):0;const Ut=[];let Kt,_r,ir;_r=mt[1].sub(mt[0])._perp()._unit();let nr=!0;for(let Yt=1,pr=0;Yt0?1:0,Vn=jr.dist(zr);if(pr+Vn>32768&&(pr=0),He){ir=Rr.sub(zr)._perp()._unit();let Hn=BY(jr,zr,Rr,FY(_r,ir),He);isNaN(Hn)&&(Hn=0);const Ii=zr.sub(jr)._unit();jr=jr.add(Ii.mult(Lt))._round(),zr=zr.add(Ii.mult(-Hn))._round(),Lt=Hn,_r=ir,ae&&this.zoom>=17&&(Ge(Ut,jr)||Ut.push(jr),Ge(Ut,zr)||Ut.push(zr))}const Sn=jt.vertexLength,fs=mt.length>4&&$Y(jr,zr,Rr);let ni=UY(pr,Ct,nr);if(ZE(this.layoutVertexArray,jr.x,jr.y,$n,cn,0,0,ni),ZE(this.layoutVertexArray,jr.x,jr.y,$n,cn,0,1,ni),this.wallMode){const Hn=ye(Yt-1,mt),Ii=ce.joinNormals[Yt-1];XE(this.wallVertexArray,Ii,Hn),XE(this.wallVertexArray,Ii,Hn)}if(pr+=Vn,ni=UY(pr,fs,!nr),Ct=fs,ZE(this.layoutVertexArray,zr.x,zr.y,$n,cn,0,0,ni),ZE(this.layoutVertexArray,zr.x,zr.y,$n,cn,0,1,ni),this.wallMode){const Hn=ye(Yt,mt),Ii=ce.joinNormals[Yt];XE(this.wallVertexArray,Ii,Hn),XE(this.wallVertexArray,Ii,Hn)}if(jt.vertexLength+=4,this.indexArray.emplaceBack(Sn+0,Sn+1,Sn+2),this.indexArray.emplaceBack(Sn+1,Sn+3,Sn+2),jt.primitiveLength+=2,He){const Hn=yt+(Yt===1?mt.length-2:Yt-2),Ii=Yt===1?yt:Hn+1;if(this.indexArray.emplaceBack(Sn+1,Hn,Sn+3),this.indexArray.emplaceBack(Hn,Ii,Sn+3),jt.primitiveLength+=2,Kt===void 0&&(Kt=Sn),!s4(Rr,mt[Yt],Ve)){const ls=Yt===mt.length-1?Kt:jt.vertexLength;this.indexArray.emplaceBack(Sn+2,Sn+3,ls),this.indexArray.emplaceBack(Sn+3,ls+1,ls),this.indexArray.emplaceBack(Sn+3,Ii,ls+1),jt.primitiveLength+=3}nr=!nr}if(K){const Hn=this.layoutVertexExtArray,Ii=q.projectTilePoint(jr.x,jr.y,b),ls=q.projectTilePoint(zr.x,zr.y,b),Oa=q.upVector(b,jr.x,jr.y),cs=q.upVector(b,zr.x,zr.y);QE(Hn,Ii,Oa),QE(Hn,Ii,Oa),QE(Hn,ls,cs),QE(Hn,ls,cs)}}X&&(yt+=mt.length-1),ae&&He&&this.zoom>=17&&(Ut.length!==0&&Ge(Ut,Ut[0])&&Ut.pop(),this.groundEffect.addData(Ut,Ve,z,He>0))}this.footprintSegments.push(kt),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?pN: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 Ot(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ot(-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[m].borders[l][0])}splitToSubtiles(){const l=[];for(let j=0;jar),z=2*O+(+(C.min.x+C.max.x>ar)^O);for(let U=0;Uj.triangleSegmentIdx===C.triangleSegmentIdx?j.subtile-C.subtile:j.triangleSegmentIdx-C.triangleSegmentIdx);let m=0,x=0,b=0;for(const j of l){if(j.triangleSegmentIdx!==m)break;b++}const S=l.length;for(;x!==l.length;){m=l[x].triangleSegmentIdx;let j=0,C=x,O=x;for(let z=C;z0&&this.triangleSubSegments.push({segment:K,min:U,max:q}),C=O;for(let X=C;X[J[0]*(1-ae[0])+ne[0]*ae[0],J[1]*(1-ae[1])+ne[1]*ae[1]],K=[],X=[];for(const J of this.triangleSubSegments){K[0]=J.min.x/ar,K[1]=J.min.y/ar,X[0]=J.max.x/ar,X[1]=J.max.y/ar;const ne=q(z,U,K),ae=q(z,U,X);if(new oi([ne[0],ne[1],b],[ae[0],ae[1],S]).intersectsPrecise(m)===0){O&&(x.segments.push(O),O=void 0);continue}const he=J.segment;O&&O.vertexOffset!==he.vertexOffset&&(x.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&&x.segments.push(O),x}encodeCentroid(l,u){const m=l.centroid(),x=u.span(),b=Math.min(7,Math.round(x.x*this.tileToMeter/10)),S=Math.min(6,Math.round(x.y*this.tileToMeter/10));return new Ot(fe(m.x,1,8191)<<3|b,fe(m.y,1,8191)<<3|S)}encodeBorderCentroid(l){if(!l.borders)return new Ot(0,0);const u=l.borders,m=Number.MAX_VALUE;if(u[0][0]!==m||u[1][0]!==m){const x=u[0][0]!==m?0:1;return new Ot(6|(u[0][0]!==m?0:65528),(u[x][0]+u[x][1])/2<<3|6)}{const x=u[2][0]!==m?2:3;return new Ot((u[x][0]+u[x][1])/2<<3|6,6|(u[2][0]!==m?0:65528))}}showCentroid(l){const u=this.centroidData[l.centroidDataIndex];if(u.flags&=Jm,u.groupCentroidPos.x!==0||u.groupCentroidPos.y!==0){const m=u.span(),x=Math.min(7,Math.round(m.x*this.tileToMeter/10)),b=Math.min(6,Math.round(m.y*this.tileToMeter/10));u.centroidXY=new Ot(fe(u.groupCentroidPos.x,1,8191)<<3|x,fe(u.groupCentroidPos.y,1,8191)<<3|b)}else u.centroidXY=new Ot(0,0);this.writeCentroidToBuffer(u)}writeCentroidToBuffer(l){this.groundEffect.updateHiddenByLandmark(l);const u=l.vertexArrayOffset,m=l.vertexCount+l.vertexArrayOffset,x=-1073741824&l.flags?pN:l.centroidXY,b=this.centroidVertexArray.geta_centroid_pos0(u);if(this.centroidVertexArray.geta_centroid_pos1(u)!==x.y||b!==x.x){for(let S=u;SC.max.x||C.min.x>S.max.x||S.min.y>C.max.y||C.min.y>S.max.y||S.footprint.buildingIds.has(C.buildingId)&&(C.flags|=S.clipMask!==mN.None?-1073741824:Jm);else for(const C of this.centroidData)if(!(C.flags&Jm||C.flags&gN||S.min.x>C.max.x||C.min.x>S.max.x||S.min.y>C.max.y||C.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&&(x=!x)}j=C}}return x}getHeightAtTileCoord(l,u){let m=Number.NEGATIVE_INFINITY,x=!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&Jm)}: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<=m||this.footprintContainsPoint(l,u,S)&&(m=S.height,this.partLookup[b]=S,x=!!(S.flags&Jm));if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.partLookup[b]=void 0}}function FY(h,l){const u=h.add(l)._unit();return h.x*u.x+h.y*u.y}function lke(h,l,u,m){const x=l.sub(h)._perp()._unit(),b=u.sub(l)._perp()._unit();return BY(h,l,u,FY(x,b),m)}function BY(h,l,u,m,x){const b=Math.sqrt(1-m*m);return Math.min(h.dist(l)/3,l.dist(u)/3,x*b/m)}function s4(h,l,u){return h.xu[1].x&&l.x>u[1].x||h.yu[1].y&&l.y>u[1].y}function zY(h,l){return h.xl[1].x||h.yl[1].y}function cke(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 $Y(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 m=u.sub(l),x=m.perp(),b=h.sub(l);return(m.x*b.x+m.y*b.y)/Math.sqrt((m.x*m.x+m.y*m.y)*(b.x*b.x+b.y*b.y))>-.866&&x.x*b.x+x.y*b.y<0}function UY(h,l,u){const m=l?2|h:-3&h;return u?1|m:-2&m}function VY(){const h=Math.PI/32,l=Math.tan(h),u=qe;return u*Math.sqrt(1+2*l*l)-u}function qY(h,l,u){const m=1<{for(const $e of ke)X.push({polygon:$e,bounds:He})},ne=Math.ceil(Math.log2(z)),ae=Math.ceil(Math.log2(U)),he=ne-ae,ce=[];for(let ke=0;ke0?0:1);for(let ke=0;keHe+1?Ee.push({polygons:jt,bounds:kt,depth:He+1}):J(jt,kt)}if(It.length){const kt=[new Ot($e===0?wt:Ge.x,$e===1?wt:Ge.y),Ue];ce.length>He+1?Ee.push({polygons:It,bounds:kt,depth:He+1}):J(It,kt)}}return X}(h,l,Math.ceil((b-x)/11.25),Math.ceil((S-j)/11.25),1,(C,O,z)=>{if(C===0)return .5*(O+z);{const U=gt((u.y+O/ar)/m);return(Ft(.5*(gt((u.y+z/ar)/m)+U))*m-u.y)*ar}})}function uke(h,l,u,m,x,b){const S=Math.pow(2,m.z-x.z);for(let j=0;j=C[S]&&(j=l,C=h),j[S]x&&KY(j,C,S,x),j[S]b&&KY(C,j,S,b)}}function _N(h,l,u,m,x,b){const S=[];for(let j=0;j=m&&X.x>=m||(K.x>=m?K=new Ot(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round():X.x>=m&&(X=new Ot(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round()),K.y>=x&&X.y>=x||(K.y>=x?K=new Ot(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round():X.y>=x&&(X=new Ot(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round()),O&&K.equals(O[O.length-1])||(O=[K],S.push(O),b&&b.push({progress:{min:ne+ZY(ae,he,K)*J,max:1},parentIndex:j,prevPoint:ae,nextPoint:he})),O.push(X),b&&(b[b.length-1].progress.max=ne+ZY(ae,he,X)*J,b[b.length-1].nextPoint=he)))))}if(b&&U>0)for(let q=z;qO.t-z.t);let S=0,j=0,C=[];for(m.push(C);S!==h.length;){if(j===b.length){for(;S!==h.length;)C.length!==0&&C[C.length-1].equals(h[S])||C.push(h[S]),S++;break}b[j].t<=S?(C.length!==0&&C[C.length-1].equals(b[j].point)||C.push(b[j].point),Math.trunc(b[j].t),j++):(C.length!==0&&C[C.length-1].equals(h[S])||C.push(h[S]),S++)}}function ZY(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 JE(h,l){return h.x*l.x+h.y*l.y}function XY(h,l){if(h.length===1){let u=0;const m=l[u++];let x;for(;!x||m.equals(x);)if(x=l[u++],!x)return 1/0;for(;u{wt[0]=jt,wt[1]=It,wt[2]=kt,wt[3]=1},yt=VY();K>0&&(K+=yt),X+=yt;for(const wt of q){const jt=[],It=[];for(const kt of wt){const Bt=kt.x+J.x,mt=kt.y+J.y,Ct=U.projection.projectTilePoint(Bt,mt,Ee),Lt=U.projection.upVector(Ee,kt.x,kt.y);let Ut=K,Kt=X;if(ae){const _r=eZ(Bt,mt,K,X,ae,he,ce,ye);Ut+=_r.base,Kt+=_r.top}K!==0?Ve(Ge,Ct.x+Lt[0]*$e*Ut,Ct.y+Lt[1]*$e*Ut,Ct.z+Lt[2]*$e*Ut):Ve(Ge,Ct.x,Ct.y,Ct.z),Ve(Ue,Ct.x+Lt[0]*$e*Kt,Ct.y+Lt[1]*$e*Kt,Ct.z+Lt[2]*$e*Kt),or(Ge,Ge,ne),or(Ue,Ue,ne),jt.push(new C0(Ge[0],Ge[1],Ge[2])),It.push(new C0(Ue[0],Ue[1],Ue[2]))}ke.push(jt),He.push(It)}return[ke,He]}(h,l,u,m,x,b,S,j,C,O,z):S?function(U,q,K,X,J,ne,ae,he,ce){const ye=[],Ee=[],ke=[0,0,0,1];for(const He of U){const $e=[],Ge=[];for(const Ue of He){const Ve=Ue.x+X.x,yt=Ue.y+X.y,wt=eZ(Ve,yt,q,K,ne,ae,he,ce);ke[0]=Ve,ke[1]=yt,ke[2]=wt.base,ke[3]=1,hr(ke,ke,J),ke[3]=Math.max(ke[3],1e-5);const jt=new C0(ke[0]/ke[3],ke[1]/ke[3],ke[2]/ke[3]);ke[0]=Ve,ke[1]=yt,ke[2]=wt.top,ke[3]=1,hr(ke,ke,J),ke[3]=Math.max(ke[3],1e-5);const It=new C0(ke[0]/ke[3],ke[1]/ke[3],ke[2]/ke[3]);$e.push(jt),Ge.push(It)}ye.push($e),Ee.push(Ge)}return[ye,Ee]}(l,u,m,x,b,S,j,C,O):function(U,q,K,X,J){const ne=[],ae=[],he=J[8]*q,ce=J[9]*q,ye=J[10]*q,Ee=J[11]*q,ke=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 wt of Ue){const jt=wt.x+X.x,It=wt.y+X.y,kt=J[0]*jt+J[4]*It+J[12],Bt=J[1]*jt+J[5]*It+J[13],mt=J[2]*jt+J[6]*It+J[14],Ct=J[3]*jt+J[7]*It+J[15],Lt=kt+he,Ut=Bt+ce,Kt=mt+ye,_r=Math.max(Ct+Ee,1e-5),ir=kt+ke,nr=Bt+He,Yt=mt+$e,pr=Math.max(Ct+Ge,1e-5);Ve.push(new C0(Lt/_r,Ut/_r,Kt/_r)),yt.push(new C0(ir/pr,nr/pr,Yt/pr))}ne.push(Ve),ae.push(yt)}return[ne,ae]}(l,u,m,x,b)}function eZ(h,l,u,m,x,b,S,j){const C=S*x.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 X=Math.floor(q[0]/8),J=Math.floor(q[1]/8),ne=10*(q[0]-8*X),ae=10*(q[1]-8*J),he=U.getElevationAt(X,J,!0,!0),ce=U.getMeterToDEM(K),ye=Math.floor(.5*(ne*ce-1)),Ee=Math.floor(.5*(ae*ce-1)),ke=U.tileCoordToPixel(X,J),He=2*ye+1,$e=2*Ee+1,Ge=function(It,kt,Bt,mt,Ct){return[It.getElevationAtPixel(kt,Bt,!0),It.getElevationAtPixel(kt+Ct,Bt,!0),It.getElevationAtPixel(kt,Bt+Ct,!0),It.getElevationAtPixel(kt+mt,Bt+Ct,!0)]}(U,ke.x-ye,ke.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]),wt=Math.min(.25,.5*ce*(Ue+Ve)/He),jt=Math.min(.25,.5*ce*yt/$e);return he+Math.max(wt*ne,jt*ae)}(x,b,j):C;return{base:C+(u===0?-1:u),top:O?Math.max(z+m,C+u+2):C+m}}const a4=4096;class hke{constructor(l){this.module=l,this.memoryStack=this.module.malloc(a4),this.memoryStackNextFree=this.memoryStack}createIntArray(l){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>a4?-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>a4?-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,m){this.module.setFauxFacadeOptions(l?1:0,u?1:0,m)}setFacadeClassifierOptions(l){this.module.setFacadeClassifierOptions(l)}generateMesh(l,u){this.memoryStackNextFree=this.memoryStack;for(const j of l){const C=this.createIntArray(j.ringIndices),O=this.createFloatArray(j.coordinates);if(C===-1||O===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(j.id,j.sourceId,j.minHeight,j.height,j.roofType,O,C,j.ringIndices.length-1)}for(const j of u){let C;C=j.entrances?JSON.parse(j.entrances):[];const O=this.createFloatArray(C),z=this.createFloatArray(j.coordinates);if(O===-1||z===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(j.sourceId,j.crossPerc,j.distanceToRoad,O,C.length,z,j.coordinates.length)}if(!this.module.generateMesh()){const j=this.module.getLastError();return this.readStringBuffer(j)}const m=this.module.getMeshCount(),x=new Array(m);for(let j=0;j>2)-3,ne=K[X++]>>2;if(X++,x.json=JSON.parse(uZ.decode(K.subarray(X,X+ne))),X+=ne,X>>0,Math.ceil(1.2*ye)),ke=Math.ceil((Ee-ye)/65536);try{return J.grow(ke),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:ke,T:He,X:$e,Ja:Ge,La:Ue,Qa:Ve,Va:yt,Wa:wt,eb:jt,jb:It,f:kt,e:Bt,yb:mt,zb:Ct,Ab:Lt,Bb:Ut,Db:Kt,Gb:_r}=ce.instance.exports;J=Bt;const ir=(()=>{let nr=0,Yt=0,pr=0,jr=0;return zr=>{pr&&(ye(jr),ye(nr),Yt+=pr,pr=nr=0),nr||(Yt+=128,nr=Ee(Yt));const Rr=zr.length+7&-8;let ln=nr;Rr>=Yt&&(pr=Rr,ln=jr=Ee(Rr));for(let $n=0;$n{Sh=K,e2=void 0}))}()),q&&z.push(function(){if(o4)return;const K=function(X){let J;const ne=WebAssembly.instantiateStreaming(X,{}).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,ke,He,$e){(function(Ge,Ue,Ve,yt,wt,jt,It){const kt=Ge.exports.sbrk,Bt=yt+3&-4,mt=kt(Bt*wt),Ct=kt(jt.length),Lt=new Uint8Array(Ge.exports.memory.buffer);Lt.set(jt,Ct);const Ut=Ue(mt,yt,wt,Ct,jt.length);if(Ut===0&&It&&It(mt,Bt,wt),Ve.set(Lt.subarray(mt,mt+yt*wt)),kt(mt-kt(0)),Ut!==0)throw new Error(`Malformed buffer data: ${Ut}`)})(J,J.exports[he[He]],ce,ye,Ee,ke,J.exports[ae[$e]])}}}(fetch(vo()));return K.ready.then(()=>{o4=K})}()),S)for(let K=0;K{const j=ig(m,(C,O)=>{C?S(C):b(O)});x&&x.addEventListener("abort",()=>{j.cancel(),S(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:h,type:"arrayBuffer"},l);return fZ(u,0,h,l)}function c4(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 u4(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 Nf{constructor(l,u,m,x){this.context=l,this.format=m,this.useMipmap=x&&x.useMipmap,this.texture=l.gl.createTexture(),this.update(u,{premultiply:x&&x.premultiply})}update(l,u){const m=l&&l instanceof HTMLVideoElement&&l.width===0?l.videoWidth:l.width,x=l&&l instanceof HTMLVideoElement&&l.height===0?l.videoHeight:l.height,{context:b}=this,{gl:S}=b,{x:j,y:C}=u&&u.position?u.position:{x:0,y:0},O=j+m,z=C+x;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,j,C,c4(this.format),u4(this.format),l):"data"in l&&l.data&&S.texSubImage2D(S.TEXTURE_2D,0,j,C,m,x,c4(this.format),u4(this.format),l.data)),this.useMipmap&&S.generateMipmap(S.TEXTURE_2D)}bind(l,u,m=!1){const{context:x}=this,{gl:b}=x;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&&!m?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,m,x,b){const{context:S}=this,{gl:j}=S;j.bindTexture(j.TEXTURE_2D,this.texture),u!==this.magFilter&&(j.texParameteri(j.TEXTURE_2D,j.TEXTURE_MAG_FILTER,u),this.magFilter=u),l!==this.minFilter&&(j.texParameteri(j.TEXTURE_2D,j.TEXTURE_MIN_FILTER,this.useMipmap?l===j.NEAREST?j.NEAREST_MIPMAP_NEAREST:j.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),m!==this.wrapS&&(j.texParameteri(j.TEXTURE_2D,j.TEXTURE_WRAP_S,m),this.wrapS=m),x!==this.wrapT&&(j.texParameteri(j.TEXTURE_2D,j.TEXTURE_WRAP_T,x),this.wrapT=x),b!==this.compareMode&&(b?(j.texParameteri(j.TEXTURE_2D,j.TEXTURE_COMPARE_MODE,j.COMPARE_REF_TO_TEXTURE),j.texParameteri(j.TEXTURE_2D,j.TEXTURE_COMPARE_FUNC,b)):j.texParameteri(j.TEXTURE_2D,j.TEXTURE_COMPARE_MODE,j.NONE),this.compareMode=b)}destroy(){const{gl:l}=this.context;l.deleteTexture(this.texture),this.texture=null}}class r2{constructor(l,u){this.context=l,this.texture=u}bind(l,u){const{context:m}=this,{gl:x}=m;x.bindTexture(x.TEXTURE_2D,this.texture),l!==this.minFilter&&(x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,l),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,l),this.minFilter=l),u!==this.wrapS&&(x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,u),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,u),this.wrapS=u)}}const _ke=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),vke=Pn([{name:"a_color_3f",components:3,type:"Float32"}]),bke=Pn([{name:"a_color_4f",components:4,type:"Float32"}]),wke=Pn([{name:"a_uv_2f",components:2,type:"Float32"}]),Ske=Pn([{name:"a_normal_3f",components:3,type:"Float32"}]),Tke=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"}]),Eke=Pn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function pZ(h,l){const u=SN(h.projection,h.zoom,h.width,h.height),m=function(b,S,j,C,O){const z=new Qe(j.lng-180*Dg,j.lat),U=new Qe(j.lng+180*Dg,j.lat),q=b.project(z.lng,z.lat),K=b.project(U.lng,U.lat),X=-Math.atan2(K.y-q.y,K.x-q.x),J=Ar.fromLngLat(j);J.y=fe(J.y,-1+Dg,1-Dg);const ne=J.toLngLat(),ae=b.project(ne.lng,ne.lat),he=Ar.fromLngLat(ne);he.x+=Dg;const ce=he.toLngLat(),ye=b.project(ce.lng,ce.lat),Ee=yZ(ye.x-ae.x,ye.y-ae.y,X),ke=Ar.fromLngLat(ne);ke.y+=Dg;const He=ke.toLngLat(),$e=b.project(He.lng,He.lat),Ge=yZ($e.x-ae.x,$e.y-ae.y,X),Ue=Math.abs(Ee.x)/Math.abs(Ge.y),Ve=R([]);Z(Ve,Ve,-X*(1-(O?0:C)));const yt=R([]);return V(yt,yt,[1,1-(1-Ue)*C,1]),yt[4]=-Ge.x/Ge.y*C,Z(yt,yt,X),M(yt,Ve,yt),yt}(h.projection,0,h.center,u,l),x=gZ(h);return V(m,m,[x,x,1]),m}function gZ(h){const l=h.projection,u=SN(h.projection,h.zoom,h.width,h.height),m=d4(l,h.center),x=d4(l,Qe.convert(l.center));return Math.pow(2,m*u+(1-u)*x)}function SN(h,l,u,m,x=1/0){const b=h.range;if(!b)return 0;const S=Math.min(x,Math.max(u,m)),j=Math.log2(S/1024);return Oe(b[0]+j,b[1]+j,l)}const Dg=1/4e4;function d4(h,l){const u=fe(l.lat,-85.051129,St),m=new Qe(l.lng-180*Dg,u),x=new Qe(l.lng+180*Dg,u),b=h.project(m.lng,u),S=h.project(x.lng,u),j=Ar.fromLngLat(m),C=Ar.fromLngLat(x),O=S.x-b.x,z=S.y-b.y,U=C.x-j.x,q=C.y-j.y,K=Math.sqrt((U*U+q*q)/(O*O+z*z));return Math.log2(K)}function yZ(h,l,u){const m=Math.cos(u),x=Math.sin(u);return{x:h*m-l*x,y:h*x+l*m}}function xZ(h,l,u){R(h),Z(h,h,Yn(l[2])),G(h,h,Yn(l[0])),W(h,h,Yn(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 TN(h,l,u,m,x,b,S,j){const C=[u[0]-l[0],u[1]-l[1],0],O=[m[0]-l[0],m[1]-l[1],0];if(Me(C)<1e-12||Me(O)<1e-12)return Pr(h);const z=er([],C,O);pt(z,z),Pe(O,m,l),C[2]=(b-x)*j,O[2]=(S-x)*j;const U=C;return er(U,C,O),pt(U,U),la(h,z,U)}function EN(h,l,u=!1){const m=Xm(l.zoom),x=function(b,S,j){const C=S.worldSize,O=[b[12],b[13],b[14]],z=gt(O[1]/C),U=et(O[0]/C),q=R([]),K=ot(1,z)*C,X=ot(1,0)*C*Ht(z,S.zoom),J=1/M5(C);let ne=X*J;if(j){const ye=SN(S.projection,S.zoom,S.width,S.height,1024);ne=J*S.projection.pixelSpaceConversion(S.center.lat,C,ye)}const ae=Be(z,U);me(ae,ae,We([],pt([],ae),K*ne*O[2]));const he=function(ye){const Ee=[ye[0],ye[1],ye[2]];let ke=[0,1,0];const He=er([],ke,Ee);return er(ke,Ee,He),_t(ke)===0&&(ke=[0,1,0],er(He,Ee,ke)),pt(He,He),pt(ke,ke),pt(Ee,Ee),[He[0],He[1],He[2],0,ke[0],ke[1],ke[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(m>0){const b=function(S,j){const C=j.worldSize,O=ot(1,0)*C*Ht(j.center.lat,j.zoom)/M5(C),z=ot(1,j.center.lat)*C,U=R([]);W(U,U,Yn(j.center.lng)),G(U,U,Yn(j.center.lat)),B(U,U,[0,0,Le]),V(U,U,[O,O,O*z]);const q=j.point;return B(U,U,[-q.x,-q.y,0]),M(U,U,S),M(U,j.globeMatrix,U)}(h,l);return function(S,j,C){const O=(X,J,ne)=>{const ae=Me(X),he=Me(J),ce=Zm(X,J,ne);return We(ce,ce,1/Me(ce)*Xr(ae,he,ne))},z=O([S[0],S[1],S[2]],[j[0],j[1],j[2]],C),U=O([S[4],S[5],S[6]],[j[4],j[5],j[6]],C),q=O([S[8],S[9],S[10]],[j[8],j[9],j[10]],C),K=Zm([S[12],S[13],S[14]],[j[12],j[13],j[14]],C);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]}(x,b,m)}return x}function h4(h,l,u,m){const x=oi.projectAabbCorners(m,u);let b=Number.MAX_VALUE;for(let j=0;j0||ne===0&&X[0]*J[0]+X[1]*J[1]>=0&&X[0]*X[0]+X[1]*X[1]>J[0]*J[0]+J[1]*J[1])&&(z=K)}U=z}while(U!==O);return C.length>0&&C.push(C[0]),C}(x);if(Is(h,S))return b}const I0=64,Eb={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function AN(h,l,u,m,x,b,S,j,C,O=!1){const z=u.zoom,U=u.project(m),q=Ht(m.lat,z),K=1/q;R(h),B(h,h,[U.x+S[0]*K,U.y+S[1]*K,S[2]]);let X=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;X=Ee,J=Ee*Ht(u.center.lat,z)}else if(u.projection.name==="globe"){const ye=EN(h,u),Ee=[0,0,0,1];hr(Ee,Ee,M([],u.projMatrix,ye));const ke=Ee[3]/u.cameraToCenterDistance,He=Xm(z),$e=u.projection.pixelsPerMeter(m.lat,ne)*Ht(m.lat,z),Ge=u.projection.pixelsPerMeter(u.center.lat,ne)*Ht(u.center.lat,z);X=ke/Xr($e,rr(u.center.lat),He),J=ke*q/$e,X*=Ge,J*=Ge}}else X=K;V(h,h,[X,X,J]);const ae=[...h],he=l.orientation,ce=[];if(xZ(ce,[he[0]+(x?x[0]:0),he[1]+(x?x[1]:0),he[2]+(x?x[2]:0)],b),M(h,ae,ce),j&&u.elevation){let ye=0;const Ee=[];if(C&&u.elevation){ye=function(He,$e,Ge,Ue,Ve){const yt=$e.elevation;if(!yt)return 0;const wt=oi.projectAabbCorners(Ge,Ue),jt=ot(1,Ve.lat)*$e.worldSize,It=function(Yt,pr){const jr=[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=Yt[Rr.corners[0]],$n=Yt[Rr.corners[1]],cn=Yt[Rr.corners[2]],Vn=[$n[0]-ln[0],$n[1]-ln[1],pr*($n[2]-ln[2])],Sn=er(Vn,Vn,[cn[0]-ln[0],cn[1]-ln[1],pr*(cn[2]-ln[2])]);pt(Sn,Sn),Rr.dotProductWithUp=Nt(Sn,jr)}return zr.sort((Rr,ln)=>Rr.dotProductWithUp-ln.dotProductWithUp),zr[0].corners}(wt,jt),kt=wt[It[0]],Bt=wt[It[1]],mt=wt[It[2]],Ct=wt[It[3]],Lt=yt.getAtPointOrZero(new Ar(kt[0]/$e.worldSize,kt[1]/$e.worldSize),0),Ut=yt.getAtPointOrZero(new Ar(Bt[0]/$e.worldSize,Bt[1]/$e.worldSize),0),Kt=yt.getAtPointOrZero(new Ar(mt[0]/$e.worldSize,mt[1]/$e.worldSize),0),_r=yt.getAtPointOrZero(new Ar(Ct[0]/$e.worldSize,Ct[1]/$e.worldSize),0),ir=(Lt+_r)/2,nr=(Ut+Kt)/2;return ir>nr?Ut=l.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function Ake(h,l,u){h.indexBuffer=l.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=l.createVertexBuffer(h.vertexArray,_ke.members,!1,!0),h.normalArray&&(h.normalBuffer=l.createVertexBuffer(h.normalArray,Ske.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=l.createVertexBuffer(h.texcoordArray,wke.members,!1,!0)),h.colorArray&&(h.colorBuffer=l.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?vke:bke).members,!1,!0)),h.featureArray&&(h.pbrBuffer=l.createVertexBuffer(h.featureArray,Eke.members,!0)),h.segments=ji.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const m=h.material;m.pbrMetallicRoughness.baseColorTexture&&n2(m.pbrMetallicRoughness.baseColorTexture,l),m.pbrMetallicRoughness.metallicRoughnessTexture&&n2(m.pbrMetallicRoughness.metallicRoughnessTexture,l),m.normalTexture&&n2(m.normalTexture,l),m.occlusionTexture&&n2(m.occlusionTexture,l,u),m.emissionTexture&&n2(m.emissionTexture,l)}function f4(h,l,u){if(h.meshes)for(const m of h.meshes)Ake(m,l,u);if(h.children)for(const m of h.children)f4(m,l,u)}function jN(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)jN(l)}function jke(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 m4(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&&jke(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)m4(l)}function N0(h,l){const u=h.json.bufferViews[l.bufferView],m=bN[l.componentType];return new m(h.buffers[u.buffer],(l.byteOffset||0)+(u.byteOffset||0),l.count*(u.byteStride&&u.byteStride!==t2[l.type]*m.BYTES_PER_ELEMENT?u.byteStride/m.BYTES_PER_ELEMENT:t2[l.type]))}function p4(h,l,u,m){const x=bN[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}}(x),S=h.json.bufferViews[l.bufferView],j=S.byteStride?S.byteStride/x.BYTES_PER_ELEMENT:t2[l.type],C=u.float32,O=C.length/u.capacity;for(let z=0,U=0;z0){for(let ne=0;ne0){b.texcoordArray=new Hm;const q=l.json.accessors[x.TEXCOORD_0];b.texcoordArray.resize(q.count);const K=N0(l,q);p4(l,q,b.texcoordArray,K)}if(x._FEATURE_ID_RGBA4444!==void 0){const q=l.json.accessors[x._FEATURE_ID_RGBA4444];l.json.extensionsUsed&&l.json.extensionsUsed.includes("EXT_meshopt_compression")&&(b.featureData=N0(l,q))}x._FEATURE_RGBA4444!==void 0&&(b.featureData=new Uint32Array(N0(l,l.json.accessors[x._FEATURE_RGBA4444]).buffer));const U=h.material;return b.material=function(q,K){const{emissiveFactor:X=[0,0,0],alphaMode:J="OPAQUE",alphaCutoff:ne=.5,normalTexture:ae,occlusionTexture:he,emissiveTexture:ce,doubleSided:ye,name:Ee}=q,{baseColorFactor:ke=[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 Zn(...ke),metallicFactor:He,roughnessFactor:$e,baseColorTexture:Ge?K[Ge.index]:void 0,metallicRoughnessTexture:Ue?K[Ue.index]:void 0},doubleSided:ye,emissiveFactor:new Zn(...X),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 vZ(h,l,u){const{matrix:m,rotation:x,translation:b,scale:S,mesh:j,extras:C,children:O,name:z}=h,U={};if(U.name=z,U.localMatrix=m||function(q,K,X,J){var ne=K[0],ae=K[1],he=K[2],ce=K[3],ye=ne+ne,Ee=ae+ae,ke=he+he,He=ne*ye,$e=ne*Ee,Ge=ne*ke,Ue=ae*Ee,Ve=ae*ke,yt=he*ke,wt=ce*ye,jt=ce*Ee,It=ce*ke,kt=J[0],Bt=J[1],mt=J[2];return q[0]=(1-(Ue+yt))*kt,q[1]=($e+It)*kt,q[2]=(Ge-jt)*kt,q[3]=0,q[4]=($e-It)*Bt,q[5]=(1-(He+yt))*Bt,q[6]=(Ve+wt)*Bt,q[7]=0,q[8]=(Ge+jt)*mt,q[9]=(Ve-wt)*mt,q[10]=(1-(He+Ue))*mt,q[11]=0,q[12]=X[0],q[13]=X[1],q[14]=X[2],q[15]=1,q}([],x||[0,0,0,1],b||[0,0,0],S||[1,1,1]),U.globalMatrix=P(U.localMatrix),j!==void 0){U.meshes=u[j];const q=U.anchor=[0,0];for(const K of U.meshes){const{min:X,max:J}=K.aabb;q[0]+=X[0]+J[0],q[1]+=X[1]+J[1]}q[0]=Math.floor(q[0]/U.meshes.length/2),q[1]=Math.floor(q[1]/U.meshes.length/2)}if(C&&(C.id&&(U.id=C.id),C.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&&m[m.length-1].equals(m[0])&&m.pop();let x=0;for(let S=0;S0&&m.reverse();const b=vb(m.flatMap(S=>[S.x,S.y]),[]);return b.length===0?null:{vertices:m,indices:b}}function Nke(h,l){const u=[],m=[];let x=0;const b=[];for(const S of h){x=u.length;const j=S.vertexArray.float32,C=S.indexArray.uint16;for(let O=0;O0&&([m[S+1],m[S+2]]=[m[S+2],m[S+1]])}return{vertices:u,indices:m}}function g4(h){const l=function(C,O){const z=[],U=WebGL2RenderingContext;if(C.json.textures)for(const q of C.json.textures){const K={magFilter:U.LINEAR,minFilter:U.NEAREST,wrapS:U.REPEAT,wrapT:U.REPEAT};q.sampler!==void 0&&Object.assign(K,C.json.samplers[q.sampler]),z.push({image:O[q.source],sampler:K,uploaded:!1})}return z}(h,h.images),u=function(C,O){const z=[];for(const U of C.json.meshes){const q=[];for(const K of U.primitives)q.push(kke(K,C,O));z.push(q)}return z}(h,l),{scenes:m,scene:x,nodes:b}=h.json,S=m?m[x||0].nodes:[...b.keys()],j=[];for(const C of S)j.push(vZ(b[C],h,u));return function(C,O,z){const U={},q=new Set;for(let K=0;K0){const K=Array.from(q.values()).sort((X,J)=>X-J);for(let X=K.length-1;X>=0;X--)C.splice(K[X],1)}}(j,S,h.json.nodes),j}function Pke(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const l=h.vertexArray.float32,u=h.aabb.min[0]-1,m=h.aabb.min[1]-1,x=I0/(h.aabb.max[0]-u+2),b=I0/(h.aabb.max[1]-m+2);for(let S=0;Sh.heightmap[O*I0+C]&&(h.heightmap[O*I0+C]=j)}}function bZ(h,l,u,m,x){u.reserve(u.length+4*h.length),m.reserve(m.length+10*h.length),x.reserve(x.length+10*h.length);let b=m.length;for(const S of h){const j=Math.min(10,Math.max(4,1.3*S.height))*l,C=[-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,C,z/2),q=rt([],S.pos,C,-z/2),K=[U[0],U[1],U[2]+S.height],X=[q[0],q[1],q[2]+S.height],J=rt([],S.normal,C,O);We(J,J,j);const ne=rt([],S.normal,C,-O);We(ne,ne,j),me(J,U,J),me(ne,q,ne),U[2]+=.1,q[2]+=.1,m.emplaceBack(J[0],J[1],J[2]),m.emplaceBack(ne[0],ne[1],ne[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(K[0],K[1],K[2]),m.emplaceBack(X[0],X[1],X[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(J[0],J[1],J[2]),m.emplaceBack(ne[0],ne[1],ne[2]);const ae=z/j/2;x.emplaceBack(-ae-O,-1,ae,.8),x.emplaceBack(ae+O,-1,ae,.8),x.emplaceBack(-ae,0,ae,1.3),x.emplaceBack(ae,0,ae,1.3),x.emplaceBack(ae+O,-.8,ae,.7),x.emplaceBack(ae+O,-.8,ae,.7),x.emplaceBack(0,0,ae,1.3),x.emplaceBack(0,0,ae,1.3),x.emplaceBack(ae+O,-1.2,ae,.8),x.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 Rke(h,l){const u={};u.indexArray=new vs,u.vertexArray=new fu,u.colorArray=new bh,bZ(h,l,u.indexArray,u.vertexArray,u.colorArray);const m={defined:!0};m.emissiveFactor=Zn.black;const x={};return x.baseColorFactor=Zn.white,m.pbrMetallicRoughness=x,u.material=m,u.aabb=new oi([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),u}const wZ=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),Lke=Pn([{name:"a_normal_3",components:3,type:"Int16"}]),Dke=Pn([{name:"a_centroid_3",components:3,type:"Int16"}]),SZ=Pn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),Mke=Pn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Oke=Pn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Fke=Pn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Bke=Pn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),zke=Pn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),TZ=tn.types,kN=32767;function $ke(h,l){const u=ar+l;for(const m of h)for(const x of m)if(x.x<-l||x.x>u||x.y<-l||x.y>u)return!1;return!0}function Uke(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 y4{constructor(){this.layoutVertexArray=new fu,this.layoutAttenuationArray=new bh,this.layoutColorArray=new mu,this.indexArray=new vs,this.indexArrayForConflation=new vs,this.segmentsBucket=new ji}}class x4{constructor(l){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new ji,this.entranceBloom=new y4;const u=66560;this.layoutVertexArray=new fu,this.layoutVertexArray.reserve(u),this.layoutNormalArray=new Id,this.layoutNormalArray.reserve(u),this.layoutCentroidArray=new Id,this.layoutCentroidArray.reserve(u),this.layoutColorArray=new mu,this.layoutColorArray.reserve(u),this.layoutFloodLightDataArray=new mb,this.layoutFloodLightDataArray.reserve(u),this.layoutAOArray=new pb,this.layoutAOArray.reserve(u),this.indexArray=new vs,this.indexArray.reserve(66560),this.indexArrayForConflation=new vs,this.segmentsBucket=new ji,this.entranceBloom=new y4,l&&(this.layoutFacadePaintArray=new mu,this.layoutFacadeDataArray=new kg,this.layoutFacadeVerticalRangeArray=new mu)}reserve(l,u,m){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),m&&(this.layoutFacadePaintArray.reserveForAdditional(l),this.layoutFacadeDataArray.reserveForAdditional(l),this.layoutFacadeVerticalRangeArray.reserveForAdditional(l))}}class EZ{constructor(l){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Hm,this.footprintsIndices=new Wm,this.footprintsMin=new Ot(1/0,1/0),this.footprintsMax=new Ot(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new x4(!1),this.buildingWithFacade=new x4(!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 i4(l),this.groundEffect.groundRadiusArray=new kc,this.hasAppearances=null}updateFootprints(l,u){const m=new dN([],[],1),x={vertices:[],indices:new Uint32Array(0),grid:m,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};u.push({footprint:x,id:l})}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(vN!=null||tZ!=null)return null;if(Tb!=null)return Tb;const l=fetch(co());return Tb=function(u){let m,x,b,S,j;function C(){m=new Uint8Array(j.buffer),x=new Int16Array(j.buffer),b=new Int32Array(j.buffer),S=new Float32Array(j.buffer)}function O(){throw new Error("Unexpected BuildingGen error.")}const z=()=>{},U={a:{a:O,f:function(q){const K=m.length,X=Math.max(q>>>0,Math.ceil(1.2*K)),J=Math.ceil((X-K)/65536);try{return j.grow(J),C(),!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)(),j=K.f,C(),new hke({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:m,heap16:x,heap32:b,heapF32:S})})}(l).then(u=>(Tb=null,vN=u,vN)).catch(u=>{Br("Could not load building-gen"),Tb=null,tZ=u instanceof Error?u:new Error("Unknown error")}),Tb}()}populate(l,u,m,x){const b=fke();if(!b)return;const S=Dt(m);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 j=new Map,C=new Map;let O=0;for(const{feature:ae}of l){if(TZ[ae.type]!=="LineString"){j.set(ae.id,ae.properties.source_id);continue}const he=this.layers[0]._featureFilter.needGeometry;if(he&&!this.layers[0]._featureFilter.filter(new ri(this.zoom),ae,m))continue;const ce=wn(ae,he);if(!he&&!this.layers[0]._featureFilter.filter(new ri(this.zoom),ce,m))continue;const ye=he?ce.geometry:Ur(ae,m,x),Ee=[];for(const Ge of ye)for(const Ue of Ge)Ee.push(Ue.x),Ee.push(Ue.y);const ke={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=C.get(He);$e||($e=[],C.set(He,$e)),$e.push(ke),++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})},X=64*(l.length-O),J=X/2;this.buildingWithFacade.reserve(X,J,!0),this.buildingWithoutFacade.reserve(2*X,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(TZ[ae.type]==="LineString")continue;const Ee=this.layers[0]._featureFilter.needGeometry;if(Ee&&!this.layers[0]._featureFilter.filter(new ri(this.zoom),ae,m))continue;let ke=null;if(ae.properties&&ae.properties.hasOwnProperty("building_id")&&(ke=Number(ae.properties.building_id),U.has(ke)))continue;const He=wn(ae,Ee);if(!Ee&&!this.layers[0]._featureFilter.filter(new ri(this.zoom),He,m))continue;const $e=Ee?He.geometry:Ur(ae,m,x),Ge=HE($e,500);let Ue=!1;for(const Cn of Ge)if(Cn.length!==1){Ue=!0;break}if(Ue){q(ke);continue}if(!$ke($e,163)){q(ke);continue}const Ve=this.layers[0],yt=Uke(Ve.layout.get("building-roof-shape").evaluate(ae,{},m)),wt=Ve.layout.get("building-base").evaluate(ae,{},m),jt=Ve.layout.get("building-height").evaluate(ae,{},m),It=Ve.layout.get("building-flood-light-ground-radius").evaluate(ae,{},m),kt=Ve.paint.get("building-ambient-occlusion-intensity"),Bt=It/this.tileToMeter;ae.properties["building-part"]="roof";const mt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),Ct=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),Ut=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="window";const Kt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),_r=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 Yt=Ve.layout.get("building-flood-light-wall-radius").evaluate(ae,{},m);Yt=fe(Yt,0,2048);const pr=Yt/2048*kN,jr=j.get(he),zr=C.get(jr)||[],Rr=zr.length!==0&&Ve.layout.get("building-facade").evaluate(ae,{},m);b.setFacadeOptions(4,!0),b.setFauxFacadeOptions(Rr,!1,1);let ln=0,$n=0,cn=0,Vn=0,Sn=0,fs=0,ni=0,Hn=0,Ii=0,ls=0,Oa=0;if(Rr){let Cn=Math.round(Ve.layout.get("building-facade-floors").evaluate(ae,{},m));if(wt===0){Cn=Math.max(1,Cn-(zr.length>0?1:0));let Ss=4;if(jt>100){const Aa=[10,13,15];Ss=Aa[ae.id?ae.id%Aa.length:0]}else jt<=10&&(Ss=3);b.setFacadeOptions(Ss,!0),Sn=(jt<15?1.3:1.61803)*Ss/S}else Sn=wt/S;fs=jt/S,Sn=Math.min(Sn,fs),cn=Ve.layout.get("building-facade-unit-width").evaluate(ae,{},m)/S,Vn=(fs-Sn)/Cn,b.setFauxFacadeOptions(!0,!0,cn);const Ka=Ve.layout.get("building-facade-window").evaluate(ae,{},m);ln=Ka[0],$n=Ka[1],ni=Math.floor(65535*Math.min(1,Sn/ar)),Hn=Math.floor(65535*Math.min(1,fs/ar)),Ii=Math.floor(255*ln)<<8|Math.floor(255*$n),ls=Math.floor(65535*Math.min(1,cn/ar)),Oa=Math.floor(65535*Math.min(1,Vn/ar))}const cs=Array(Ge.length),bs={x:1/0,y:1/0},Ws={x:-1/0,y:-1/0},ws={x:0,y:0};let So=0;for(let Cn=0;Cn0){const Ss=[],Aa=Array(Ka.length+1);Aa[0]=0;for(let Hu=0;Huar||bs.y<0||Ws.y>ar)&&this.featuresOnBorder.push({featureId:ae.id,footprintIndex:this.footprints.length});{const Cn=vb(np,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Cn.length),this.footprintsIndices.uint16.set(Cn,Fb),this.buildingIds.add(ke??ae.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,qu.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,qu.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Gu.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Gu.y);const Ka={footprintVertexOffset:rp,footprintVertexLength:this.footprintsVertices.length-rp,footprintIndexOffset:Fb,footprintIndexLength:this.footprintsIndices.length-Fb,min:qu,max:Gu,hiddenFlags:0,indicesOffset:nP,indicesLength:lB,bloomIndicesOffset:To,bloomIndicesLength:ms,groundEffectVertexOffset:F0,groundEffectVertexLength:Bb,hasFauxFacade:Rr,height:Ob,promoteId:he,feature:He,parts:Ha,buildingBloom:wl},Ss=this.footprints.length;ae.id!==void 0&&this.featureFootprintLookup.set(ae.id,Ss),K(ke,Ss),this.footprints.push(Ka)}this.programConfigurations.populatePaintArrays(En.layoutVertexArray.length,ae,ce,{},u.availableImages,m,u.brightness),this.groundEffect.addPaintPropertiesData(ae,ce,{},u.availableImages,m,u.brightness),u.featureIndex.insert(ae,$e,ce,ye,this.index,el)}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,m,x,b,S,j){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,j),this.groundEffect.update(l,u,b,m,x,S,j),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=m=>{m.layoutVertexBuffer=l.createVertexBuffer(m.layoutVertexArray,wZ.members),m.layoutNormalBuffer=l.createVertexBuffer(m.layoutNormalArray,Lke.members),m.layoutCentroidBuffer=l.createVertexBuffer(m.layoutCentroidArray,Dke.members),m.layoutFloodLightDataBuffer=l.createVertexBuffer(m.layoutFloodLightDataArray,zke.members),m.layoutFacadeDataArray&&m.layoutFacadeDataArray.length&&(m.layoutFacadeDataBuffer=l.createVertexBuffer(m.layoutFacadeDataArray,Oke.members)),m.layoutFacadeVerticalRangeArray&&m.layoutFacadeVerticalRangeArray.length&&(m.layoutFacadeVerticalRangeBuffer=l.createVertexBuffer(m.layoutFacadeVerticalRangeArray,Fke.members)),m.entranceBloom.layoutVertexArray.length&&(m.entranceBloom.layoutVertexBuffer=l.createVertexBuffer(m.entranceBloom.layoutVertexArray,wZ.members),m.entranceBloom.layoutAttenuationBuffer=l.createVertexBuffer(m.entranceBloom.layoutAttenuationArray,Bke.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,m=!0){let x=!1;const b=m?u:0,S=0|(m?-1:~u);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const j of l){const C=this.footprints[j],O=C.hiddenFlags&S|b;C.hiddenFlags!==O&&(C.hiddenFlags=O,x=!0,this.groundEffect.updateHiddenByLandmarkRange(C.groundEffectVertexOffset,C.groundEffectVertexLength,C.hiddenFlags!==0))}return x&&(this.indexArrayForConflationUploaded=!1),x}uploadUpdatedIndexBuffer(l){if(this.groundEffect.uploadHiddenByLandmark(l),this.indexArrayForConflationUploaded)return;const u=x=>{x.indexArray.length!==0&&(x.indexArrayForConflation.resize(x.indexArray.length),x.indexArrayForConflation.uint16.set(x.indexArray.uint16),x.entranceBloom.indexArrayForConflation.resize(x.entranceBloom.indexArray.length),x.entranceBloom.indexArrayForConflation.uint16.set(x.entranceBloom.indexArray.uint16))};u(this.buildingWithoutFacade),u(this.buildingWithFacade);for(const x of this.footprints){const b=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,S=x.indicesOffset+x.indicesLength;if(x.hiddenFlags!==0){for(let C=x.indicesOffset;C{x.indexArray.length!==0&&(x.indexBuffer?x.indexBuffer.updateData(x.indexArrayForConflation):x.indexBuffer=l.createIndexBuffer(x.indexArrayForConflation,!0),x.entranceBloom.indexBuffer?x.entranceBloom.indexBuffer.updateData(x.entranceBloom.indexArrayForConflation):x.entranceBloom.indexBuffer=l.createIndexBuffer(x.entranceBloom.indexArrayForConflation,!0))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(l){const u=m=>{m.layoutColorBuffer?m.layoutColorBuffer.updateData(m.layoutColorArray):m.layoutColorBuffer=l.createVertexBuffer(m.layoutColorArray,SZ.members,!0),m.layoutFacadePaintArray&&(m.layoutFacadePaintBuffer?m.layoutFacadePaintBuffer.updateData(m.layoutFacadePaintArray):m.layoutFacadePaintBuffer=l.createVertexBuffer(m.layoutFacadePaintArray,Mke.members,!0)),m.entranceBloom.layoutColorBuffer?m.entranceBloom.layoutColorBuffer.updateData(m.entranceBloom.layoutColorArray):m.entranceBloom.layoutColorBuffer=l.createVertexBuffer(m.entranceBloom.layoutColorArray,SZ.members,!0)};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(l,u){const m=l.paint.get("building-ambient-occlusion-intensity");for(const x of this.footprints){if(4&x.hiddenFlags)continue;const b=u[x.promoteId],S=x.feature;S.properties["building-part"]="roof";const j=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),C=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),X=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical),J=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const ae of x.parts){let he,ce=j;ae.part===1?(ce=j,he=C):ae.part===0?(ce=O,he=z):ae.part===2?(ce=U,he=q):ae.part===3&&(ce=K,he=X),he=fe(he,0,1);for(let ye=0;yeS.max.x||C.max.xS.max.y||C.max.yj.max.x||j.min.x>l||u>j.max.y||j.min.y>u||j.height<=m||Vke(S,this.footprintsVertices.float32.subarray(2*j.footprintVertexOffset,2*(j.footprintVertexOffset+j.footprintVertexLength)),this.footprintsIndices.uint16.subarray(j.footprintIndexOffset,j.footprintIndexOffset+j.footprintIndexLength))&&(m=j.height,this.footprintLookup[b]=j,x=j.hiddenFlags!==0);if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.footprintLookup[b]=void 0}}function Vke(h,l,u){for(let m=0;m1&&(C=l[++j]);const z=Math.abs(O-C.left),U=Math.abs(O-C.right),q=Math.min(z,U);let K;const X=b/m*(x+1);if(C.isDash){const J=x-Math.abs(X);K=Math.sqrt(q*q+J*J)}else K=x-Math.sqrt(q*q+X*X);this.image.data[S+O]=Math.max(0,Math.min(255,K+128))}}}addRegularDash(l,u){for(let C=l.length-1;C>=0;--C){const O=l[C],z=l[C+1];O.zeroLength?l.splice(C,1):z&&z.isDash===O.isDash&&(z.left=O.left,l.splice(C,1))}const m=l[0],x=l[l.length-1];m.isDash===x.isDash&&(m.left=x.left-this.width,x.right=m.right+this.width);const b=this.width*this.nextRow;let S=0,j=l[S];for(let C=0;C1&&(j=l[++S]);const O=Math.abs(C-j.left),z=Math.abs(C-j.right),U=Math.min(O,z);this.image.data[b+C]=Math.max(0,Math.min(255,(j.isDash?U:-U)+u+128))}}addDash(l,u){const m=this.getKey(l,u);if(this.positions[m])return this.positions[m];const x=u==="round",b=x?7:0,S=2*b+1;if(this.nextRow+S>this.height)return Br("LineAtlas out of space"),null;l.length===0&&l.push(1);let j=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 g0,this.layoutVertexArray2=new fu,this.patternVertexArray=new fu,this.indexArray=new vs,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.segments=new ji,this.maxLineLength=0,this.zOffsetVertexArray=new fu,this.elevationGroundScaleVertexArray=new kc,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,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.hasPattern=$5("line",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Dt(m);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 j=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&j!==void 0;const C=[];for(const{feature:q,id:K,index:X,sourceLayerIndex:J}of l){const ne=this.layers[0]._featureFilter.needGeometry,ae=wn(q,ne);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),ae,m))continue;const he=b?b.evaluate(ae,{},m):void 0,ce={id:K,properties:q.properties,type:q.type,sourceLayerIndex:J,index:X,geometry:ne?ae.geometry:Ur(q,m,x),patterns:{},sortKey:he};C.push(ce)}b&&C.sort((q,K)=>q.sortKey-K.sortKey);const{lineAtlas:O,featureIndex:z}=u,U=this.addConstantDashes(O);for(const q of C){const{geometry:K,index:X,sourceLayerIndex:J}=q;if(U&&this.addFeatureDashes(q,O),this.hasPattern){const ne=U5("line",this.layers,q,this.zoom,this.pixelRatio,u);this.patternFeatures.push(ne)}else this.addFeature(q,K,X,m,O.positions,u.availableImages,u.brightness,u.elevationFeatures);z.insert(l[X].feature,K,X,J,this.index)}}addConstantDashes(l){let u=!1;for(const m of this.layers){const x=m.paint.get("line-dasharray").value,b=m.layout.get("line-cap").value;if(x.kind!=="constant"||b.kind!=="constant")u=!0;else{const S=b.value,j=x.value;if(!j)continue;l.addDash(j,S)}}return u}addFeatureDashes(l,u){const m=this.zoom;for(const x of this.layers){const b=x.paint.get("line-dasharray").value,S=x.layout.get("line-cap").value;if(b.kind==="constant"&&S.kind==="constant")continue;let j,C;if(b.kind==="constant"){if(j=b.value,!j)continue}else j=b.evaluate({zoom:m},l);C=S.kind==="constant"?S.value:S.evaluate({zoom:m},l),u.addDash(j,C),l.patterns[x.id]=[u.getKey(j,C)]}}update(l,u,m,x,b,S,j,C,O){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,j,O)}addFeatures(l,u,m,x,b,S){for(const j of this.patternFeatures)this.addFeature(j,j.geometry,j.index,u,m,x,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,Zke)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=l.createVertexBuffer(this.patternVertexArray,Qke)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,Hke.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=l.createVertexBuffer(this.elevationGroundScaleVertexArray,Wke.members,!0)),this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,Kke),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 m,x;if(u&&u>0?(m=`mapbox_clip_start_${u}`,x=`mapbox_clip_end_${u}`):(m="mapbox_clip_start",x="mapbox_clip_end"),l.properties&&l.properties.hasOwnProperty(m)&&l.properties.hasOwnProperty(x))return{start:+l.properties[m],end:+l.properties[x]}}addFeature(l,u,m,x,b,S,j,C){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 X=!(!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,x,C,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,m,b,S,x,j,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 _N(l,-u,-u,ar+u,ar+u)}clipRuntimeLinesToTile(l,u){const m=[];return[_N(l,-u,-u,ar+u,ar+u,m),m]}addElevatedRoadFeature(l,u,m,x,b,S,j,C){const O=[],z=Li.getElevationFeature(l,x);if(z){const U=this.clipLinesToTile(u,1),q=this.prepareElevatedLines(U,z,m);for(const K of q)O.push({geometry:K,elevation:z,elevationTileID:m,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,m,b,S,j,C);const K=new $i(m,U.elevationTileID);if(U.elevation)for(let X=q;X>1,this.layoutVertexArray.int16[6*X+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,m){if(u.constantHeight!=null)return l;const x=[],b=1/Dt(m);for(const S of l)dke(S,new Ic(u,b),0,x);return x}fillNonElevatedRoadSegment(l){for(let u=l;u0,q=C&&C.progress.max<1;if(this.lineClips){let Ge={min:this.lineClips.start,max:this.lineClips.end},Ue=1;if(C){const wt=this.lineClips.end-this.lineClips.start;Ge=function(jt,It,kt){return{min:ys(jt.min,It,kt),max:ys(jt.max,It,kt)}}(C.progress,{min:0,max:1},Ge),wt>0&&(Ue=(Ge.max-Ge.min)/wt)}const Ve=+u.properties.mapbox_clip_feature_len,yt=+u.properties.mapbox_clip_seg_len;if(Number.isNaN(Ve)||Number.isNaN(yt)){for(let jt=0;jt=2&&l[X-1].equals(l[X-2]);)X--;let J=0;for(;J0,Ct=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ue&&Ve==="round"){if(ItS&&(Ve="bevel"),Ve==="bevel"&&(It>2&&(Ve="flipbevel"),It2*Ct){const Kt=ae.sub(ae.sub(he)._mult(Ct/Lt)._round());this.updateDistance(he,Kt),this.addCurrentVertex(Kt,ye,0,0,ne,$e),he=Kt}this.updateDistance(he,ae),wt._mult(It),this.addCurrentVertex(ae,wt,0,0,ne,$e);const Ut=ae.dist(ce);if(Ut>2*Ct){const Kt=ae.add(ce.sub(ae)._mult(Ct/Ut)._round());this.updateDistance(ae,Kt),this.addCurrentVertex(Kt,Ee,0,0,ne,$e),ae=Kt}}else wt._mult(It),this.addCurrentVertex(ae,wt,0,0,ne,$e);else if(Ve==="flipbevel"){if(It>100)wt=Ee.mult(-1);else{const Lt=It*ye.add(Ee).mag()/ye.sub(Ee).mag();wt._perp()._mult(Lt*(mt?-1:1))}this.addCurrentVertex(ae,wt,0,0,ne,$e),this.addCurrentVertex(ae,wt.mult(-1),0,0,ne,$e)}else if(Ve==="bevel"||Ve==="fakeround"){const Lt=ae.dist(he);let Ut=1;if(this.elevationType==="offset"&&Ve==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&$e!=null&&he&&ce){const pr=4*Ct;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 ke=-ye/Ee,He=ce/Ee,$e=ke,Ge=He,Ue=-ke,Ve=-He;for(let yt=1;yt=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,z),C.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 _4(h,l,u){return h.xu||h.yu}let CZ,IZ;function NZ(h,l,u){return l*(ar/(h.tileSize*Math.pow(2,u-h.tileID.overscaledZ)))}br(CN,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const PZ=(h,l,u)=>(1-u)*h+u*l;function RZ(h,l){return 1/NZ(h,1,l.tileZoom)}function LZ(h,l,u,m){return h.translatePosMatrix(m||l.tileID.projMatrix,l,u.paint.get("line-translate"),u.paint.get("line-translate-anchor"))}const DZ=h=>{const l=[];MZ(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 m=h.layout.get("line-join").constantOr("miter")==="none",x=!!h.paint.get("line-pattern").constantOr(1);return m&&x&&l.push("LINE_JOIN_NONE"),l};function MZ(h){const l=h.paint.get("line-dasharray").value;return l.kind!=="constant"||l.value}let v4;const OZ=()=>v4||(v4={layout:CZ||(CZ=new rs({"line-cap":new qt(nt.layout_line["line-cap"]),"line-join":new qt(nt.layout_line["line-join"]),"line-miter-limit":new Qt(nt.layout_line["line-miter-limit"]),"line-round-limit":new Qt(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 Qt(nt.layout_line["line-elevation-reference"]),"line-cross-slope":new Qt(nt.layout_line["line-cross-slope"]),visibility:new Qt(nt.layout_line.visibility),"line-width-unit":new Qt(nt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new qt(nt.layout_line["line-elevation-ground-scale"])})),paint:IZ||(IZ=new rs({"line-opacity":new qt(nt.paint_line["line-opacity"]),"line-color":new qt(nt.paint_line["line-color"]),"line-translate":new Qt(nt.paint_line["line-translate"]),"line-translate-anchor":new Qt(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 Qt(nt.paint_line["line-pattern-cross-fade"]),"line-gradient":new Ag(nt.paint_line["line-gradient"]),"line-trim-offset":new Qt(nt.paint_line["line-trim-offset"]),"line-trim-fade-range":new Qt(nt.paint_line["line-trim-fade-range"]),"line-trim-color":new Qt(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 Qt(nt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new Qt(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"})}))},v4);class rCe extends qt{possiblyEvaluate(l,u){return u=new ri(Math.floor(u.zoom),{now:u.now,fadeDuration:u.fadeDuration,transition:u.transition,worldview:u.worldview}),super.possiblyEvaluate(l,u)}evaluate(l,u,m,x){return u=Object.assign({},u,{zoom:Math.floor(u.zoom)}),super.evaluate(l,u,m,x)}}let i2;function FZ(h,l){return l>0?l+2*h:h}const nCe=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),iCe=Pn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),sCe=Pn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Pn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const aCe=Pn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),oCe=Pn([{name:"a_feature_index",components:1,type:"Float32"}],4),lCe=Pn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),cCe=Pn([{name:"a_texb",components:2,type:"Uint16"}]),uCe=Pn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),dCe=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 BZ=Pn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),hCe=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 b4=class dL{constructor(l=null,u=0,m=4096){this.batchIndex=u,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=l||null,this.propsDwords=m,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(dL.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let x=0;xl.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,dL.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,m){const x=4*m.dataDrivenBlockSizeVec4;if(x===0)return;const b=u*x;if(b+x>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${u} exceeds propertiesData capacity`);for(let S=0;S<9;S++)m.dataDrivenMask&1<{if(!j)return;const O=m.getUniformBlockIndex(u,S);O!==m.INVALID_INDEX&&(m.uniformBlockBinding(u,O,C),m.bindBufferBase(m.UNIFORM_BUFFER,C,j))},b=3*this.batchIndex;x("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,b),x("SymbolPaintPropertiesUniform",this.propertiesBuffer,b+1),x("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)}}};b4.HEADER_DWORDS=12,b4.HEADER_BYTES=48;let w4=b4;function S4(h,l,u,m){return[gb(255*h,255*l),gb(255*u,255*m)]}function zZ(h,l,u,m,x,b,S,j){return!!h&&(h.kind==="constant"?h.value==="none":h.kind==="composite"||h.kind==="source"?h.evaluate({zoom:0,brightness:b,worldview:j},l,u,x,m,S)==="none":typeof h=="string"&&h==="none")}br(w4,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class T4{constructor(l,u,m,x,b="",S,j){this.layer=l,this.zoom=u,this.lut=m,this.isText=x,this.propDefs=this._getPropDefs(),this.worldview=b,this.maxUniformBufferBindings=S||24,this.uboSizeDwords=j||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,x),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 m=0,x=0,b=0,S=0;const j=[0,0,0,0,0,0,0,0,0];for(let C=0;C<9;C++){const{name:O,isColor:z,isVec2:U}=u[C],q=l.get(O),K=!(!q||typeof q.isConstant!="function"||q.isConstant()),X=this._appearancesHavePaintProperties(O),J=K||X,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?(m|=1<u.hasPaintProperty(l):this.isText?u=>u.hasTextPaintProperties():u=>u.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(l,u){const m=l.paint,x=u?"text":"icon",b=[`${x}-color`,`${x}-halo-color`,`${x}-opacity`,`${x}-halo-width`,`${x}-halo-blur`,`${x}-emissive-strength`,`${x}-occlusion-opacity`,"symbol-z-offset",`${x}-translate`];for(const S of b){const j=m.get(S);if(j&&typeof j=="object"&&"isConstant"in j&&!j.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(l,u){if(u.dataDrivenMask===0)return"";const m=[];for(let x=0;x<9;x++){if(!(u.dataDrivenMask&1<=X){Br(`Too many symbol features: batch ${q} requires binding points up to ${3*q+2}, device limit ${X}. Some features will render incorrectly.`);const ne={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:u,featureId:C};return this.allFeatures.push(ne),C!=null&&(this.featureVertexRangesFromId.has(C)||this.featureVertexRangesFromId.set(C,[]),this.featureVertexRangesFromId.get(C).push(ne)),0}this.ubos[q]||(this.ubos[q]=new w4(j,q,this.uboSizeDwords),this.ubos[q].writeHeader(O)),this.ubos[q].writeDataDrivenBlock(z,K,O);const J={batchIndex:q,localFeatureIndex:K,vtFeatureIndex:u,featureId:C};return this.allFeatures.push(J),C!=null&&(this.featureVertexRangesFromId.has(C)||this.featureVertexRangesFromId.set(C,[]),this.featureVertexRangesFromId.get(C).push(J)),K}updateFeatures(l,u,m,x,b,S,j){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const C=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(!m)continue;const K=m.feature(q.vtFeatureIndex);if(!K)continue;const X={type:K.type,id:O,properties:K.properties||{},geometry:[]},J=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(q.vtFeatureIndex):void 0,ne=this.evaluateAllProperties(X,U,x,b,j,void 0,J);this.ubos[q.batchIndex]&&this.ubos[q.batchIndex].writeDataDrivenBlock(ne,q.localFeatureIndex,C)}}}updateDynamicExpressions(l,u,m,x,b,S){if(this.layer=l,this.cachedConstantUniforms=null,!this.cachedHeader)return;const j=this.cachedHeader;for(const C of this.allFeatures){if(!u)continue;const O=u.feature(C.vtFeatureIndex);if(!O)continue;const z=C.featureId!=null&&b[C.featureId]||{},U={type:O.type,id:C.featureId,properties:O.properties||{},geometry:[]},q=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(C.vtFeatureIndex):void 0,K=this.evaluateAllProperties(U,z,m,x,S,void 0,q);this.ubos[C.batchIndex]&&this.ubos[C.batchIndex].writeDataDrivenBlock(K,C.localFeatureIndex,j)}}updateFeaturePaintForAppearance(l,u,m,x,b,S,j){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(l,j||null),!this.cachedHeader))return!1;const C=this.cachedHeader;if(C.dataDrivenMask===0)return!1;let O=!1;for(const z of this.allFeatures){if(z.vtFeatureIndex!==l)continue;const U=this.evaluateAllProperties(u,m,x,b,S,void 0,j);this.ubos[z.batchIndex]&&(this.ubos[z.batchIndex].writeDataDrivenBlock(U,z.localFeatureIndex,C),O=!0)}return O}getConstantUniformValues(l,u){const m=this.cachedHeader,x=!(!m||!m.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===u&&(!x||this.cachedConstantRenderZoom===l))return this.cachedConstantUniforms;const b=this.layer.paint,S=this.propDefs,j=x?new ri(l,{brightness:u,worldview:this.worldview}):null,C={type:1,id:void 0,properties:{},geometry:[]},O=q=>{const K=S[q],X=b.get(K.name);if(!X)return[0,0,0,1];const J=K.useThemeName?b.get(K.useThemeName):void 0,ne=zZ(J&&typeof J!="string"?J.value:void 0,C,{},[],void 0,u,void 0,this.worldview)?null:this.lut;let ae;ae=m&&m.cameraMask&1<{const X=b.get(S[q].name);if(!X)return K;if(m&&m.cameraMask&1<{m.text=function(x,b,S){const j=b.layout.get("text-transform").evaluate(S,{});return j==="uppercase"?x=x.toLocaleUpperCase():j==="lowercase"&&(x=x.toLocaleLowerCase()),xh.applyArabicShaping&&(x=xh.applyArabicShaping(x)),x}(m.text,l,u)}),h}const s2={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function mCe(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function pCe(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const E4=4294967296,$Z=1/E4,UZ=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let IN=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&m,h(x,l,this),this.pos===b&&this.skip(m)}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)*E4;return this.pos+=8,h}readSFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*E4;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,m;return m=l[this.pos++],u=127&m,m<128?u:(m=l[this.pos++],u|=(127&m)<<7,m<128?u:(m=l[this.pos++],u|=(127&m)<<14,m<128?u:(m=l[this.pos++],u|=(127&m)<<21,m<128?u:(m=l[this.pos],u|=(15&m)<<28,function(x,b,S){const j=S.buf;let C,O;if(O=j[S.pos++],C=(112&O)>>4,O<128||(O=j[S.pos++],C|=(127&O)<<3,O<128)||(O=j[S.pos++],C|=(127&O)<<10,O<128)||(O=j[S.pos++],C|=(127&O)<<17,O<128)||(O=j[S.pos++],C|=(127&O)<<24,O<128)||(O=j[S.pos++],C|=(1&O)<<31,O<128))return Ab(x,C,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&&UZ?UZ.decode(this.buf.subarray(l,h)):function(u,m,x){let b="",S=m;for(;S239?4:j>223?3:j>191?2:1;if(S+q>x)break;q===1?j<128&&(U=j):q===2?(C=u[S+1],(192&C)==128&&(U=(31&j)<<6|63&C,U<=127&&(U=null))):q===3?(C=u[S+1],O=u[S+2],(192&C)==128&&(192&O)==128&&(U=(15&j)<<12|(63&C)<<6|63&O,(U<=2047||U>=55296&&U<=57343)&&(U=null))):q===4&&(C=u[S+1],O=u[S+2],z=u[S+3],(192&C)==128&&(192&O)==128&&(192&z)==128&&(U=(15&j)<<18|(63&C)<<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 m,x;if(l>=0?(m=l%4294967296|0,x=l/4294967296|0):(m=~(-l%4294967296),x=~(-l/4294967296),4294967295^m?m=m+1|0:(m=0,x=x+1|0)),l>=18446744073709552e3||l<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");u.realloc(10),function(b,S,j){j.buf[j.pos++]=127&b|128,b>>>=7,j.buf[j.pos++]=127&b|128,b>>>=7,j.buf[j.pos++]=127&b|128,b>>>=7,j.buf[j.pos++]=127&b|128,j.buf[j.pos]=127&(b>>>=7)}(m,0,u),function(b,S){const j=(7&b)<<4;S.buf[S.pos++]|=j|((b>>>=3)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b)))))}(x,u)}(h,this):(this.realloc(4),this.buf[this.pos++]=127&h|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=h>>>7&127))))}writeSVarint(h){this.writeVarint(h<0?2*-h-1:2*h)}writeBoolean(h){this.writeVarint(+h)}writeString(h){h=String(h),this.realloc(4*h.length),this.pos++;const l=this.pos;this.pos=function(m,x,b){for(let S,j,C=0;C55295&&S<57344){if(!j){S>56319||C+1===x.length?(m[b++]=239,m[b++]=191,m[b++]=189):j=S;continue}if(S<56320){m[b++]=239,m[b++]=191,m[b++]=189,j=S;continue}S=j-55296<<10|S-56320|65536,j=null}else j&&(m[b++]=239,m[b++]=191,m[b++]=189,j=null);S<128?m[b++]=S:(S<2048?m[b++]=S>>6|192:(S<65536?m[b++]=S>>12|224:(m[b++]=S>>18|240,m[b++]=S>>12&63|128),m[b++]=S>>6&63|128),m[b++]=63&S|128)}return b}(this.buf,h,this.pos);const u=this.pos-l;u>=128&&VZ(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&&VZ(u,m,this),this.pos=u-1,this.writeVarint(m),this.pos+=m}writeMessage(h,l,u){this.writeTag(h,2),this.writeRawMessage(l,u)}writePackedVarint(h,l){l.length&&this.writeMessage(h,gCe,l)}writePackedSVarint(h,l){l.length&&this.writeMessage(h,yCe,l)}writePackedBoolean(h,l){l.length&&this.writeMessage(h,vCe,l)}writePackedFloat(h,l){l.length&&this.writeMessage(h,xCe,l)}writePackedDouble(h,l){l.length&&this.writeMessage(h,_Ce,l)}writePackedFixed32(h,l){l.length&&this.writeMessage(h,bCe,l)}writePackedSFixed32(h,l){l.length&&this.writeMessage(h,wCe,l)}writePackedFixed64(h,l){l.length&&this.writeMessage(h,SCe,l)}writePackedSFixed64(h,l){l.length&&this.writeMessage(h,TCe,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 Ab(h,l,u){return u?4294967296*l+(h>>>0):4294967296*(l>>>0)+(h>>>0)}function VZ(h,l,u){const m=l<=16383?1:l<=2097151?2:l<=268435455?3:Math.floor(Math.log(l)/(7*Math.LN2));u.realloc(m);for(let x=u.pos-1;x>=h;x--)u.buf[x+m]=u.buf[x]}function gCe(h,l){for(let u=0;u=0&&m>=l&&NN[this.text.charCodeAt(m)];m--)u--;this.text=this.text.substring(l,u),this.sectionIndex=this.sectionIndex.slice(l,u)}substring(l,u){const m=new jb;return m.text=this.text.substring(l,u),m.sectionIndex=this.sectionIndex.slice(l,u),m.sections=this.sections,m}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(a2.forText(l.scale,l.fontStack||u));const m=this.sections.length-1;for(let x=0;x=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function A4(h,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J=1,ne=1){const ae=jb.fromFeature(h,x,J,ne);U===Lc.vertical&&ae.verticalizePunctuation(q);let he=[];const ce=function($e,Ge,Ue,Ve,yt,wt,jt=1){if(!$e)return[];const It=[],kt=function(Ct,Lt,Ut,Kt,_r,ir,nr=1){let Yt=0;for(let pr=0;pr=0;let mt=0;for(let Ct=0;Ct<$e.length();Ct++){const Lt=$e.getSection(Ct),Ut=$e.getCodePoint(Ct);if(NN[Ut]||(mt+=qZ(Ut,Lt,Ve,yt,Ge,wt,jt)),Ct<$e.length()-1){const Kt=v5(Ut);(kCe[Ut]||Kt||Lt.image)&&It.push(HZ(Ct+1,mt,kt,It,CCe(Ut,$e.getCodePoint(Ct+1),Kt&&Bt),!1))}}return WZ(HZ($e.length(),mt,kt,It,0,!0))}(ae,O,b,l,m,K,ne),{processBidirectionalText:ye,processStyledBidirectionalText:Ee}=xh;if(ye&&ae.sections.length===1){const $e=ye(ae.toString(),ce);for(const Ge of $e){const Ue=new jb;Ue.text=Ge,Ue.sections=ae.sections;for(let Ve=0;Ve0&&el>Sn&&(Sn=el)}else{const Ha=Ue[ls.fontStack];if(!Ha)continue;Ha[cs]&&(ws=Ha[cs]);const wl=Ge[ls.fontStack];if(!wl)continue;const To=wl.glyphs[cs];if(!To)continue;if(Ws=To.metrics,Fa=cs!==8203?Ma:0,nr){const ms=wl.ascender!==void 0?Math.abs(wl.ascender):0,el=wl.descender!==void 0?Math.abs(wl.descender):0,Wa=(ms+el)*bs;fs-u/2;){if(S--,S<0)return!1;j-=h[S].dist(b),b=h[S]}j+=h[S].dist(h[S+1]),S++;const C=[];let O=0;for(;jm;)O-=C.shift().angleDelta;if(O>x)return!1;S++,j+=z.dist(U)}return!0}function JZ(h){let l=0;for(let u=0;uO){const X=(O-C)/K,J=Xr(U.x,q.x,X),ne=Xr(U.y,q.y,X),ae=new tp(J,ne,0,q.angleTo(U),z);return!S||QZ(h,ae,j,S,l)?ae:void 0}C+=K}}function NCe(h,l,u,m,x,b,S,j,C){const O=eX(m,b,S),z=tX(m,x),U=z*S,q=h[0].x===0||h[0].x===C||h[0].y===0||h[0].y===C;return l-U=0&&ye=0&&Ee=0&&q+O<=z){const ke=new tp(ye,Ee,0,he,X);m&&!QZ(h,ke,b,m,x)||K.push(ke)}}U+=ae}return j||K.length||S||(K=rX(h,U/2,u,m,x,b,S,!0,C)),K}function nX(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,j)=>j.h-S.h);const m=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(l/.95)),u),h:1/0}];let x=0,b=0;for(const S of h)for(let j=m.length-1;j>=0;j--){const C=m[j];if(!(S.w>C.w||S.h>C.h)){if(S.x=C.x,S.y=C.y,b=Math.max(b,S.y+S.h),x=Math.max(x,S.x+S.w),S.w===C.w&&S.h===C.h){const O=m.pop();O&&jl.id?1:h.versionl.version?1:h.sxl.sx?1:h.syl.sy?1:0}function N4(h){let l=0;for(let u=0;u0,iX(l,m,this.iconDescriptors,b),iX(u,m,this.patternDescriptors,b),this.iconDescriptors.sort(RN),this.patternDescriptors.sort(RN);let S=0;const j=x?x.data:"";j&&(S=Th(S,N4(j))),S=Th(S,1);for(const C of this.iconDescriptors)S=Th(S,N4(C.id)),S=Th(S,C.version),S=Th(S,C.sx),S=Th(S,C.sy);S=Th(S,1);for(const C of this.patternDescriptors)S=Th(S,N4(C.id)),S=Th(S,C.version),S=Th(S,C.sx),S=Th(S,C.sy);this.hash=S}subsetOf(l){return this.isSubsetArray(this.iconDescriptors,l.iconDescriptors,RN)&&this.isSubsetArray(this.patternDescriptors,l.patternDescriptors,RN)}isSubsetArray(l,u,m){let x=0,b=0;if(l.length>u.length)return!1;for(;x{const S=x.variant.id.toString().localeCompare(b.variant.id.toString());return S!==0?S:x.variant.sx!==b.variant.sx?x.variant.sx-b.variant.sx:x.variant.sy!==b.variant.sy?x.variant.sy-b.variant.sy:0});const m=new Map;for(const x of u)m.set(x.key,x.value);return m}class sX{constructor(l){this.sourceAtlasHash=l}}class aX{constructor(l,u,m,x){const b=new Map,S=new Map;this.haveRenderCallbacks=[];const j=[],C=x!==void 0,O=C?new Map:void 0,z=C?L4(l,O):l,U=C?L4(u,O):u;this.addImages(z,b,1,j),this.addImages(U,S,2,j);const{w:q,h:K}=nX(j),X=new Oo({width:q||1,height:K||1});for(const[J,ne]of z.entries()){const ae=b.get(J).paddedRect;Oo.copy(ne.data,X,{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,ke=ne.data.width,He=ne.data.height;ce=ce>1?ce-1:ce,Oo.copy(ne.data,X,{x:0,y:0},{x:ye,y:Ee},ne.data,m),Oo.copy(ne.data,X,{x:0,y:He-ce},{x:ye,y:Ee-ce},{width:ke,height:ce},m),Oo.copy(ne.data,X,{x:0,y:0},{x:ye,y:Ee+He},{width:ke,height:ce},m),Oo.copy(ne.data,X,{x:ke-ce,y:0},{x:ye-ce,y:Ee},{width:ce,height:He},m),Oo.copy(ne.data,X,{x:0,y:0},{x:ye+ke,y:Ee},{width:ce,height:He},m),Oo.copy(ne.data,X,{x:ke-ce,y:He-ce},{x:ye-ce,y:Ee-ce},{width:ce,height:ce},m),Oo.copy(ne.data,X,{x:0,y:He-ce},{x:ye+ke,y:Ee-ce},{width:ce,height:ce},m),Oo.copy(ne.data,X,{x:0,y:0},{x:ye+ke,y:Ee+He},{width:ce,height:ce},m),Oo.copy(ne.data,X,{x:ke-ce,y:0},{x:ye-ce,y:Ee+He},{width:ce,height:ce},m)}this.lut=m,this.image=X,this.iconPositions=b,this.patternPositions=S,C&&(this.contentDescriptor=new P4(z,U,x,m,O))}addImages(l,u,m,x){for(const[b,S]of l.entries()){const{bin:j,imagePosition:C,imageVariant:O}=R4(b,S,m);u.set(b,C),x.push(j),S.hasRenderCallback&&this.haveRenderCallbacks.push(O.id)}}patchUpdatedImages(l,u,m,x){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(b=>l.hasImage(b,m)),l.dispatchRenderCallbacks(this.haveRenderCallbacks,m);for(const b of l.getUpdatedImages(m)){for(const S of this.iconPositions.keys()){const j=du.parse(S);if(lc.isEqual(j.id,b)){const C=l.getImage(b,m);this.patchUpdatedImage(this.iconPositions.get(S),C,u,null)}}for(const S of this.patternPositions.keys()){const j=du.parse(S);if(lc.isEqual(j.id,b)){const C=l.getImage(b,m);this.patchUpdatedImage(this.patternPositions.get(S),C,u,x||this.lut)}}}}patchUpdatedImage(l,u,m,x=null){if(!l||!u||l.version===u.version)return;l.version=u.version;const[b,S]=l.tl,j=l.sdf;if(this.lut||j){const C={width:u.data.width,height:u.data.height},O=new Oo(C);Oo.copy(u.data,O,{x:0,y:0},{x:0,y:0},C,x,j),m.update(O,{position:{x:b,y:S},recreateWhenResize:!1})}else m.update(u.data,{position:{x:b,y:S},recreateWhenResize:!1})}}br(o2,"ImagePosition"),br(aX,"ImageAtlas",{omit:["lut"]}),br(sX,"ImageAtlasReference");class l2{constructor(l){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!l||l.useServerFontComposition===void 0||l.useServerFontComposition}loadGlyphRange(l,u,m,x,b){if(this.useServerFontComposition)return void l2.loadGlyphRange(l,u,m,x,b);const S=l.split(",").map(j=>j.trim()).filter(j=>j.length>0);S.length!==0?S.length!==1?this._loadMultipleFonts(S,u,m,x,b):this._loadFont(S[0],u,m,x,b):b(new Error("Empty fontstack"))}_loadMultipleFonts(l,u,m,x,b){const S=l.map(()=>null),j={completed:0,firstError:null,callbackCalled:!1},C=(O,z,U)=>{if(!j.callbackCalled&&(z&&!j.firstError&&(j.firstError=z),U&&(S[O]=U),j.completed++,j.completed===l.length)){j.callbackCalled=!0;const q=S.filter(X=>X!==null);if(q.length===0)return void b(j.firstError||new Error("All fonts failed to load"));const K=this._composeGlyphs(q);b(null,K)}};for(let O=0;O{C(O,z,U)})}_loadFont(l,u,m,x,b){const S=`${l}:${u}`;if(this.cachedRanges.has(S)){const C=this.cachedRanges.get(S);return void Ol.frame(()=>b(null,C))}const j=this.pendingRequests.get(S);j?j.push(b):(this.pendingRequests.set(S,[b]),l2.loadGlyphRange(l,u,m,x,(C,O)=>{C||this.cachedRanges.set(S,O||null);const z=this.pendingRequests.get(S);if(this.pendingRequests.delete(S),z)for(const U of z)U(C,O)}))}_composeGlyphs(l){const u={};let m,x;for(const b of l)if(m===void 0&&b.ascender!==void 0&&(m=b.ascender),x===void 0&&b.descender!==void 0&&(x=b.descender),b.glyphs)for(const S in b.glyphs)u[S]===void 0&&(u[S]=b.glyphs[S]);return{glyphs:u,ascender:m,descender:x}}}l2.loadGlyphRange=function(h,l,u,m,x){const b=256*l,S=b+255,j=m.transformRequest(m.normalizeGlyphsURL(u).replace("{fontstack}",h).replace("{range}",`${b}-${S}`),Lx.Glyphs);sg(j,(C,O)=>{if(C)x(C);else if(O){const z={},U=function(q){return new IN(q).readFields(ECe,{})}(O);for(const q of U.glyphs)z[q.id]=q;x(null,{glyphs:z,ascender:U.ascender,descender:U.descender})}})};const c2=1e20;function oX(h,l,u,m,x,b,S,j,C){for(let O=l;O-1);C++,b[C]=j,S[C]=O,S[C+1]=c2}for(let j=0,C=0;j{if(S){x.ascender=S.ascender,x.descender=S.descender;for(const j in S.glyphs)this._doesCharSupportLocalGlyph(+j)||(x.glyphs[+j]=S.glyphs[+j]);x.ranges[u]=!0}for(const j of x.requests[u]||[])j(b,S);delete x.requests[u]}))}getGlyphs(l,u){const m=[],x=this.url||Mn.GLYPHS_URL;for(const b in l)for(const S of l[b])m.push({stack:b,id:S});Je(m,({stack:b,id:S},j)=>{let C=this.entries[b];C||(C=this.entries[b]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let O=C.glyphs[S];if(O!==void 0)return void j(null,{stack:b,id:S,glyph:O});if(O=this._tinySDF(C,b,S),O)return C.glyphs[S]=O,void j(null,{stack:b,id:S,glyph:O});const z=Math.floor(S/256);if(256*z>65535)return Br("glyphs > 65535 not supported"),void j(null,{stack:b,id:S,glyph:O});if(C.ranges[z])return void j(null,{stack:b,id:S,glyph:O});let U=C.requests[z];U||(U=C.requests[z]=[],this.glyphLoader.loadGlyphRange(b,z,x,this.requestManager,(q,K)=>{if(K){C.ascender=K.ascender,C.descender=K.descender;for(const X in K.glyphs)this._doesCharSupportLocalGlyph(+X)||(C.glyphs[+X]=K.glyphs[+X]);C.ranges[z]=!0}for(const X of U)X(q,K);delete C.requests[z]})),U.push((q,K)=>{q?j(q):K&&j(null,{stack:b,id:S,glyph:K.glyphs[S]||null})})},(b,S)=>{if(b)u(b);else if(S){const j={};for(const{stack:C,id:O,glyph:z}of S)j[C]===void 0&&(j[C]={}),j[C].glyphs===void 0&&(j[C].glyphs={}),j[C].glyphs[O]=z&&{id:z.id,bitmap:z.bitmap.clone(),metrics:z.metrics},j[C].ascender=this.entries[C].ascender,j[C].descender=this.entries[C].descender;u(null,j)}})}_doesCharSupportLocalGlyph(l){return this.localGlyphMode!==D4.none&&(this.localGlyphMode===D4.all?!!this.localFontFamily:!!this.localFontFamily&&(Jv(l)||rE(l)||d0(l)||$m(l)||u0(l)||eE(l)||(u=l)>=131072&&u<=173791||(m=>m>=66736&&m<=66815)(l)));var u}_tinySDF(l,u,m){const x=this.localFontFamily;if(!x||!this._doesCharSupportLocalGlyph(m))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 LN.TinySDF({fontFamily:x,fontWeight:ne,fontSize:48,buffer:6,radius:16}),b.fontWeight=ne}const S=b.fontWeight;if(this.localGlyphs[S][m])return this.localGlyphs[S][m];const j=String.fromCodePoint(m),{data:C,width:O,height:z,glyphWidth:U,glyphHeight:q,glyphLeft:K,glyphTop:X,glyphAdvance:J}=b.draw(j);return this.localGlyphs[S][m]={id:m,bitmap:new Pg({width:O,height:z},C),metrics:{width:U/2,height:q/2,left:K/2,top:X/2-27,advance:J/2,localGlyph:!0}}}}function cX(h,l){return h+l[1]-l[0]}function M4(h,l,u,m,x=1){const b=[],S=h.imagePrimary,j=S.pixelRatio,C=S.paddedRect.w-2,O=S.paddedRect.h-2,z=(h.right-h.left)*x,U=(h.bottom-h.top)*x,q=S.stretchX||[[0,C]],K=S.stretchY||[[0,O]],X=q.reduce(cX,0),J=K.reduce(cX,0),ne=C-X,ae=O-J;let he=0,ce=X,ye=0,Ee=J,ke=0,He=ne,$e=0,Ge=ae;if(S.content&&m){const Ve=S.content;he=DN(q,0,Ve[0]),ye=DN(K,0,Ve[1]),ce=DN(q,Ve[0],Ve[2]),Ee=DN(K,Ve[1],Ve[3]),ke=Ve[0]-he,$e=Ve[1]-ye,He=Ve[2]-Ve[0]-ce,Ge=Ve[3]-Ve[1]-Ee}const Ue=(Ve,yt,wt,jt)=>{const It=MN(Ve.stretch-he,ce,z,h.left*x),kt=ON(Ve.fixed-ke,He,Ve.stretch,X),Bt=MN(yt.stretch-ye,Ee,U,h.top*x),mt=ON(yt.fixed-$e,Ge,yt.stretch,J),Ct=MN(wt.stretch-he,ce,z,h.left*x),Lt=ON(wt.fixed-ke,He,wt.stretch,X),Ut=MN(jt.stretch-ye,Ee,U,h.top*x),Kt=ON(jt.fixed-$e,Ge,jt.stretch,J),_r=new Ot(It,Bt),ir=new Ot(Ct,Bt),nr=new Ot(Ct,Ut),Yt=new Ot(It,Ut),pr=new Ot(kt/j,mt/j),jr=new Ot(Lt/j,Kt/j),zr=l*Math.PI/180;if(zr){const Sn=Math.sin(zr),fs=Math.cos(zr),ni=[fs,-Sn,Sn,fs];_r._matMult(ni),ir._matMult(ni),Yt._matMult(ni),nr._matMult(ni)}const Rr=Ve.stretch+Ve.fixed,ln=wt.stretch+wt.fixed,$n=yt.stretch+yt.fixed,cn=jt.stretch+jt.fixed,Vn=h.imageSecondary;return{tl:_r,tr:ir,bl:Yt,br:nr,texPrimary:{x:S.paddedRect.x+1+Rr,y:S.paddedRect.y+1+$n,w:ln-Rr,h:cn-$n},texSecondary:Vn?{x:Vn.paddedRect.x+1+Rr,y:Vn.paddedRect.y+1+$n,w:ln-Rr,h:cn-$n}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:pr,pixelOffsetBR:jr,minFontScaleX:He/j/z,minFontScaleY:Ge/j/U,isSDF:u}};if(S.stretchX||S.stretchY){const Ve=uX(q,ne,X),yt=uX(K,ae,J);for(let wt=0;wt0?[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 X=l.positionedLines.length,J=K/X;let ne=l.top-u[1];for(let ae=0;aeb)&&(b=X.x),(!K||X.y>S)&&(S=X.y)}const C=Math.min(b-m,S-x);let O=C/2;const z=new Yx([],DCe);if(C===0)return new Ot(m,x);for(let K=m;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 Cb(K.p.x-O,K.p.y-O,O,h)),z.push(new Cb(K.p.x+O,K.p.y-O,O,h)),z.push(new Cb(K.p.x-O,K.p.y+O,O,h)),z.push(new Cb(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 DCe(h,l){return l.max-h.max}LN.TinySDF=class{constructor({fontSize:h=24,buffer:l=3,radius:u=8,cutoff:m=.25,fontFamily:x="sans-serif",fontWeight:b="normal",fontStyle:S="normal",lang:j=null}={}){this.buffer=l,this.cutoff=m,this.radius=u,this.lang=j;const C=this.size=h+4*l,O=this._createCanvas(C),z=this.ctx=O.getContext("2d",{willReadFrequently:!0});z.font=`${S} ${b} ${h}px ${x}`,z.textBaseline="alphabetic",z.textAlign="left",z.fillStyle="black",this.gridOuter=new Float64Array(C*C),this.gridInner=new Float64Array(C*C),this.f=new Float64Array(C),this.z=new Float64Array(C+1),this.v=new Uint16Array(C)}_createCanvas(h){const l=document.createElement("canvas");return l.width=l.height=h,l}draw(h){const{width:l,actualBoundingBoxAscent:u,actualBoundingBoxDescent:m,actualBoundingBoxLeft:x,actualBoundingBoxRight:b}=this.ctx.measureText(h),S=Math.ceil(u),j=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(b-x))),C=Math.min(this.size-this.buffer,S+Math.ceil(m)),O=j+2*this.buffer,z=C+2*this.buffer,U=Math.max(O*z,0),q=new Uint8ClampedArray(U),K={data:q,width:O,height:z,glyphWidth:j,glyphHeight:C,glyphTop:S,glyphLeft:0,glyphAdvance:l};if(j===0||C===0)return K;const{ctx:X,buffer:J,gridInner:ne,gridOuter:ae}=this;this.lang&&(X.lang=this.lang),X.clearRect(J,J,j,C),X.fillText(h,J,J+S);const he=X.getImageData(J,J,j,C);ae.fill(c2,0,U),ne.fill(0,0,U);for(let ce=0;ce0?He*He:0,ne[ke]=He<0?He*He:0}}oX(ae,0,0,O,z,O,this.f,this.v,this.z),oX(ne,J,J,j,C,O,this.f,this.v,this.z);for(let ce=0;ceb.y!=J.y>b.y&&b.x<(J.x-X.x)*(b.y-X.y)/(J.y-X.y)+X.x&&(j=!j),C=Math.min(C,Pd(b,X,J))}}return(j?1:-1)*Math.sqrt(C)}(this.p,x),this.max=this.d+this.h*Math.SQRT2}}const MCe=Object.keys,O4=Number.POSITIVE_INFINITY,OCe=Math.sqrt(2);function Mg(h,l,u,m,x,b){const S=k4(h)&&h.collisionPadding?h.collisionPadding:[0,0,0,0],j={top:h.top-S[1],bottom:h.bottom+S[3],left:h.left-S[0],right:h.right+S[2],scaled:!1};return m!==void 0&&function(C,O){C.top*=O,C.bottom*=O,C.left*=O,C.right*=O,C.scaled=!0}(j,m),b&&(j.left+=b[0],j.right+=b[0],j.top+=b[1],j.bottom+=b[1]),u&&function(C,O,z){if(!O)return;const U=Yn(O),q=new Ot(z?z[0]:0,z?z[1]:0),K=new Ot(C.left,C.top),X=new Ot(C.right,C.top),J=new Ot(C.left,C.bottom),ne=new Ot(C.right,C.bottom);K._rotateAround(U,q),X._rotateAround(U,q),J._rotateAround(U,q),ne._rotateAround(U,q),C.left=Math.min(K.x,X.x,J.x,ne.x),C.right=Math.max(K.x,X.x,J.x,ne.x),C.top=Math.min(K.y,X.y,J.y,ne.y),C.bottom=Math.max(K.y,X.y,J.y,ne.y)}(j,u,x),l?{top:Math.min(l.top,j.top),bottom:Math.max(l.bottom,j.bottom),left:Math.min(l.left,j.left),right:Math.max(l.right,j.right),scaled:l.scaled||j.scaled}:j}function fX(h,[l,u]){let m=0,x=0;if(u===O4){l<0&&(l=0);const b=l/OCe;switch(h){case"top-right":case"top-left":x=b-7;break;case"bottom-right":case"bottom-left":x=7-b;break;case"bottom":x=7-l;break;case"top":x=l-7}switch(h){case"top-right":case"bottom-right":m=-b;break;case"top-left":case"bottom-left":m=b;break;case"left":m=l;break;case"right":m=-l}}else{switch(l=Math.abs(l),u=Math.abs(u),h){case"top-right":case"top-left":case"top":x=u-7;break;case"bottom-right":case"bottom-left":case"bottom":x=7-u}switch(h){case"top-right":case"bottom-right":case"right":m=-l;break;case"top-left":case"bottom-left":case"left":m=l}}return[m,x]}function FCe(h,l,u,m,x,b,S,j,C,O,z,U,q,K,X){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,wt]=He.get("icon-size-scale-range");return{baseIconRotate:Ue,baseTextRotate:Ve,iconScaleFactor:fe(1,yt,wt)}}(m,x,b);l&&(ae.iconBBox=Mg(l,ae.iconBBox,ce),u)&&(ae.iconVerticalBBox=Mg(u,ae.iconVerticalBBox,ce+90));const ke=BN(U.horizontal);ke&&(he.textBBox=Mg(ke,he.textBBox,ye,1,K)),U.vertical&&(he.textVerticalBBox=Mg(U.vertical,he.textVerticalBBox,ye+90,1,K));for(const He of ne)He.hasIconLayoutProperties()&&BCe(ae,h,J,He,x,b,j,ce,S,C,l,O,Ee,z,X),He.hasTextLayoutProperties()&&zCe(he,J,He,x,b,K,ye,q,ke,U.vertical);return{iconBBox:ae.iconBBox,iconVerticalBBox:ae.iconVerticalBBox,textBBox:he.textBBox,textVerticalBBox:he.textVerticalBBox}}function BCe(h,l,u,m,x,b,S,j,C,O,z,U,q,K,X){const{appearanceIconOffset:J,appearanceIconRotate:ne,appearanceIconSize:ae}=mX(m,u,x,b,S,j,C,O.iconScaleFactor);let he=null,ce=null,ye=null;m.hasLayoutProperty("icon-image")?ye=function(ke,He,$e,Ge,Ue,Ve,yt,wt){let jt=null;const It=He.getAppearanceValueAndResolveTokens($e,"icon-image",Ge,Ue,wt);if(It){const kt=ke.getResolvedImageFromTokens(It),Bt=$e.hasLayoutProperty("icon-size")?$e.getUnevaluatedLayoutProperty("icon-size"):He._unevaluatedLayout._values["icon-size"],mt=u2(kt,P0(ke.zoom,Bt,ke.worldview,wt),Bt,Ue,ke.zoom,Ge,ke.pixelRatio,yt,ke.worldview,wt);jt=Ve.get(mt.iconPrimary.toString())}return jt}(l,u,m,x,b,U,q,X):z&&(ye=z.imagePrimary),ye&&(he=PN(ye,null,J,K),l.allowVerticalPlacement&&(ce=PN(ye,null,J,K)));const Ee=C>0?ae/C:1;he&&(h.iconBBox=Mg(he,h.iconBBox,ne,Ee!==1?Ee:void 0)),ce&&(h.iconVerticalBBox=Mg(ce,h.iconVerticalBBox,ne+90,Ee!==1?Ee:void 0))}function mX(h,l,u,m,x,b,S,j){const C=h.hasLayoutProperty("icon-offset")?l.getAppearanceValueAndResolveTokens(h,"icon-offset",u,m,[]):null,O=C&&Array.isArray(C)?C:x,z=h.hasLayoutProperty("icon-rotate")?l.getAppearanceValueAndResolveTokens(h,"icon-rotate",u,m,[]):null,U=typeof z=="number"?z:b,q=h.hasLayoutProperty("icon-size")?l.getAppearanceValueAndResolveTokens(h,"icon-size",u,m,[]):null;return{appearanceIconOffset:O,appearanceIconRotate:U,appearanceIconSize:typeof q=="number"?q*j:S}}function zCe(h,l,u,m,x,b,S,j,C,O){const{appearanceTextOffset:z,appearanceTextRotate:U,appearanceTextSize:q}=pX(u,l,m,x,b,S,j),K=q/j,X=[(z[0]-b[0])*K,(z[1]-b[1])*K],J=X[0]!==0||X[1]!==0;C&&(h.textBBox=Mg(C,h.textBBox,U,K,z,J?X:void 0)),O&&(h.textVerticalBBox=Mg(O,h.textVerticalBBox,U+90,K,z,J?X:void 0))}function pX(h,l,u,m,x,b,S){const j=h.hasLayoutProperty("text-offset")?l.getAppearanceValueAndResolveTokens(h,"text-offset",u,m,[]):null,C=j&&Array.isArray(j)?[j[0]*Ma,j[1]*Ma]:x,O=h.hasLayoutProperty("text-rotate")?l.getAppearanceValueAndResolveTokens(h,"text-rotate",u,m,[]):null,z=typeof O=="number"?O:b,U=h.hasLayoutProperty("text-size")?l.getAppearanceValueAndResolveTokens(h,"text-size",u,m,[]):null;return{appearanceTextOffset:C,appearanceTextRotate:z,appearanceTextSize:typeof U=="number"?U:S}}function FN(h,l,u,m,x,b,S,j,C){if(!l||!l.usvg)return;const O=XZ(m),z=XZ(x),U=b!=="both"&&b!=="width"||!YZ(m)?1:z.width/O.width,q=b!=="both"&&b!=="height"||!ZZ(m)?1:z.height/O.height;u.scaleSelf(U,q);const K=u.toString();S.set(K,u),j.set(K,l);const{imagePosition:X}=R4(K,l,1);C.set(K,X)}function gX(h,l,u,m,x,b,S,j,C,O){if(!h)return;const z=function(U,q,K,X,J,ne,ae){if(U.kind==="camera")return U.maxSize;if(U.kind==="composite"){const he=q.possiblyEvaluate(new ri(U.maxZoom,{worldview:ne}),K,ae).evaluate(J,{},K,ae),ce=q.possiblyEvaluate(new ri(U.minZoom,{worldview:ne}),K,ae).evaluate(J,{},K,ae);return Math.max(he,ce)}return q.possiblyEvaluate(new ri(X,{worldview:ne}),K,ae).evaluate(J,{},K,ae)}(l,u,m,x,b,C,O);return h.scaleSelf(z*j*S)}function u2(h,l,u,m,x,b,S,j,C,O){return{iconPrimary:gX(h.getPrimary(),l,u,m,x,b,S,j,C,O),iconSecondary:gX(h.getSecondary(),l,u,m,x,b,S,j,C,O)}}function $Ce(h,l,u){if(!l)return;const m=u.get(h.toString()),x=u.get(l.toString());m&&x&&(m.paddedRect.w===x.paddedRect.w&&m.paddedRect.h===x.paddedRect.h||Br(`Mismatch in icon variant sizes: ${h.toString()} and ${l.toString()}`),m.usvg!==x.usvg&&Br(`Mismatch in icon variant image types: ${h.id} and ${l.id}`))}function yX(h,l,u,m){if(!h)return;const x=l.get(u.toString());if(x&&(h.imagePrimary=x),m){const b=l.get(m.toString());h.imageSecondary=b}}function UCe(h,l){for(const u in h.horizontal)xX(h.horizontal[u],l);xX(h.vertical,l)}function xX(h,l){if(h){for(const u of h.positionedLines)for(const m of u.positionedGlyphs)if(m.image!==null){const x=m.image.toString();m.rect=l.get(x).paddedRect}}}function F4(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 VCe(h,l,u,m,x,b,S,j,C){const O=BN(b.horizontal)||b.vertical,z=u.get("icon-text-fit-padding").evaluate(m,{},x);let U,q=l;return l&&C!=="none"&&(h.allowVerticalPlacement&&b.vertical&&(U=C4(l,b.vertical,C,z,j,S)),O&&(q=C4(l,O,C,z,j,S))),{defaultShapedIcon:q,verticallyShapedIcon:U}}function _X(h,l){return h*l/24}function qCe(h,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he,ce,ye,Ee,ke,He){let $e=S.textMaxSize.evaluate(l,{},q);$e===void 0?$e=j*S.textScaleFactor:$e*=S.textScaleFactor;const Ge=h.layers[0].layout,Ue=_X(j,S.textScaleFactor),Ve=BN(u.horizontal)||u.vertical,yt=h.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),wt=h.getAppearanceFeatureData(l.index);(ne!=="none"||yt)&&wt&&(wt.textShaping=Ve,wt.iconTextFitPadding=Ge.get("icon-text-fit-padding").evaluate(l,{},q),wt.fontScale=Ue,wt.textScaleFactor=S.textScaleFactor);const jt=K.name==="globe",It=h.tilePixelRatio*$e/24,kt=(Kt=h.overscaling,h.zoom>18&&Kt>2&&(Kt>>=1),Math.max(ar/(512*Kt),1)*Ge.get("symbol-spacing")),Bt=Ge.get("text-padding")*h.tilePixelRatio,mt=Ge.get("icon-padding")*h.tilePixelRatio,Ct=Yn(Ge.get("text-max-angle")),Lt=Ge.get("icon-rotation-alignment")==="map"&&ce!=="point",Ut=kt/2;var Kt;h.hasAnyIconTextFit===!1&&ne!=="none"&&(h.hasAnyIconTextFit=!0);const _r=l.properties?+l.properties[yn]:null,ir=_r&&h.elevationFeatureIdToIndex?h.elevationFeatureIdToIndex.get(_r):65535,nr=(Yt,pr,jr)=>{if(pr.x<0||pr.x>=ar||pr.y<0||pr.y>=ar)return;let zr=null;if(jt){const{x:Rr,y:ln,z:$n}=K.projectTilePoint(pr.x,pr.y,jr);zr={anchor:new tp(Rr,ln,$n,0,void 0),up:K.upVector(jr,pr.x,pr.y)}}(function(Rr,ln,$n,cn,Vn,Sn,fs,ni,Hn,Ii,ls,Oa,cs,bs,Ws,ws,So,Fa,En,bl,Ns,Ha,wl,To,ms,el,Wa,nP,Ob,zl,lB,Fb){const rp=Rr.addToLineVertexArray(ln,cn);let np,qu,Gu,F0,Bb,Cn,Ka,Ss=0,Aa=0,Hu=0,Dc=0,Mc=-1,Oc=-1;const Dd={};let iP=mf("");const kh=$n?$n.anchor:ln,zb=nP!=="none";let $b=0,fa=0;if(Hn._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Ps=Hn.layout.get("text-offset").evaluate(Ns,{},ms);$b=Ps[0]*Ma,fa=Ps[1]*Ma}else $b=Hn.layout.get("text-radial-offset").evaluate(Ns,{},ms)*Ma,fa=O4;if(Rr.allowVerticalPlacement&&Vn.vertical){const Ps=Vn.vertical;if(Ws)Cn=$4(Ps),ni&&(Ka=$4(ni));else{const Sl=Hn.layout.get("text-rotate").evaluate(Ns,{},ms)+90;Gu=zN(Ii,kh,ln,ls,Oa,cs,Ps,bs,Sl,ws,Fb),ni&&(F0=zN(Ii,kh,ln,ls,Oa,cs,ni,Fa,Sl,null,lB))}}if(Sn){const Ps=Hn.layout.get("icon-rotate").evaluate(Ns,{},ms),Sl=M4(Sn,Ps,wl,zb,Ha.iconScaleFactor),$l=ni?M4(ni,Ps,wl,zb,Ha.iconScaleFactor):void 0;qu=zN(Ii,kh,ln,ls,Oa,cs,Sn,Fa,Ps,null,zl);const Od=function(Ch,E2,Ub,sNe,aNe,zQ,$Q,oNe,hVt,uB){const UQ=Ch.layers[0],VQ=UQ.appearances;let Vb=E2.length;if(Ub&&(Vb=Math.max(Vb,Ub.length)),VQ.length===0)return Vb;const[lNe,cNe]=sNe.get("icon-size-scale-range"),uNe=fe(1,lNe,cNe);for(const lP of VQ)if(lP.hasLayoutProperty("icon-image")){const qQ=UQ.getAppearanceValueAndResolveTokens(lP,"icon-image",zQ,$Q,uB);if(qQ){const GQ=Ch.getResolvedImageFromTokens(qQ);if(GQ){const HQ=lP.hasLayoutProperty("icon-size")?lP.getUnevaluatedLayoutProperty("icon-size"):aNe._values["icon-size"],dNe=u2(GQ,P0(Ch.zoom,HQ,Ch.worldview,uB),HQ,$Q,Ch.zoom,zQ,Ch.pixelRatio,uNe,Ch.worldview,uB),WQ=oNe.get(dNe.iconPrimary.toString());WQ&&(Vb=Math.max(Vb,PCe(WQ)))}}}return Vb}(Rr,Sl,$l,Hn.layout,Hn._unevaluatedLayout,Ns,ms,Rr.iconAtlasPositions,0,To);Ss=4*Od;const sP=Hn.layout.get("icon-size").evaluate(Ns,{},ms,To),aP=Ha.compositeIconSizes?Ha.compositeIconSizes[0].evaluate(Ns,{},ms,To):0,cB=Ha.compositeIconSizes?Ha.compositeIconSizes[1].evaluate(Ns,{},ms,To):0,oP=z4(Rr.layerIds[0],Rr.iconSizeData,sP,Ha.iconScaleFactor,aP,cB);Rr.addSymbols(Rr.icon,Sl,oP,bl,En,Ns,void 0,$n,ln,rp.lineStartIndex,rp.lineLength,-1,To,ms,el,Wa,Rr.symbolInstances.length,Od),Mc=Rr.icon.placedSymbolArray.length-1,$l&&(Aa=4*Od,Rr.addSymbols(Rr.icon,$l,oP,bl,En,Ns,Lc.vertical,$n,ln,rp.lineStartIndex,rp.lineLength,-1,To,ms,el,Wa,Rr.symbolInstances.length,Od),Oc=Rr.icon.placedSymbolArray.length-1)}for(const Ps in Vn.horizontal){const Sl=Ps,$l=Vn.horizontal[Sl];np||(iP=mf($l.text),Ws?Bb=$4($l):np=zN(Ii,kh,ln,ls,Oa,cs,$l,bs,Hn.layout.get("text-rotate").evaluate(Ns,{},ms),ws,Fb));const Od=$l.positionedLines.length===1;if(Hu+=vX(Rr,$n,ln,$l,fs,Hn,Ws,Ns,ws,rp,Vn.vertical?Lc.horizontal:Lc.horizontalOnly,Od?MCe(Vn.horizontal):[Sl],Dd,Mc,Ha,To,ms,Rr.symbolInstances.length,el),Od)break}Vn.vertical&&(Dc+=vX(Rr,$n,ln,Vn.vertical,fs,Hn,Ws,Ns,ws,rp,Lc.vertical,["vertical"],Dd,Oc,Ha,To,ms,Rr.symbolInstances.length,el));let ea=-1;const ja=(Ps,Sl)=>Ps?Math.max(Ps,Sl):Sl;ea=ja(Bb,ea),ea=ja(Cn,ea),ea=ja(Ka,ea);const Md=ea>-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"),Ns.sortKey!==void 0&&Rr.addToSortKeyRanges(Rr.symbolInstances.length,Ns.sortKey),Rr.symbolInstances.emplaceBack(ln.x,ln.y,kh.x,kh.y,kh.z,Dd.right>=0?Dd.right:-1,Dd.center>=0?Dd.center:-1,Dd.left>=0?Dd.left:-1,Dd.vertical>=0?Dd.vertical:-1,Mc,Oc,iP,np!==void 0?np:Rr.collisionBoxArray.length,np!==void 0?np+1:Rr.collisionBoxArray.length,Gu!==void 0?Gu:Rr.collisionBoxArray.length,Gu!==void 0?Gu+1:Rr.collisionBoxArray.length,qu!==void 0?qu:Rr.collisionBoxArray.length,qu!==void 0?qu+1:Rr.collisionBoxArray.length,F0||Rr.collisionBoxArray.length,F0?F0+1:Rr.collisionBoxArray.length,ls,Hu,Dc,Ss,Aa,Md,0,$b,fa,ea,0,zb?1:0,Ob)})(h,pr,zr,Yt,u,m,b,x,h.layers[0],h.collisionBoxArray,l.index,l.sourceLayerIndex,h.index,Bt,he,O,0,mt,Lt,ae,l,S,z,U,q,X,J,ne,ir,ye,Ee,ke)};if(ce==="line")for(const Yt of _N(l.geometry,0,0,ar,ar)){const pr=NCe(Yt,kt,Ct,u.vertical||Ve,m,24,It,h.overscaling,ar);for(const jr of pr)Ve&&GCe(h,Ve.text,Ut,jr)||nr(Yt,jr,q)}else if(ce==="line-center"){for(const Yt of l.geometry)if(Yt.length>1){const pr=ICe(Yt,Ct,u.vertical||Ve,m,24,It);pr&&nr(Yt,pr,q)}}else if(l.type==="Polygon")for(const Yt of HE(l.geometry,0)){const pr=LCe(Yt,16);nr(Yt[0],new tp(pr.x,pr.y,0,0,void 0),q)}else if(l.type==="LineString")for(const Yt of l.geometry)nr(Yt,new tp(Yt[0].x,Yt[0].y,0,0,void 0),q);else if(l.type==="Point")for(const Yt of l.geometry)for(const pr of Yt)nr([pr],new tp(pr.x,pr.y,0,0,void 0),q)}const B4=255,R0=B4*ep;function vX(h,l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he){const ce=hX(0,m,C,b,S,j,x,h.allowVerticalPlacement,void 0,X.textScaleFactor),ye=b.layout.get("text-size").evaluate(j,{},ne),Ee=X.compositeTextSizes?X.compositeTextSizes[0].evaluate(j,{},ne):0,ke=X.compositeTextSizes?X.compositeTextSizes[1].evaluate(j,{},ne):0,He=z4(h.layerIds[0],h.textSizeData,ye,X.textScaleFactor,Ee,ke);h.addSymbols(h.text,ce,He,C,S,j,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 z4(h,l,u,m,x,b){const S=l;let j=null;return S.kind==="source"?(j=[ep*u*m],j[0]>R0&&Br(`${h}: Value for "text-size" is >= ${B4}. Reduce your "text-size".`)):S.kind==="composite"&&(j=[ep*x*m,ep*b*m],(j[0]>R0||j[1]>R0)&&Br(`${h}: Value for "text-size" is >= ${B4}. Reduce your "text-size".`)),j}function BN(h){for(const l in h)return h[l];return null}function zN(h,l,u,m,x,b,S,j,C,O,z){let U,q,K,X;if(U=z?z.top:S.top,q=z?z.bottom:S.bottom,K=z?z.left:S.left,X=z?z.right:S.right,k4(S)&&S.collisionPadding){const J=S.collisionPadding;K-=J[0],U-=J[1],X+=J[2],q+=J[3]}if(C){const J=new Ot(K,U),ne=new Ot(X,U),ae=new Ot(K,q),he=new Ot(X,q),ce=Yn(C);let ye=new Ot(0,0);O&&(ye=new Ot(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),X=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,X,q,j,m,x,b),h.length-1}function $4(h){k4(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 GCe(h,l,u,m){const x=h.compareText;if(l in x){const b=x[l];for(let S=b.length-1;S>=0;S--)if(m.dist(b[S])ce&&(ye(ke,jt,$e,Ge,yt,wt),ye(jt,He,yt,wt,Ue,Ve))}ye(U,q,m,b,x,b),ye(q,K,x,b,x,S),ye(K,X,x,S,m,S),ye(X,U,m,S,m,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 wX(h,{x:l,y:u},m=0){return new Ot(((l-m)*h.scale-h.x)*ar,(u*h.scale-h.y)*ar)}const HCe=R(new Float32Array(16));class Og{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,m){return{x:l,y:u,z:0}}locationPoint(l,u,m,x=!0){return l._coordinatePoint(l.locationCoordinate(u,m),x)}pixelsPerMeter(l,u){return ot(1,l)*u}pixelSpaceConversion(l,u,m){return 1}farthestPixelDistance(l){return bX(l,l.pixelsPerMeter)}pointCoordinate(l,u,m,x){const b=l.horizonLineFromTop(!1),S=new Ot(u,Math.max(b,m));return l.rayIntersectionCoordinate(l.pointRayIntersection(S,x))}pointCoordinate3D(l,u,m){const x=new Ot(u,m);if(l.elevation)return l.elevation.pointCoordinate(x);{const b=this.pointCoordinate(l,x.x,x.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 m=l.horizonLineFromTop();return u.y0?u<-Ib+m&&(u=-Ib+m):u>Ib-m&&(u=Ib-m);const S=b/Math.pow(UN(u),x);let j=S*Math.sin(x*l),C=b-S*Math.cos(x*l);return j=.5*(j/Math.PI+.5),C=.5*(C/Math.PI+.5),{x:j,y:this.southernCenter?C:1-C,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:m,f:x}=this,b=x-u,S=Math.sign(b),j=Math.sign(m)*Math.sqrt(l*l+b*b);let C=Math.atan2(l,Math.abs(b))*S;b*m<0&&(C-=Math.PI*Math.sign(l)*S);const O=fe(lo(C/m)+this.center[0],-180,180),z=fe(lo(2*Math.atan(Math.pow(x/j,1/m))-Ib),-85.051129,St);return new Qe(O,this.southernCenter?-z:z)}}class SX extends Og{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 m=et(l),x=gt(u);return new Qe(m,x)}}const TX=Yn(St);class XCe extends Og{project(l,u){const m=(u=Yn(u))*u,x=m*m;return{x:.5*((l=Yn(l))*(.8707-.131979*m+x*(x*(.003971*m-.001529*x)-.013791))/Math.PI+.5),y:1-.5*(u*(1.007226+m*(.015085+x*(.028874*m-.044475-.005916*x)))/Math.PI+1),z:0}}unproject(l,u){l=(2*l-.5)*Math.PI;let m=u=(2*(1-u)-1)*Math.PI,x=25,b=0,S=m*m;do{S=m*m;const O=S*S;b=(m*(1.007226+S*(.015085+O*(.028874*S-.044475-.005916*O)))-u)/(1.007226+S*(.045255+O*(.259866*S-.311325-.005916*11*O))),m=fe(m-b,-TX,TX)}while(Math.abs(b)>1e-6&&--x>0);S=m*m;const j=fe(lo(l/(.8707+S*(S*(S*S*S*(.003971-.001529*S)-.013791)-.131979))),-180,180),C=lo(m);return new Qe(j,C)}}const EX=Yn(St);class QCe extends Og{project(l,u){u=Yn(u),l=Yn(l);const m=Math.cos(u),x=2/Math.PI,b=Math.acos(m*Math.cos(l/2)),S=Math.sin(b)/b,j=.5*(l*x+2*m*Math.sin(l/2)/S)||0,C=.5*(u+Math.sin(u)/S)||0;return{x:.5*(j/Math.PI+.5),y:1-.5*(C/Math.PI+1),z:0}}unproject(l,u){let m=l=(2*l-.5)*Math.PI,x=u=(2*(1-u)-1)*Math.PI,b=25;const S=1e-6;let j=0,C=0;do{const O=Math.cos(x),z=Math.sin(x),U=2*z*O,q=z*z,K=O*O,X=Math.cos(m/2),J=Math.sin(m/2),ne=2*X*J,ae=J*J,he=1-K*X*X,ce=he?1/he:0,ye=he?Math.acos(O*X)*Math.sqrt(1/he):0,Ee=.5*(2*ye*O*J+2*m/Math.PI)-l,ke=.5*(ye*z+x)-u,He=.5*ce*(K*ae+ye*O*X*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*X+ye*ae*O)+.5,Ve=$e*Ge-Ue*He;j=(ke*$e-Ee*Ue)/Ve,C=(Ee*Ge-ke*He)/Ve,m=fe(m-j,-Math.PI,Math.PI),x=fe(x-C,-EX,EX)}while((Math.abs(j)>S||Math.abs(C)>S)&&--b>0);return new Qe(lo(m),lo(x))}}class AX extends Og{constructor(l){super(l),this.center=l.center||[0,0],this.parallels=l.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Yn(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:m,cosPhi:x}=this;return{x:Yn(l)*x*m+.5,y:-Math.sin(Yn(u))/x*m+.5,z:0}}unproject(l,u){const{scale:m,cosPhi:x}=this,b=-(u-.5)/m,S=fe(lo((l-.5)/m)/x,-180,180),j=Math.asin(fe(b*x,-1,1)),C=fe(lo(j),-85.051129,St);return new Qe(S,C)}}class JCe extends SX{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,m){const x=BE(l,u,m);return or(x,x,zE(kf(m))),{x:x[0],y:x[1],z:x[2]}}locationPoint(l,u,m){const x=Be(u.lat,u.lng),b=pt([],x),S=m?l._centerAltitude+m:l.elevation?l.elevation.getAtPointOrZero(l.locationCoordinate(u),l._centerAltitude):l._centerAltitude;rt(x,x,b,ot(1,0)*ar*S);const j=R(new Float64Array(16));return M(j,l.pixelMatrix,l.globeMatrix),or(x,x,j),new Ot(x[0],x[1])}pixelsPerMeter(l,u){return ot(1,0)*u}pixelSpaceConversion(l,u,m){const x=ot(1,l)*u,b=Xr(ot(1,45)*u,x,m);return this.pixelsPerMeter(l,u)/b}createTileMatrix(l,u,m){const x=D5(kf(m.canonical));return M(new Float64Array(16),l.globeMatrix,x)}createInversionMatrix(l,u){const{center:m}=l,x=zE(kf(u));return W(x,x,Yn(m.lng)),G(x,x,Yn(m.lat)),V(x,x,[l._pixelsPerMercatorPixel,l._pixelsPerMercatorPixel,1]),Float32Array.from(x)}pointCoordinate(l,u,m,x){return UK(l,u,m,!0)||new Ar(0,0)}pointCoordinate3D(l,u,m){const x=this.pointCoordinate(l,u,m,0);return[x.x,x.y,x.z]}isPointAboveHorizon(l,u){return!UK(l,u.x,u.y,!1)}farthestPixelDistance(l){const u=function(x,b){const S=x.cameraToCenterDistance,j=x._centerAltitude*b,C=x._camera,O=x._camera.forward(),z=me([],We([],O,-S),[0,0,j]),U=x.worldSize/(2*Math.PI),q=[0,0,-U],K=x.width/x.height,X=Math.tan(x.fovAboveCenter),J=We([],C.up(),X),ne=We([],C.right(),X*K),ae=pt([],me([],me([],O,J),ne)),he=[];let ce;if(new In(z,ae).closestPointOnSphere(q,U,he)){const ye=me([],he,q),Ee=tr([],ye,z);ce=Math.cos(x.fovAboveCenter)*Me(Ee)}else{const ye=tr([],z,q),Ee=tr([],q,z);pt(Ee,Ee);const ke=Me(ye)-U;ce=Math.sqrt(ke*(ke+2*U));const He=Math.acos(ce/(U+ke))-Math.acos(Nt(O,Ee));ce*=Math.cos(He)}return 1.01*ce}(l,this.pixelsPerMeter(l.center.lat,l.worldSize)),m=Xm(l.zoom);if(m>0){const x=bX(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,x+b*(1-Math.cos(S)),Math.pow(m,10))}return u}upVector(l,u,m){return BE(u,m,l,1)}upVectorScale(l){return{metersToTile:tN(nN(kf(l)))}}}function jX(h){const l=h.parallels,u=!!l&&Math.abs(l[0]+l[1])<.01;switch(h.name){case"mercator":return new SX(h);case"equirectangular":return new YCe(h);case"naturalEarth":return new XCe(h);case"equalEarth":return new KCe(h);case"winkelTripel":return new QCe(h);case"albers":return u?new AX(h):new WCe(h);case"lambertConformalConic":return u?new AX(h):new ZCe(h);case"globe":return new JCe(h)}throw new Error(`Invalid projection name: ${h.name}`)}class eIe{constructor(l,u){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=u,this.appearances=l;const m=l.map(x=>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:!Om(S),stateDependent:!gg(S),zoomDependent:!Ad(S,["zoom"]),pitchDependent:!Ad(S,["pitch"]),brightnessDependent:!Ad(S,["brightness","measure-light"]),worldviewDependent:!Ad(S,["worldview"])}}(x));this.anyFeatureDependent=m.some(x=>x.featureDependent),this.anyStateDependent=m.some(x=>x.stateDependent)}update(l,u){const m=this.lastParams,x=!m||m.zoom!==l.zoom||m.pitch!==(l.pitch||0)||m.brightness!==(l.brightness||0)||m.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(!x&&!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 x=0;xS-j),b=new Map;for(const S of x){const j=m.get(S);b.set(S,new ji(j))}return u&&(this.cachedBatchIndices=x,this.cachedBatchSegments=b),{batchIndices:x,batchSegments:b}}snapshotSymbolVertexData(l,u){const m=l*Pb;return this.layoutVertexArray.uint16.slice(m,m+u*Pb)}restoreSymbolVertexData(l,u){this.layoutVertexArray.uint16.set(u,l*Pb)}updateSymbolVertexData(l,u,m,x,b,S,j,C,O,z,U,q,K){const X=this.layoutVertexArray.uint16,J=l*Pb;X[J]=u,X[J+1]=m,X[J+2]=x,X[J+3]=b,X[J+4]=S,X[J+5]=j,X[J+6]=C,X[J+7]=O,X[J+8]=z,X[J+9]=U,X[J+10]=q,X[J+11]=K}upload(l,u,m,x,b,S){this.isEmpty()||(m&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,nCe.members,!!S),this.indexBuffer=l.createIndexBuffer(this.indexArray,u),this.dynamicLayoutVertexBuffer=l.createVertexBuffer(this.dynamicLayoutVertexArray,sCe.members,!0),this.opacityVertexBuffer=l.createVertexBuffer(this.opacityVertexArray,rIe,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=l.createVertexBuffer(this.iconTransitioningVertexArray,cCe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,iCe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,aCe.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=l.createVertexBuffer(this.orientationVertexArray,lCe.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=l.createVertexBuffer(this.featureIdArray,oCe.members,!1))),(m||x)&&(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())}}br(U4,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class V4{constructor(l,u,m){this.layoutVertexArray=new l,this.layoutAttributes=u,this.indexArray=new m,this.segments=new ji,this.collisionVertexArray=new _0,this.collisionVertexArrayExt=new bh}upload(l){this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=l.createVertexBuffer(this.collisionVertexArray,uCe.members,!0),this.collisionVertexBufferExt=l.createVertexBuffer(this.collisionVertexArrayExt,dCe.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}br(V4,"CollisionBuffers");class Eh{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=P0(this.zoom,u["text-size"],this.worldview,l.availableImages),this.iconSizeData=P0(this.zoom,u["icon-size"],this.worldview,l.availableImages);const m=this.layers[0].layout,x=m.get("symbol-sort-key"),b=m.get("symbol-z-order");this.lut=l.lut,this.canOverlap=m.get("text-allow-overlap")||m.get("icon-allow-overlap")||m.get("text-ignore-placement")||m.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&x.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=m.get("text-writing-mode").map(S=>Lc[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 m=Array.isArray(l)?l:[l];return u.some(x=>m.some(b=>x.hasLayoutProperty(b)))}getAppearanceFeatureData(l){return this.featureAppearanceData.get(l)}createArrays(){this.text=new U4(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("text")||l.startsWith("symbol"))),this.icon=new U4(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("icon")||l.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new T4(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new T4(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new YI,this.lineVertexArray=new w0,this.symbolInstances=new KI}calculateGlyphDependencies(l,u,m,x,b){for(const S of l){const j=S.codePointAt(0);if(j===void 0)break;if(u[j]=!0,x&&b&&j<=65535){const C=s2[S];C&&(u[C.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(l,u,m,x,b,S,j){if(!l.hasLayoutProperty("icon-size"))return j*S;let C=1;const O=l.getUnevaluatedLayoutProperty("icon-size"),z=P0(this.zoom,O,this.worldview,b),U=kb(z,u);if(z.kind!=="constant"&&z.kind!=="camera"||(C=U.uSize),z.kind==="composite"){const{minZoom:q,maxZoom:K}=z,X=O.possiblyEvaluate(new ri(q,{worldview:this.worldview}),x),J=O.possiblyEvaluate(new ri(K,{worldview:this.worldview}),x),ne=X.evaluate(m,{},x,b);C=ne+(J.evaluate(m,{},x,b)-ne)*U.uSizeT}return z.kind==="source"&&(C=O.possiblyEvaluate(new ri(this.zoom,{worldview:this.worldview}),x).evaluate(m,{},x,b)),C*S}updateFootprints(l,u){}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);return!fN(this.activeReplacements,m)&&(this.activeReplacements=m,!0)}getResolvedImageFromTokens(l){return typeof l=="string"?Fl.build(l):l}populate(l,u,m,x){const b=this.layers[0],S=b.layout,j=this.projection.name==="globe",C=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),[X,J]=S.get("text-size-scale-range"),ne=fe(u.scaleFactor||1,X,J),ae=(O.value.kind!=="constant"||O.value.value instanceof Lo&&!O.value.value.isEmpty()||O.value.value.toString().length>0)&&(C.value.kind!=="constant"||C.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,ke=u.glyphDependencies,He=u.availableImages,$e=new ri(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:wt,sourceLayerIndex:jt}=Ue,It=b._featureFilter.needGeometry,kt=wn(Ve,It);if(!b._featureFilter.filter($e,kt,m))continue;if(It||(kt.geometry=Ur(Ve,m,x)),j&&Ve.type!==1&&m.z<=5){const ir=kt.geometry,nr=.98078528056,Yt=(pr,jr)=>Nt(BE(pr.x,pr.y,m,1),BE(jr.x,jr.y,m,1)){if(!ir.getLayoutProperty("icon-image"))return;const nr=this.getCombinedIconPrimary(ir,Ct,kt,m,He,Kt,K);nr&&Ge(nr)}),Bt){const ir=C.evaluate(kt,{},m).join(","),nr=S.get("text-rotation-alignment")==="map"&&S.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Lc.vertical)>=0;for(const Yt of Bt.sections)if(Yt.image){const pr=Yt.image.getPrimary().scaleSelf(this.pixelRatio*ne),jr=pr.id.toString(),zr=Ee.get(jr)||[];zr.push(pr),Ee.set(jr,zr)}else{const pr=oE(Bt.toString()),jr=Yt.fontStack||ir,zr=ke[jr]=ke[jr]||{};this.calculateGlyphDependencies(Yt.text,zr,nr,this.allowVerticalPlacement,pr)}}}if(S.get("symbol-placement")==="line"&&(this.features=function(Ue){const Ve={},yt={},wt=[];let jt=0;function It(Ct){wt.push(Ue[Ct]),jt++}function kt(Ct,Lt,Ut){const Kt=yt[Ct];return delete yt[Ct],yt[Lt]=Kt,wt[Kt].geometry[0].pop(),wt[Kt].geometry[0]=wt[Kt].geometry[0].concat(Ut[0]),Kt}function Bt(Ct,Lt,Ut){const Kt=Ve[Lt];return delete Ve[Lt],Ve[Ct]=Kt,wt[Kt].geometry[0].shift(),wt[Kt].geometry[0]=Ut[0].concat(wt[Kt].geometry[0]),Kt}function mt(Ct,Lt,Ut){const Kt=Ut?Lt[0][Lt[0].length-1]:Lt[0][0];return`${Ct}:${Kt.x}:${Kt.y}`}for(let Ct=0;CtCt.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,m,x,b,S,j){let C,O;if(l.hasLayoutProperty("icon-image")){const z=u.getAppearanceValueAndResolveTokens(l,"icon-image",m,x,b);C=this.getResolvedImageFromTokens(z)}else{const z=u.getValueAndResolveTokens("icon-image",m,x,b);C=this.getResolvedImageFromTokens(z)}if(C){const z=l.hasLayoutProperty("icon-size")?l.getUnevaluatedLayoutProperty("icon-size"):u._unevaluatedLayout._values["icon-size"];O=u2(C,P0(this.zoom,z,this.worldview,b),z,x,this.zoom,S,this.pixelRatio,j,this.worldview,b).iconPrimary}return O}updateSymbolInstanceIconVertices(l,u,m,x,b,S){const{canonical:j,availableImages:C,globalProperties:O,layer:z,iconScaleFactor:U,featureState:q,layoutIconOffset:K,layoutIconSize:X,layoutIconRotate:J}=S;if(l.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(u.activeAppearanceIndex===m)return{vertexOffsetDelta:l.numIconVertices,hasChanges:!1};const ne=m>=0?z.appearances[m]:null;if(ne){const ae=this.getCombinedIconPrimary(ne,z,x,j,C,{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}=mX(ne,z,x,j,K,J,X,U);let ke=PN(ce,void 0,ye,z.layout.get("icon-anchor").evaluate(x,q,j));const He=ce.sdf,$e=z.layout.get("icon-text-fit").constantOr("none");$e!=="none"&&u.textShaping&&u.iconTextFitPadding&&u.fontScale&&(ke=C4(ke,u.textShaping,$e,u.iconTextFitPadding,ye,u.fontScale));const Ge=this.calculateEffectiveAppearanceIconSize(ne,O.zoom,x,j,C,U,X),Ue=0,Ve=1+(Math.min(R0,Math.round(Ge*ep))<<1),yt=M4(ke,Ee,He,$e!=="none",U);u.isUsingAppearanceIconVertexData||(u.isUsingAppearanceIconVertexData=!0,u.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(b,l.numIconVertices));const wt=Math.floor(l.numIconVertices/4),jt=Math.min(yt.length,wt);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===m)return{vertexOffsetDelta:l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices,hasChanges:!1};const Ee=m>=0?C.appearances[m]:null;if(Ee&&u.textShaping){const{appearanceTextOffset:ke,appearanceTextRotate:He,appearanceTextSize:$e}=pX(Ee,C,x,j,q,X,K);u.fontScale=_X($e,u.textScaleFactor);const Ge=Ee.getUnevaluatedLayoutProperty("text-size");let Ue=this.textSizeData,Ve=ae,yt=he;Ee.hasLayoutProperty("text-size")&&(Ue=P0(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 wt=u.textShaping.bottom-q[1],jt=u.textShaping.left-q[0],It=u.textShaping.right-q[0];u.textShaping.top=ke[1]+(u.textShaping.top-q[1]),u.textShaping.bottom=ke[1]+wt,u.textShaping.left=ke[0]+jt,u.textShaping.right=ke[0]+It;const kt=hX(0,u.textShaping,ke,C,!1,x,z,this.allowVerticalPlacement,He),Bt=$e&&Ue.kind==="composite"?Ge.possiblyEvaluate(new ri(Ve,{}),j).evaluate(x,U,j):J,mt=$e&&Ue.kind==="composite"?Ge.possiblyEvaluate(new ri(yt,{}),j).evaluate(x,U,j):ne,Ct=z4(Ee.name,Ue,$e,O,Bt,mt),Lt=Array.isArray(Ct)?Ct[1]:$e,Ut=0,Kt=1+(Math.min(R0,Math.round(Lt*ep))<<1);u.isUsingAppearanceTextVertexData||(u.isUsingAppearanceTextVertexData=!0,u.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(b,l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices));for(let _r=0;_r0){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,C,m,l,j),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(O,b[0],u,C,m,l,j)}}}updateRoadElevation(l){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let u=!1;const m=Dt(l),x=1/m;let b=!1,S=!1;for(let j=0;j0||q>0,ne=K>0,ae=this.elevationFeatures[C.elevationFeatureIndex];if(ae){const he=new Ot(C.tileAnchorX,C.tileAnchorY),ce=.075+ae.pointElevation(he);C.zOffset!==ce&&(u=!0,C.zOffset=ce),ce!==0&&(this.hasAnyZOffset=!0);const ye=ae.computeSlopeNormal(he,x),Ee=la(Xt(),Ae(0,0,1),ye);nn(O,O,Ee),nn(z,z,Ee),O[2]*=m,z[2]*=m,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&&(VN(this.text.orientationVertexArray,U,O,z),VN(this.text.orientationVertexArray,q,O,z)),ne){const{placedIconSymbolIndex:he,verticalPlacedIconSymbolIndex:ce}=C;he>=0&&VN(this.icon.orientationVertexArray,K,O,z),ce>=0&&VN(this.icon.orientationVertexArray,X,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,j)=>{m+=S,m>b.length&&b.resize(m);for(let C=-S;C<0;C++)b.emplace(C+m,j)},u=(b,S,j)=>{x+=S,x>b.length&&b.resize(x);for(let C=-S;C<0;C++)b.emplace(C+x,j)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let m=0,x=0;for(let b=0;b0;if((j>0||C>0)&&(l(this.text.zOffsetVertexArray,j,z),l(this.text.zOffsetVertexArray,C,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,m,x,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,m,x,b,S=!1){const j={hasLayoutChanges:!1,hasUboChanges:!1};if(!l||!m||!this.featureAppearanceData)return j;const C=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 j;const U=this.layers[0],q=U.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===U.appearancesVersion||(this.featureAppearances=new eIe(U.appearances,U.appearancesVersion));const K=this.featureAppearances.update(x,S);if(K.kind==="no-changes")return j;let X=1,J=0,ne=!1,ae=!1;if(O){const[ke,He]=q.get("icon-size-scale-range");X=fe(1,ke,He)}let he=1,ce=0,ye=!1;if(z){const[ke,He]=q.get("text-size-scale-range");he=fe(1,ke,He)}const Ee=new Map;if(b&&m)for(const ke of m){const He=b.getImage(ke,U.scope);if(He){const $e=new du(ke.toString());Ee.set($e.toString(),He)}}for(let ke=0;keIt.isActive({globals:x,feature:Ve,canonical:l,featureState:Ue})):-1;yt=jt>=0?jt:-1}const wt=$e.activeAppearanceIndex!==yt;if(z){const jt=q.get("text-size"),It=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,kt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Bt={canonical:l,layer:U,featureState:Ue,availableImages:m,textScaleFactor:he,imageMap:Ee,layoutTextOffset:q.get("text-offset").evaluate(Ve,Ue,l).map(Ct=>Ct*Ma),layoutTextSize:jt.evaluate(Ve,Ue,l),layoutTextRotate:q.get("text-rotate").evaluate(Ve,Ue,l),layoutMinZoomSize:jt.evaluate(Ve,{zoom:It},l),layoutMaxZoomSize:jt.evaluate(Ve,{zoom:kt},l),layoutTextSizeMinZoom:It,layoutTextSizeMaxZoom:kt},mt=this.updateSymbolInstanceTextVertices(He,$e,yt,Ve,ce,Bt);ce+=mt.vertexOffsetDelta,ye=ye||mt.hasChanges}if(O){const jt={canonical:l,layer:U,featureState:Ue,availableImages:m,globalProperties:x,iconScaleFactor:X,layoutIconOffset:q.get("icon-offset").evaluate(Ve,Ue,l),layoutIconSize:q.get("icon-size").evaluate(Ve,Ue,l,m),layoutIconRotate:q.get("icon-rotate").evaluate(Ve,Ue,l)},It=this.updateSymbolInstanceIconVertices(He,$e,yt,Ve,J,jt);J+=It.vertexOffsetDelta,ne=ne||It.hasChanges}if(wt){const jt=He.featureIndex,It=x?x.brightness:null,kt=Ue||{},Bt=yt>=0?U.appearances[yt]:null;this.text.uboBinder&&(this.text.uboBinder.layer=U,ae=this.text.uboBinder.updateFeaturePaintForAppearance(jt,Ve,kt,l,m,It,Bt)||ae),this.icon.uboBinder&&(this.icon.uboBinder.layer=U,ae=this.icon.uboBinder.updateFeaturePaintForAppearance(jt,Ve,kt,l,m,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=jX(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(l,u){const m=this.lineVertexArray.length;if(l.segment!==void 0)for(const{x,y:b}of u)this.lineVertexArray.emplaceBack(x,b);return{lineStartIndex:m,lineLength:this.lineVertexArray.length-m}}addSymbols(l,u,m,x,b,S,j,C,O,z,U,q,K,X,J,ne,ae,he){const ce=l.indexArray,ye=l.layoutVertexArray,Ee=l.globeExtVertexArray,ke=he,He=l.uboBinder?l.uboBinder.getCurrentBatchIndex():void 0,$e=l.segments.prepareSegment(4*ke,ye,ce,this.canOverlap?S.sortKey:void 0,He),Ge=this.glyphOffsetArray.length,Ue=$e.vertexLength,Ve=this.allowVerticalPlacement&&j===Lc.vertical?Math.PI/2:0,yt=S.text&&S.text.sections;let wt=ye.length,jt=-1;for(let Bt=0;Bt=0)){const Bt=4*It;for(let mt=0;mt=0?u.rightJustifiedTextSymbolIndex:u.centerJustifiedTextSymbolIndex>=0?u.centerJustifiedTextSymbolIndex:u.leftJustifiedTextSymbolIndex>=0?u.leftJustifiedTextSymbolIndex:u.verticalPlacedTextSymbolIndex>=0?u.verticalPlacedTextSymbolIndex:x),S=I4(this.textSizeData,l,b)/Ma;return this.tilePixelRatio*S}getSymbolInstanceIconSize(l,u,m){const x=this.icon.placedSymbolArray.get(m),b=I4(this.iconSizeData,l,x);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(l,u,m,x){l.emplaceBack(u,-m,-m,x),l.emplaceBack(u,m,-m,x),l.emplaceBack(u,m,m,x),l.emplaceBack(u,-m,m,x)}_updateTextDebugCollisionBoxes(l,u,m,x,b,S,j){for(let C=x;C0}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 m=l.placedSymbolArray.get(u),x=m.vertexStartIndex+4*m.numGlyphs;for(let b=m.vertexStartIndex;bx[j]-x[C]||b[C]-b[j]),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 m=this.sortKeyRanges[this.sortKeyRanges.length-1];m&&m.sortKey===u?m.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 m=this.symbolInstances.get(u);this.featureSortOrder.push(m.featureIndex);const{rightJustifiedTextSymbolIndex:x,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:S,verticalPlacedTextSymbolIndex:j,placedIconSymbolIndex:C,verticalPlacedIconSymbolIndex:O}=m;x>=0&&this.addIndicesForPlacedSymbol(this.text,x),b>=0&&b!==x&&this.addIndicesForPlacedSymbol(this.text,b),S>=0&&S!==b&&S!==x&&this.addIndicesForPlacedSymbol(this.text,S),j>=0&&this.addIndicesForPlacedSymbol(this.text,j),C>=0&&this.addIndicesForPlacedSymbol(this.icon,C),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 m=(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 x of this.symbolsByBatch.values())for(const b of x){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 x=0;xb.rotatedY-S.rotatedY||S.featureIndex-b.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(l,u){for(const m of l){const x=m.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){m.primitiveOffset=this.text.indexArray.length,m.primitiveLength=0;continue}m.primitiveOffset=this.text.indexArray.length;const S=this.text.indexArray.length;for(const{index:j}of b){const C=this.symbolInstances.get(j),{rightJustifiedTextSymbolIndex:O,centerJustifiedTextSymbolIndex:z,leftJustifiedTextSymbolIndex:U,verticalPlacedTextSymbolIndex:q}=C;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)}m.primitiveLength=this.text.indexArray.length-S}}rebuildIconSegmentIndices(l,u){for(const m of l){const x=m.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){m.primitiveOffset=this.icon.indexArray.length,m.primitiveLength=0;continue}m.primitiveOffset=this.icon.indexArray.length;const S=this.icon.indexArray.length;for(const{index:j}of b){const C=this.symbolInstances.get(j),{placedIconSymbolIndex:O,verticalPlacedIconSymbolIndex:z}=C;O>=0&&this.addIndicesForPlacedSymbol(this.icon,O),z>=0&&this.addIndicesForPlacedSymbol(this.icon,z)}m.primitiveLength=this.icon.indexArray.length-S}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const l=Math.sin(this.sortedAngle),u=Math.cos(this.sortedAngle),m=this.getOrCreateSortedSymbolsByBatch(l,u),x=Array.from(m.keys()).sort((b,S)=>b-S);for(const b of x){const S=m.get(b);for(const{index:j}of S){const C=this.symbolInstances.get(j);this.featureSortOrder.push(C.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),m),this.rebuildIconSegmentIndices(this.icon.segments.get(),m),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 m;return this.elevationFeatures&&um in h?String(h[m]):"")}let CX,IX,q4;br(Eh,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Eh.addDynamicAttributes=Nb;class NX{constructor(l){this.type=l.property.overrides?l.property.overrides.runtimeType:fh,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}}br(NX,"FormatSectionOverride",{omit:["defaultValue"]});const G4=()=>q4||(q4={layout:CX||(CX=new rs({"symbol-placement":new Qt(nt.layout_symbol["symbol-placement"]),"symbol-spacing":new Qt(nt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Qt(nt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new qt(nt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Qt(nt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new Qt(nt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new Qt(nt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new Qt(nt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Qt(nt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Qt(nt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Qt(nt.layout_symbol["icon-rotation-alignment"]),"icon-size":new qt(nt.layout_symbol["icon-size"]),"icon-size-scale-range":new Qt(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 Qt({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new qt(nt.layout_symbol["icon-rotate"]),"icon-padding":new Qt(nt.layout_symbol["icon-padding"]),"icon-keep-upright":new Qt(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 Qt(nt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Qt(nt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Qt(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 Qt(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 Qt(nt.layout_symbol["text-variable-anchor"]),"text-anchor":new qt(nt.layout_symbol["text-anchor"]),"text-max-angle":new Qt(nt.layout_symbol["text-max-angle"]),"text-writing-mode":new Qt(nt.layout_symbol["text-writing-mode"]),"text-rotate":new qt(nt.layout_symbol["text-rotate"]),"text-padding":new Qt(nt.layout_symbol["text-padding"]),"text-keep-upright":new Qt(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 Qt(nt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Qt(nt.layout_symbol["text-ignore-placement"]),"text-optional":new Qt(nt.layout_symbol["text-optional"]),visibility:new Qt(nt.layout_symbol.visibility)})),paint:IX||(IX=new rs({"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"]),"icon-translate-anchor":new Qt(nt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new Qt(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:_l,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"]),"text-translate-anchor":new Qt(nt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new Qt(nt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new Qt(nt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new Qt(nt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new Qt(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"})}))},q4);class qN extends Jo{constructor(l,u,m,x){super(l,G4(),u,m,x,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(x=>{x.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 m=this.layout.get("text-writing-mode");if(m){const x=[];for(const b of m)x.indexOf(b)<0&&x.push(b);this.layout._values["text-writing-mode"]=x}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(l,u,m,x){return this._saturation===l&&this._contrast===u&&this._brightnessMin===m&&this._brightnessMax===x||(this._colorAdjustmentMatrix=function(b,S,j,C){b=as(b),S=Ri(S);const O=k(),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,X=C-j;return M(O,[X,0,0,0,0,X,0,0,0,0,X,0,j,j,j,1],[S,0,0,0,0,S,0,0,0,0,S,0,K,K,K,1]),M(O,O,q),O}(l,u,m,x),this._saturation=l,this._contrast=u,this._brightnessMin=m,this._brightnessMax=x),this._colorAdjustmentMatrix}getValueAndResolveTokens(l,u,m,x){const b=this.layout.get(l).evaluate(u,{},m,x),S=this._unevaluatedLayout._values[l];return S.isDataDriven()||o0(S.value)||!b?b:kX(u.properties,b)}getAppearanceValueAndResolveTokens(l,u,m,x,b){const S=l.getLayoutProperty(u);if(!S)return;const j=S.evaluate(m,{},x,b),C=l.getUnevaluatedLayoutProperties()._values[u];return C.isDataDriven()||o0(C.value)||!j||typeof j!="string"?j:kX(m.properties,j)}createBucket(l){return new Eh(l)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const l of G4().paint.overridableProperties){if(!qN.hasPaintOverride(this.layout,l))continue;const u=this.paint.get(l),m=new NX(u),x=new Wv(m,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 wg("source",x):new Bm("composite",x,u.value.zoomStops,u.value.interpolationType),this.paint._values[l]=new Vm(u.property,b,u.parameters)}}_handleOverridablePaintPropertyUpdate(l,u,m){return!(!this.layout||u.isDataDriven()||m.isDataDriven())&&qN.hasPaintOverride(this.layout,l)}static hasPaintOverride(l,u){const m=l.get("text-field"),x=G4().paint.properties[u];let b=!1;const S=j=>{for(const C of j)if(x.overrides&&x.overrides.hasOverride(C))return void(b=!0)};if(m.value.kind==="constant"&&m.value.value instanceof Lo)S(m.value.value.sections);else if(m.value.kind==="source"){const j=O=>{b||(O instanceof Ir&&Cs(O.value)===Ox?S(O.value.sections):O instanceof Pm?S(O.sections):O.eachChild(j))},C=m.value;C._styleExpression&&j(C._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(l,u,m){return{config:new ee(this,{zoom:u,lut:m}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let PX,RX,LX,DX;var GN=Pn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function HN(h,l,u,m,x,b,S,j){const C=[h,l,1,u,m,1,x,b,1],O=[S,j,1],z=T([],C),[U,q,K]=Sr(O,O,z);return E(C,C,[U,0,0,0,q,0,0,0,K])}function MX(h,l,u,m,x,b,S,j){const C=function(O,z,U,q,K,X,J,ne){const ae=HN(0,0,1,0,1,1,0,1),he=HN(O,z,U,q,K,X,J,ne);return E(he,he,T([],ae))}(h,l,u,m,x,b,S,j);return[C[2]/C[8]/ar,C[5]/C[8]/ar]}function WN(h){return[h[0],Math.min(Math.max(h[1],-85.051129),St)]}class OX extends Mx{constructor(l,u,m,x){super(),this.id=l,this.dispatcher=m,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(x),this.options=u,this._dirty=!1}load(l,u){if(this._loaded=u||!1,this.fire(new Ou("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return l&&(this.coordinates=l),this._loaded=!0,void this._finishLoading();this._imageRequest=ag(this.map._requestManager.transformRequest(this.url,Lx.Image),(m,x)=>{this._imageRequest=null,this._loaded=!0,m?this.fire(new og(m)):x&&(this.image=x,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 r2(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 Ou("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 r2||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],m=l[0][1];for(const b of l)b[1]>m&&(m=b[1]),b[1]St?this.onNorthPole=!0:x<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const b=l.map(Ar.fromLngLat);this.tileID=function(S){let j=1/0,C=1/0,O=-1/0,z=-1/0;for(const J of S)j=Math.min(j,J.x),C=Math.min(C,J.y),O=Math.max(O,J.x),z=Math.max(z,J.y);const U=Math.max(O-j,z-C),q=Math.max(0,Math.floor(-Math.log2(U))),K=Math.pow(2,q);let X=Math.floor((j+O)/2*K);return X>1&&(X-=1),new j0(q,X,Math.floor((C+z)/2*K))}(b),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Ou("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof r2||(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=L0(new j0(0,0,0),this.map.transform.projection),m=[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,ke=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*ke-Ee*ye,Ve=Ee*$e-He*ke,yt=He*he-ae*$e;return Ge>0&&Ue>0&&Ve>0&&yt>0||Ge<0&&Ue<0&&Ve<0&&yt<0}(m))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const x=L0(this.tileID,this.map.transform.projection),[b,S,j,C]=this.coordinates.map(ne=>{const ae=x.projection.project(ne[0],ne[1]);return wX(x,ae)._round()});this.perspectiveTransform=MX(b.x,b.y,S.x,S.y,j.x,j.y,C.x,C.y);const O=this._boundsArray=new bo;O.emplaceBack(b.x,b.y,0,0),O.emplaceBack(S.x,S.y,ar,0),O.emplaceBack(C.x,C.y,0,ar),O.emplaceBack(j.x,j.y,ar,ar),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=l.createVertexBuffer(O,GN.members),this.boundsSegments=ji.simpleSegment(0,0,4,2);const z=[],U=function(ne){return[WN(ne[0]),WN(ne[1]),WN(ne[2]),WN(ne[3])]}(this.coordinates),[q,K,X,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 bo,[ae,he,ce,ye]=function(kt){let Bt=kt[0].x,mt=Bt,Ct=kt[0].y,Lt=Ct;for(let Ut=1;Utmt&&(mt=kt[Ut].x),kt[Ut].yLt&&(Lt=kt[Ut].y);return[Bt,Ct,mt-Bt,Lt-Ct]}(m),Ee=kt=>[(kt.x-ae)/ce,(kt.y-he)/ye],[ke,He,$e,Ge]=m.map(Ee),Ue=function(kt,Bt,mt,Ct,Lt,Ut,Kt,_r){const ir=HN(0,0,1,0,1,1,0,1);return E(ir,ir,T([],HN(kt,Bt,mt,Ct,Lt,Ut,Kt,_r)))}(ke[0],ke[1],He[0],He[1],$e[0],$e[1],Ge[0],Ge[1]);this.elevatedGlobePerspectiveTransform=MX(ke[0],ke[1],He[0],He[1],$e[0],$e[1],Ge[0],Ge[1]);const Ve=(kt,Bt)=>{z.push(kt.lng);const mt=Math.round((kt.lng-q)/X*ar),Ct=Math.round((kt.lat-K)/J*ar),Lt=Ee(Bt),Ut=Sr([],[Lt[0],Lt[1],1],Ue),Kt=Math.round(Ut[0]/Ut[2]*ar),_r=Math.round(Ut[1]/Ut[2]*ar);ne.emplaceBack(mt,Ct,Kt,_r)},yt=m[3].x-m[0].x,wt=m[3].y-m[0].y,jt=m[2].x-m[1].x,It=m[2].y-m[1].y;for(let kt=0;kt<65;kt++){const Bt=kt/64,mt=[m[0].x+Bt*yt,m[0].y+Bt*wt],Ct=[m[1].x+Bt*jt,m[1].y+Bt*It],Lt=Ct[0]-mt[0],Ut=Ct[1]-mt[1];for(let Kt=0;Kt<65;Kt++){const _r=Kt/64,ir={x:mt[0]+Lt*_r,y:mt[1]+Ut*_r};Ve(u.projection.unproject(ir.x,ir.y),ir)}}this.elevatedGlobeVertexBuffer=l.createVertexBuffer(ne,GN.members)}{this.maxLongitudeTriangleSize=0;let ne=[],ae=new vs;const he=(ce,ye,Ee)=>{ae.emplaceBack(ce,ye,Ee);const ke=z[ce],He=z[ye],$e=z[Ee],Ge=Math.min(Math.min(ke,He),$e),Ue=Math.max(Math.max(ke,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,ke=Ee+1,He=Ee+65,$e=He+1;he(Ee,He,ke),he(ke,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 ke=[],He=new vs;for(let $e=0;$e{S.segments.push({vertexOffset:0,primitiveOffset:U,vertexLength:u.segments[0].vertexLength,primitiveLength:q,sortKey:void 0,vaos:{}})},C=.51*this.maxLongitudeTriangleSize;if(Math.abs(m[0]-x)<=C){const U=ca(m,0,m.length,x+C);return U===m.length||j(U,ss(m,U+1,m.length,x+360-C)-U),S}x0}}let BX,zX,$X,UX,VX,qX,GX;class HX extends Jo{constructor(l,u,m,x){super(l,{layout:BX||(BX=new rs({visibility:new Qt(nt["layout_raster-particle"].visibility)})),paint:zX||(zX=new rs({"raster-particle-array-band":new Qt(nt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new Qt(nt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Ag(nt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new Qt(nt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new Qt(nt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new Qt(nt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new Qt(nt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new Qt(nt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}))},u,m,x),this._updateColorRamp(),this.lastInvalidatedAt=Ol.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=$E({expression:l,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:u}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Ol.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class sIe extends Jo{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 W4(h,l,u){const m=[0,0,1],x=Pr([]);return ci(x,x,u?-Yn(h)+Math.PI:Yn(h)),Rn(x,x,-Yn(l)),nn(m,m,x),pt(m,m)}class KN{constructor(l,u,m,x){this.message=(l?`${l}: `:"")+m,x&&(this.identifier=x),u!=null&&u.__line__&&(this.line=u.__line__)}}function K4(h,l){const u=h.indexOf("://")===-1;try{return new URL(h,u&&l?"http://example.com":void 0),!0}catch{return!1}}class WX{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 KX{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new PE,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(l){const u=16*l,m=this.instancedDataArray.float32;let x=Math.floor(m[u+2]);const b=1.05*(m[u+2]-x);return x/=100,[m[u]%1*1.05,m[u+1]%1*1.05,b,x]}tileCoordinatesForInstance(l){const u=16*l,m=this.instancedDataArray.float32;let x=m[u+0];return x=x>ar?x-ar:x,new Ot(Math.trunc(x),Math.trunc(m[u+1]))}translationForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+4],m[u+5],m[u+6]]}rotationScaleForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+10],m[u+11],m[u+12],m[u+13],m[u+14],m[u+15]]}transformForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+4],m[u+10],m[u+11],m[u+12],m[u+5],m[u+13],m[u+14],m[u+15],m[u+6],0,0,0,1]}}class Y4{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,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.tileToMeter=Dt(m);const b=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const S=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?u.elevationFeatures:void 0;for(const{feature:j,id:C,index:O,sourceLayerIndex:z}of l){const U=C??(j.properties&&j.properties.hasOwnProperty("id")?j.properties.id:void 0),q=wn(j,b);if(!this.layers[0]._featureFilter.filter(new ri(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,m))continue;const K={id:U,sourceLayerIndex:z,index:O,geometry:b?q.geometry:Ur(j,m,x),properties:j.properties,type:j.type,patterns:{}},X=this.addFeature(K,K.geometry,q,S,m);X&&u.featureIndex.insert(j,K.geometry,O,z,this.index,this.instancesPerModel[X].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const l=this.layers[0].modelManager,u=this.layers[0].scope;let m=0;for(const x of this.modelUris){const b=l.getModel(x,u);if(!b)continue;const S=this.instancesPerModel[x];if(S){const j=.5*at(b.aabb.max,b.aabb.min)*S.maxScale+S.maxXYTranslationDistance,C=Math.min(ar,Math.max(j/this.tileToMeter,256));m=Math.max(C,m)}}return m}update(l,u,m,x){for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];for(const j in l)S.idToFeaturesIndex.hasOwnProperty(j)&&(this.evaluate(S.features[S.idToFeaturesIndex[j]],l[j],S,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let l=!1;for(const u in this.instancesPerModel){const m=this.instancesPerModel[u];for(const x of m.features){const b=this.layers[0],S=x.feature,j=this.canonical,C=b.paint.get("model-rotation").evaluate(S,{},j),O=b.paint.get("model-scale").evaluate(S,{},j),z=b.paint.get("model-translation").evaluate(S,{},j);xr(x.rotation,C)&&xr(x.scale,O)&&xr(x.translation,z)||(this.evaluate(x,x.featureStates,m,!0),l=!0)}}return l}updateReplacement(l,u,m,x){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const b=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);if(fN(this.activeReplacements,b))return!1;this.activeReplacements=b;let S=!1;for(const j in this.instancesPerModel){const C=this.instancesPerModel[j],O=C.instancedDataArray;for(const z of C.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[X+1]);let ce=!1;for(const ye of this.activeReplacements)if(!CY(ye,m,mN.Model,x)&&!(ye.min.x>ae||ae>ye.max.x||ye.min.y>he||he>ye.max.y)&&(ce=LY(RY(ae,he,l.canonical,ye.footprintTileId.canonical),ye.footprint),ce))break;O.float32[X]=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 m=this.instancesPerModel[u];m.instancedDataArray.length<0||m.instancedDataArray.length===0||(m.instancedDataBuffer?m.instancedDataBuffer.updateData(m.instancedDataArray):m.instancedDataBuffer=l.createVertexBuffer(m.instancedDataArray,Tke.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(l){for(const m in this.instancesPerModel){const x=this.instancesPerModel[m];x.instancedDataArray.length!==0&&x.instancedDataBuffer&&x.instancedDataBuffer.destroy()}const u=this.layers[0].modelManager;if(l&&u&&this.modelUris&&this.modelsRequested)for(const m of this.modelUris)u.removeModel(m,"",!0)}addFeature(l,u,m,x,b){const S=this.layers[0],j=S.layout.get("model-id"),C=S.layout.get("model-allow-density-reduction"),O=j.evaluate(m,{},this.canonical);if(!O)return Br(`modelId is not evaluated for layer ${S.id} and it is not going to get rendered.`),O;(K4(O,!1)||this.styleDefinedModelURLs[O]!==void 0)&&(this.modelUris.includes(O)||this.modelUris.push(O)),this.instancesPerModel[O]||(this.instancesPerModel[O]=new KX);const z=this.instancesPerModel[O],U=z.instancedDataArray,q=new WX(m,U.length);let K;x&&(K=Li.getElevationFeature(l,x));for(const X of u)for(const J of X){if(J.x<0||J.x>=ar||J.y<0||J.y>=ar)continue;if(this.lookupDim!==0&&C){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),x){z.instancesRoadElevation||(z.instancesRoadElevation=[]);const ae=K?K.pointElevation(new Ot(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,m,x){const b=this.layers[0],S=l.feature,j=this.canonical,C=l.rotation=b.paint.get("model-rotation").evaluate(S,u,j),O=l.scale=b.paint.get("model-scale").evaluate(S,u,j),z=l.translation=b.paint.get("model-translation").evaluate(S,u,j),U=Object.assign({},b.paint.get("model-color").evaluate(S,u,j));U.a=b.paint.get("model-color-mix-intensity").evaluate(S,u,j);const q=[];this.maxVerticalOffset0?Math.sqrt(K):0;m.maxScale=Math.max(Math.max(m.maxScale,O[0]),Math.max(O[1],O[2])),m.maxXYTranslationDistance=Math.max(m.maxXYTranslationDistance,X),this.maxScale=Math.max(Math.max(this.maxScale,O[0]),Math.max(O[1],O[2])),xZ(q,C,O);const J=Math.round(100*U.a)+U.b/1.05;for(let ne=0;ne10?this.tileToMeter:Dt(j,Ee)),ce[he+4]=z[0],ce[he+5]=z[1],ce[he+6]=z[2]+(m.instancesRoadElevation?m.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],m.instancesEvaluatedElevation[ae]=z[2]}}}br(Y4,"ModelBucket",{omit:["layers"]}),br(KX,"PerModelAttributes"),br(WX,"ModelFeature");class Rb{constructor(l,u,m){this._demTile=l,this._dem=this._demTile.dem,this._scale=u,this._offset=m}static create(l,u,m){const x=m||l.findDEMTileFor(u);if(!x||!x.dem)return;const b=x.dem,S=x.tileID,j=1<O.fqid),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.modelTraits|=Eb.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,x&&(this.modelTraits|=Eb.HasMapboxMeshFeatures),b&&(this.modelTraits|=Eb.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=S,this.worldview=C,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const O of u)this.nodesInfo.push(new QX(O)),ZX(O,j.featureIndexArray.length,j.grid),j.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,j.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(l,u){for(const m of this.getNodesInfo()){const x=m.node;x.footprint&&u.push({footprint:x.footprint,id:l})}}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(l){const u=Object.keys(l).length!==0;if(u&&!this.stateDependentLayers.length)return;const m=u?this.stateDependentLayers:this.layers;if(!Ro(l,this.states))for(const x of m)this.evaluate(x,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 m of u){const x=m.node;this.uploaded?this.updatePbrBuffer(x):f4(x,l,!0)}for(const m of u)jN(m.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(l){let u=!1;if(!l.meshes)return u;for(const m of l.meshes)m.pbrBuffer&&(m.pbrBuffer.updateData(m.featureArray),u=!0);return u}needsReEvaluation(l,u,m){const x=l.transform.projectionOptions,b=l.style.getBrightness(),S=this.brightness!==b;if(!this.uploaded||this.dirty||x.name!==this.projection.name||x2(m.paint.get("model-color").value,S)||x2(m.paint.get("model-color-mix-intensity").value,S)||x2(m.paint.get("model-roughness").value,S)||x2(m.paint.get("model-emissive-strength").value,S)||x2(m.paint.get("model-height-based-emissive-strength-multiplier").value,S)){this.projection=x,this.brightness=b;const j=this.getNodesInfo();for(const C of j)C.state=null;return!0}return!1}evaluateTransform(l,u){if(l.transform.zoom===this.zoom)return;this.zoom=l.transform.zoom;const m=this.getNodesInfo(),x=this.id.canonical;for(const b of m){const S=b.feature;b.evaluatedTranslation=u.paint.get("model-translation").evaluate(S,{},x),b.evaluatedScale=u.paint.get("model-scale").evaluate(S,{},x)}}evaluate(l,u){const m=this.getNodesInfo();for(const x of m){if(!x.node.meshes)continue;const b=x.feature,S=u&&u[b.id];if(Ro(S,x.state))continue;x.state=structuredClone(S);const j=x.node.meshes&&x.node.meshes[0].featureData,C=x.evaluatedColor[2],O=x.evaluatedRMEA[2],z=this.id.canonical;if(x.hasTranslucentParts=!1,j){for(let U=0;U=ke)continue;const Bt=Z4[kt],mt=Math.abs(Bt);mt>Ve&&(Ue=Bt,Ve=mt,yt=It,wt=jt)}if(Ve>.1){const jt=1-(ke+.5*Math.abs(yt*wt))/X;let It=u._dem.get($e,He)+Ue*jt;const kt=u._dem.get($e+yt,He+wt),Bt=u._dem.get($e-yt,He-wt,!0);(It-kt)*(It-Bt)>0&&(It=(kt+Bt)/2),Z4[Ge]=u._dem.set($e,He,It),D0[Ge]=ke}}}}}j&&(u._demTile.needsDEMTextureUpload=!0,u._dem._timestamp=Ol.now())}setFilter(l){this.filter=l?sb(l):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(l=>this.filter.filter(new ri(this.id.overscaledZ,{worldview:this.worldview}),l.feature,this.id.canonical)):this.nodesInfo}destroy(){const l=this.getNodesInfo();for(const u of l)jN(u.node),m4(u.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(l.toUnwrapped());for(const x of this.getNodesInfo()){const b=x.node.footprint;x.hiddenByReplacement=!!b&&!m.find(S=>S.footprint===b)}}getHeightAtTileCoord(l,u){const m=[],x=[0,0,0],b=R([]);for(const S of this.getNodesInfo()){const j=S.node.meshes[0],C=j.transformedAabb;if(lC.max[0]||u>C.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),x[0]=l,x[1]=u,or(x,x,b);const O=(x[0]-j.aabb.min[0])/(j.aabb.max[0]-j.aabb.min[0])*I0|0,z=Math.min(63,(x[1]-j.aabb.min[1])/(j.aabb.max[1]-j.aabb.min[1])*I0|0)*I0+Math.min(63,O),U=j.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 Ot(l,u),new Ot(l,u),m),m.length>0)return{height:void 0,maxHeight:S.feature.properties.height,hidden:S.hiddenByReplacement,verticalScale:S.evaluatedScale[2]}}}}function x2(h,l){return h instanceof wg&&!h.isLightConstant&&l}function aIe(h,l,u,m,x,b,S,j){let C=(61440&l|(61440&l)>>4)>>8,O=(3840&l|(3840&l)>>4)>>4,z=240&l|(240&l)>>4;u[3]>0&&(C=Xr(C,255*u[0],u[3]),O=Xr(O,255*u[1],u[3]),z=Xr(z,255*u[2],u[3]));const U=C<<8|O,q=z<<8|Math.floor(255*m[3]),K=function(ke){const He=fe(ke,0,2);return Math.min(Math.round(.5*He*255),255)}(m[2])<<8|15*m[0]<<4|15*m[1],X=fe(x[0],0,1),J=fe(x[1],0,1),ne=fe(x[2],0,1),ae=fe(x[3],0,1);let he,ce,ye,Ee;if(X!==J&&S!==b&&J!==X){const ke=S-b;ce=1/(ke*(J-X)),ye=-(b+ke*X)/(ke*(J-X));const He=fe(x[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),j){const ke=j.length;j.clear();for(let He=0;He>16&65535,z=b?C>>16&65535:65535&C,U=(15&z)<8?15&z:0,q=h.evaluatedRMEA[U],K=h.evaluatedColor[U],X=h.emissionHeightBasedParams[U];let J;if(j&&U===2&&m.lights&&(J=new fb,J.resize(10*m.lights.length)),aIe(S.featureArray,O,K,q,X,S.aabb.min[2],S.aabb.max[2],J),J&&j){j=!1;const ne=m.meshes[m.lightMeshIndex];ne.featureArray=J,ne.featureArray._trim()}}S.featureArray._trim(),x++}}br(YN,"Tiled3dModelBucket",{omit:["layers"]}),br(QX,"Tiled3dModelFeature");const lIe=["id","tile","layer","source","sourceLayer","state"];class M0{constructor(l,u,m,x,b){this.type="Feature",this._vectorTileFeature=l,this._z=u,this._x=m,this._y=x,this.properties=l?l.properties:{},this.id=b}clone(){const l=new M0(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 lIe)this[u]!==void 0&&(l[u]=this[u]);return l}}class O0 extends Mx{constructor(l,u,m,x){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 mZ(this.map._requestManager.transformRequest(l,Lx.Model).url,u)}async loadModel(l,u,m){try{const x=await this.loadGLTFFromURI(u.uri,m);if(m.aborted)return;const b=this._modelsInfo.get(l);if(!b)return;const S=g4(x),j=b.modelSpec,C=new _Z(l,j.uri,j.position,j.orientation,S);O0.applyModelSpecification(C,j),C.computeBoundsAndApplyParent(),this.models.push(C),b.model=C}catch(x){if(x instanceof Error&&x.name==="AbortError")return;const b=x instanceof Error?x.message:"Unknown error";this.fire(new og(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 m in this._options.models){const x=this._options.models[m],b=this._modelsInfo.get(m);if(b&&b.model){b.modelSpec=x;const S=b.model;S.position=x.position!=null?new Qe(x.position[0],x.position[1]):new Qe(0,0),S.orientation=x.orientation!=null?x.orientation:[0,0,0],O0.applyModelSpecification(S,x),S.computeBoundsAndApplyParent(),this.models.push(S)}else b?b.modelSpec=x:(this._modelsInfo.set(m,{modelSpec:x,model:null}),u.push(this.loadModel(m,x,l)))}u.length!==0?(await Promise.allSettled(u),l.aborted||this.fire(new Ou("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Ou("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(l,u){u.nodeOverrides&&O0.convertNodeOverrides(l,u.nodeOverrides),u.materialOverrides&&O0.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(m=>typeof m=="string")){l.nodeOverrideNames=[];for(const m of u)l.nodeOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b={orientation:[0,0,0]};if(x.hasOwnProperty("orientation")){const S=x.orientation;S&&(b.orientation=S)}l.nodeOverrides.set(m,b)})}static convertMaterialOverrides(l,u){if(Array.isArray(u)&&u.every(m=>typeof m=="string")){l.materialOverrideNames=[];for(const m of u)l.materialOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b={color:new Zn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},S=x["model-color"];S!==void 0&&(b.color.r=S[0],b.color.g=S[1],b.color.b=S[2]);const j=x["model-color-mix-intensity"];j!==void 0&&(b.colorMix=j);const C=x["model-emissive-strength"];C!==void 0&&(b.emissionStrength=C);const O=x["model-opacity"];O!==void 0&&(b.opacity=O),l.materialOverrides.set(m,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=qm(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 m in l){const x=l[m],b=this._modelsInfo.get(m);b&&b.modelSpec.uri===x.uri&&u.set(m,b)}if(this._modelsInfo.size!==u.size){this.cancelModelRequests();for(const[m,x]of u)x.model||u.delete(m)}this._modelsInfo=u,this._options.models=l,this.load()}}function X4(h,l,u,m){const x=1<C>=Ee.vertexArrayOffset&&Cye.polygon).flat());const ne=K?j:null,[ae,he]=JY(b,m,U,z,O,S,ne,q,X,b.center.lat,h.tileID.canonical),ce=h.queryGeometry;return QY(ae,he,ce.isPointQuery()?ce.screenBounds:ce.screenGeometry)}},building:class extends Jo{constructor(h,l,u,m){super(h,{layout:AZ||(AZ=new rs({visibility:new Qt(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:jZ||(jZ=new rs({"building-opacity":new Qt(nt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new Qt(nt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new Qt(nt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new Qt(nt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new Qt(nt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new Qt(nt.paint_building["building-vertical-scale"]),"building-cast-shadows":new Qt(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 Qt(nt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new Qt(nt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new Qt(nt.paint_building["building-front-cutoff"]),"building-flood-light-color":new Qt(nt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new Qt(nt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new Qt(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,m),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new EZ(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,m,x,b,S,j,C,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,X]=JY(b,m,U,z,new Ot(0,0),S,null,[0,0],1,b.center.lat,h.tileID.canonical),J=h.queryGeometry;return QY(K,X,J.isPointQuery()?J.screenBounds:J.screenGeometry)}},line:class extends Jo{constructor(h,l,u,m){const x=OZ();super(h,x,l,u,m),x.layout&&(this.layout=new _h(x.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 Xx,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(i2)return i2;const u=OZ();return i2=new rCe(u.paint.properties["line-width"].specification),i2.useIntegerZoom=!0,i2})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,h)}createBucket(h){return new CN(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 m=DZ(this);return{config:new ee(this,{zoom:l,lut:u}),defines:m,overrideFog:!1}}queryRadius(h){const l=h,u=FZ(Ng("line-width",this,l),Ng("line-gap-width",this,l)),m=Ng("line-offset",this,l);return u/2+Math.abs(m)+JI(this.paint.get("line-translate"))}queryIntersectsFeature(h,l,u,m,x,b){if(h.queryGeometry.isAboveHorizon)return!1;const S=MK(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),j=h.pixelToTileUnitsFactor/2*FZ(this.paint.get("line-width").evaluate(l,u),this.paint.get("line-gap-width").evaluate(l,u)),C=this.paint.get("line-offset").evaluate(l,u);return C&&(m=function(O,z){const U=[],q=new Ot(0,0);for(let K=0;K=3){for(let X=0;X{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 JX{constructor(l){this._stringToNumber={},this._numberToString=[];for(let u=0;u=0&&q[3]>=0&&O.insert(C,q[0],q[1],q[2],q[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Jn(new IN(this.rawTileData)).layers,this.sourceLayerCoder=new JX(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:m,transform:x,tileTransform:b,pixelPosMatrix:S,availableImages:j,worldview:C}=u;this.loadVTLayers(),this.serializedLayersCache.clear();const O=u.queryRadius?u.queryRadius:0,z=m.bufferedTilespaceBounds,U=this.grid.query(z.min.x,z.min.y,z.max.x,z.max.y,(J,ne,ae,he)=>Ef(m.bufferedTilespaceGeometry,J-O,ne-O,ae+O,he+O));U.sort(hIe);let q=null;x.elevation&&U.length>0&&(q=Rb.create(x.elevation,this.tileID));const K={};let X;for(let J=0;J(he||(he=Ur(ce,this.tileID.canonical,b)),ye.queryIntersectsFeature(m,ce,Ee,he,this.z,x,S,q,ke,u.scope)))}return K}loadMatchingFeature(l,u,m,x,b,S){const{featureIndex:j,bucketIndex:C,sourceLayerIndex:O,layoutVertexArrayOffset:z}=u,U=this.bucketLayerIDs[C],q=m.layers,K=Object.keys(q);if(K.length&&!Fr(K,U))return;const X=m.sourceCache,J=this.sourceLayerCoder.decode(O),ne=this.vtLayers[J].feature(j),ae=this.getId(ne,J);for(let he=0;he`${j.key}: ${j.message}`).join(", ");return void Br(`Failed to create expression for promoteId: ${S}`)}this.promoteIdExpression=b.value}m=this.promoteIdExpression.evaluate({zoom:0},l)}else m=l.properties[x];typeof m=="boolean"&&(m=Number(m))}return m}}function tQ(h,l,u,m,x){return $t(h,(b,S)=>{const j=l instanceof _h?l.get(S):null;return j&&j.evaluate?j.evaluate(u,m,void 0,x):j})}function hIe(h,l){return l-h}function rQ(h,l){const u={};if(!l)return u;for(const m of h){const x=m.layerIds.map(b=>l.getLayer(b)).filter(Boolean);if(x.length!==0){m.layers=x,m.stateDependentLayerIds&&(m.stateDependentLayers=m.stateDependentLayerIds.map(b=>x.filter(S=>S.id===b)[0]));for(const b of x)u[b.fqid]=m}}return u}br(eQ,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Rd=32,Pf=33,Fg=new Uint16Array(8184);for(let h=0;h<2046;h++){let l=h+2,u=0,m=0,x=0,b=0,S=0,j=0;for(1&l?x=b=S=Rd:u=m=j=Rd;(l>>=1)>1;){const O=u+x>>1,z=m+b>>1;1&l?(x=u,b=m,u=S,m=j):(u=x,m=b,x=S,b=j),S=O,j=z}const C=4*h;Fg[C+0]=u,Fg[C+1]=m,Fg[C+2]=x,Fg[C+3]=b}const Rf=new Uint16Array(2178),Bg=new Uint8Array(1089),ZN=new Uint16Array(1089);function nQ(h){return h===0?-.03125:h===32?.03125:0}const iQ={Other:0,Symbol:1,FillExtrusion:2},sQ={type:2,extent:ar,loadGeometry:()=>[[new Ot(0,0),new Ot(8193,0),new Ot(8193,8193),new Ot(0,8193),new Ot(0,0)]]};class fIe{constructor(){this.tasks={},this.taskQueue=[],ht(["process"],this),this.invoker=new dIe(this.process),this.nextId=0}add(l,u){const m=this.nextId++,x=function({type:b,renderSourceType:S,zoom:j}){j=j||0;const C=S===iQ.Symbol;return b==="message"?0:b!=="maybePrepare"||C?b!=="parseTile"||C?b==="parseTile"&&C?300-j:b==="maybePrepare"&&C?400-j:500:200-j:100-j}(u);if(x===0){try{l()}finally{}return null}return this.tasks[m]={fn:l,metadata:u,priority:x,id:m},this.taskQueue.push(m),this.invoker.trigger(),{cancel:()=>{delete this.tasks[m]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(m=>!!this.tasks[m]),!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 x=0;x>16&255)/255,(h>>8&255)/255,(255&h)/255,1)}function EIe(h,l,u){h===1?(l.rgb_color=JN(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 AIe(h,l,u){h===1?l.transform=QN(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(lQ(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 lQ(h,l){return h.readFields(jIe,{offset:0,opacity:255,rgb_color:Q4},l)}function jIe(h,l,u){h===1?l.offset=u.readFloat():h===2?l.opacity=u.readVarint():h===3&&(l.rgb_color=JN(u.readVarint()))}function kIe(h,l,u){h===1?l.transform=QN(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(lQ(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 CIe(h,l,u){h===1?l.transform=QN(u,u.readVarint()+u.pos):h===2?l.clip_path_idx=u.readVarint():h===3&&l.children.push(XN(u,u.readVarint()+u.pos))}function IIe(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(XN(u,u.readVarint()+u.pos))}class NIe{static calculate(l={},u=[]){const m=new Map,x=new Map;if(Object.keys(l).length===0)return m;u.forEach(b=>{x.set(b.name,b.rgb_color||new Zn(0,0,0))});for(const[b,S]of Object.entries(l))x.has(b)?m.set(x.get(b).toString(),S):console.warn(`Ignoring unknown image variable "${b}"`);return m}}function Lb(h,l=255,u){const m=l/255,x=h.toString(),b=u.has(x)?u.get(x).clone():h.clone();return b.a*=m,b.toString()}function _2(h,l){if(!ou()){const u=document.createElement("canvas");return u.width=h,u.height=l,u}return new OffscreenCanvas(h,l)}let J4,v2=null;function eB(h,l,u,m,x){for(const b of m.children)cQ(h,l,u,b,x)}function cQ(h,l,u,m,x){m.group?(h.save(),function(b,S,j,C,O){const z=C.mask_idx!=null?j.masks[C.mask_idx]:null,U=C.clip_path_idx!=null?j.clip_paths[C.clip_path_idx]:null;if(C.transform&&(S=Db(C.transform).preMultiplySelf(S)),!function(X,J,ne){return X.opacity!==255||J||ne}(C,U!=null,z!=null))return void eB(b,S,j,C,O);const q=_2(b.canvas.width,b.canvas.height),K=q.getContext("2d");eB(K,S,j,C,O),U&&gQ(K,S,j,U),z&&yQ(K,S,j,z,O),b.globalAlpha=C.opacity/255,b.drawImage(q,0,0)}(h,l,u,m.group,x),h.restore()):m.path&&(h.save(),function(b,S,j,C,O){b.setTransform(S),C.paint_order===1?(uQ(b,j,C,O),hQ(b,j,C,O)):(hQ(b,j,C,O),uQ(b,j,C,O))}(h,l,u,m.path,x),h.restore())}function uQ(h,l,u,m){const x=u.fill;if(!x)return;const b=x.opacity/255;switch(h.save(),h.beginPath(),xQ(u,h),x.paint){case"rgb_color":h.fillStyle=Lb(x.rgb_color,x.opacity,m);break;case"linear_gradient_idx":{const S=l.linear_gradients[x.linear_gradient_idx];S.transform&&h.setTransform(Db(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=fQ(h,S,b,m);break}case"radial_gradient_idx":{const S=l.radial_gradients[x.radial_gradient_idx];S.transform&&h.setTransform(Db(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=mQ(h,S,b,m)}}h.fill(dQ(u)),h.restore()}function dQ(h){return h.rule===1?"nonzero":h.rule===2?"evenodd":void 0}function hQ(h,l,u,m){const x=u.stroke;if(!x)return;const b=_Q(u);h.lineWidth=x.width,h.miterLimit=x.miterlimit,h.setLineDash(x.dasharray),h.lineDashOffset=x.dashoffset;const S=x.opacity/255;switch(x.paint){case"rgb_color":h.strokeStyle=Lb(x.rgb_color,x.opacity,m);break;case"linear_gradient_idx":h.strokeStyle=fQ(h,l.linear_gradients[x.linear_gradient_idx],S,m,!0);break;case"radial_gradient_idx":h.strokeStyle=mQ(h,l.radial_gradients[x.radial_gradient_idx],S,m,!0)}switch(x.linejoin){case 2:case 1:h.lineJoin="miter";break;case 3:h.lineJoin="round";break;case 4:h.lineJoin="bevel"}switch(x.linecap){case 1:h.lineCap="butt";break;case 2:h.lineCap="round";break;case 3:h.lineCap="square"}h.stroke(b)}function fQ(h,l,u,m,x=!1){if(l.stops.length===1){const q=l.stops[0];return Lb(q.rgb_color,q.opacity*u,m)}const{x1:b,y1:S,x2:j,y2:C}=l;let O=new DOMPoint(b,S),z=new DOMPoint(j,C);if(x){const q=Db(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,Lb(q.rgb_color,q.opacity*u,m));return U}function mQ(h,l,u,m,x=!1){if(l.stops.length===1){const ae=l.stops[0];return Lb(ae.rgb_color,ae.opacity*u,m)}const b=Db(l.transform),{fx:S,fy:j,fr:C,cx:O,cy:z,r:U}=l;let q=new DOMPoint(S,j),K=new DOMPoint(O,z),X=C,J=U;if(x){q=b.transformPoint(q),K=b.transformPoint(K);const ae=(b.a+b.d)/2;X=C*ae,J=l.r*ae}const ne=h.createRadialGradient(q.x,q.y,X,K.x,K.y,J);for(const ae of l.stops)ne.addColorStop(ae.offset,Lb(ae.rgb_color,ae.opacity*u,m));return ne}function pQ(h,l,u,m){const x=m.transform?Db(m.transform).preMultiplySelf(l):l,b=_2(h.canvas.width,h.canvas.height),S=b.getContext("2d");for(const C of m.children)if(C.group)pQ(S,x,u,C.group);else if(C.path){const O=C.path,z=new Path2D;z.addPath(_Q(O),x),S.fill(z,dQ(O))}const j=m.clip_path_idx!=null?u.clip_paths[m.clip_path_idx]:null;j&&gQ(S,x,u,j),h.globalCompositeOperation="source-over",h.drawImage(b,0,0)}function gQ(h,l,u,m){const x=_2(h.canvas.width,h.canvas.height);pQ(x.getContext("2d"),l,u,m),h.globalCompositeOperation="destination-in",h.drawImage(x,0,0)}function yQ(h,l,u,m,x){if(m.children.length===0)return;const b=m.mask_idx!=null?u.masks[m.mask_idx]:null;b&&yQ(h,l,u,b,x);const S=h.canvas.width,j=h.canvas.height,C=_2(S,j),O=C.getContext("2d"),z=m.width,U=m.height,q=m.left,K=m.top,X=new Path2D,J=new Path2D;J.rect(q,K,z,U),X.addPath(J,l),O.clip(X);for(const he of m.children)cQ(O,l,u,he,x);const ne=O.getImageData(0,0,S,j),ae=ne.data;if(m.mask_type===1)for(let he=0;hel[S])return null}else{const j=1/m[S];let C=(h[S]-u[S])*j,O=(l[S]-u[S])*j;if(C>O){const z=C;C=O,O=z}if(C>x&&(x=C),Ob)return null}return x}function wQ(h,l,u,m,x,b,S,j,C,O,z){const U=m-h,q=x-l,K=b-u,X=S-h,J=j-l,ne=C-u,ae=z[1]*ne-z[2]*J,he=z[2]*X-z[0]*ne,ce=z[0]*J-z[1]*X,ye=U*ae+q*he+K*ce;if(Math.abs(ye)<1e-15)return null;const Ee=1/ye,ke=O[0]-h,He=O[1]-l,$e=O[2]-u,Ge=(ke*ae+He*he+$e*ce)*Ee;if(Ge<0||Ge>1)return null;const Ue=He*K-$e*q,Ve=$e*U-ke*K,yt=ke*q-He*U,wt=(z[0]*Ue+z[1]*Ve+z[2]*yt)*Ee;return wt<0||Ge+wt>1?null:(X*Ue+J*Ve+ne*yt)*Ee}function SQ(h,l,u){return(h-l)/(u-l)}function TQ(h,l,u,m,x,b,S,j,C){const O=1<{const he=ne?1:0,ce=(K+1)*J-he,ye=X*J,Ee=(X+1)*J-he;ae[0]=K*J,ae[1]=ye,ae[2]=ce,ae[3]=Ee};let U=new vQ(C);const q=[];for(let K=0;K=1;C/=2){const K=j[j.length-1];U=new vQ(C);for(let X=0;X0;){const{idx:X,t:J,nodex:ne,nodey:ae,depth:he}=K.pop();if(this.leaves[X]){TQ(ne,ae,he,l,u,m,x,U,q);const ye=1<=kt[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 m=[0,0,0,0],x=tP.getUnpackVector(u);let b=Math.floor((l+x[3])/x[2]);return m[2]=b%256,b=Math.floor(b/256),m[1]=b%256,b=Math.floor(b/256),m[0]=b,m}getPixels(){return new oY({width:this.stride,height:this.stride},this.pixels)}backfillBorder(l,u,m){if(this.dim!==l.dim)throw new Error("dem dimension mismatch");let x=u*this.dim,b=u*this.dim+this.dim,S=m*this.dim,j=m*this.dim+this.dim;switch(u){case-1:x=b-1;break;case 1:b=x+1}switch(m){case-1:S=j-1;break;case 1:j=S+1}const C=-u*this.dim,O=-m*this.dim;for(let z=S;z=1;m--){const x=m===1?1:0,b=m===2?1:0;for(let S=0;S>>1^-(1&h[l]);return h}function GIe(h,l){switch(l){case"uint32":return h;case"uint16":for(let u=0;u>4|(61440&m)>>8|(240&x)<<4|61440&x,h[u+1]=15&m|(3840&m)>>4|(15&x)<<8|(3840&x)<<4}return h;case"uint8":for(let u=0;u>6|(192&x)>>4|(192&b)>>2|192&S,h[u+1]=(48&m)>>4|(48&x)>>2|48&b|(48&S)<<2,h[u+2]=(12&m)>>2|12&x|(12&b)<<2|(12&S)<<4,h[u+3]=3&m|(3&x)<<2|(3&b)<<4|(3&S)<<6}return h;default:throw new Error(`Invalid pixel format, "${l}"`)}}br(tP,"DEMData"),br(EQ,"DemMinMaxQuadTree",{omit:["dem"]});var Vu=Uint8Array,b2=Uint16Array,HIe=Int32Array,jQ=new Vu([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]),kQ=new Vu([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]),WIe=new Vu([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),CQ=function(h,l){for(var u=new b2(31),m=0;m<31;++m)u[m]=l+=1<>1|(21845&Ea)<<1;PQ[Ea]=((65280&(Mb=(61680&(Mb=(52428&Mb)>>2|(13107&Mb)<<2))>>4|(3855&Mb)<<4))>>8|(255&Mb)<<8)>>1}var w2=function(h,l,u){for(var m=h.length,x=0,b=new b2(l);x>C]=O;return S},S2=new Vu(288);for(Ea=0;Ea<144;++Ea)S2[Ea]=8;for(Ea=144;Ea<256;++Ea)S2[Ea]=9;for(Ea=256;Ea<280;++Ea)S2[Ea]=7;for(Ea=280;Ea<288;++Ea)S2[Ea]=8;var RQ=new Vu(32);for(Ea=0;Ea<32;++Ea)RQ[Ea]=5;var ZIe=w2(S2,9),XIe=w2(RQ,5),rB=function(h){for(var l=h[0],u=1;ul&&(l=h[u]);return l},Ah=function(h,l,u){var m=l/8|0;return(h[m]|h[m+1]<<8)>>(7&l)&u},nB=function(h,l){var u=l/8|0;return(h[u]|h[u+1]<<8|h[u+2]<<16)>>(7&l)},QIe=function(h){return(h+7)/8|0},JIe=["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"],jh=function(h,l,u){var m=new Error(l||JIe[h]);if(m.code=h,Error.captureStackTrace&&Error.captureStackTrace(m,jh),!u)throw m;return m},eNe=new Vu(0),tNe=typeof TextDecoder<"u"&&new TextDecoder;try{tNe.decode(eNe,{stream:!0})}catch{}const rNe={gzip_data:"gzip"};class Ld extends Error{constructor(l){super(l),this.name="MRTError"}}const nNe={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},LQ={uint32:1,uint16:2,uint8:4},iNe={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let iB;class rP{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 Ld(`Layer '${l}' not found`);return u}getHeaderLength(l){const u=new Uint8Array(l),m=new DataView(l);if(u[0]!==13)throw new Ld("File is not a valid MRT.");return m.getUint32(1,!0)}parseHeader(l){const u=new Uint8Array(l),m=this.getHeaderLength(l);if(u.length= ${m} but got buffer of length ${u.length}`);const x=new iB(u.subarray(0,m)).readFields(DIe,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==x.x||this.y!==x.y||this.z!==x.z))throw new Ld(`Invalid attempt to parse header ${x.z}/${x.x}/${x.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=x.x,this.y=x.y,this.z=x.z;for(const b of x.layers)this.layers[b.name]=new DQ(b,{cacheSize:this._cacheSize});return this}createDecodingTask(l){const u=[],m=this.getLayer(l.layerName);for(let x of l.blockIndices){const b=m.dataIndex[x],S=b.firstByte-l.firstByte,j=b.lastByte-l.firstByte;if(m._blocksInProgress.has(x))continue;const C={layerName:m.name,firstByte:S,lastByte:j,pixelFormat:m.pixelFormat,blockIndex:x,blockShape:[b.bands.length].concat(m.bandShape),buffer:m.buffer,codec:b.codec.codec,filters:b.filters.map(O=>O.filter)};m._blocksInProgress.add(x),u.push(C)}return new MQ(u,()=>{u.forEach(x=>m._blocksInProgress.delete(x.blockIndex))},(x,b)=>{if(u.forEach(S=>m._blocksInProgress.delete(S.blockIndex)),x)throw x;b.forEach(S=>{this.getLayer(S.layerName).processDecodedData(S)})})}}class DQ{constructor({version:l,name:u,units:m,tileSize:x,pixelFormat:b,buffer:S,dataIndex:j},C){if(this.version=l,this.version!==1)throw new Ld(`Cannot parse raster layer encoded with MRT version ${l}`);this.name=u,this.units=m,this.tileSize=x,this.buffer=S,this.pixelFormat=nNe[b],this.dataIndex=j,this.bandShape=[x+2*S,x+2*S,LQ[this.pixelFormat]],this._decodedBlocks=new eP(C?C.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return LQ[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[m,x]of this.dataIndex.entries()){for(const[b,S]of x.bands.entries())if(S===l)return{bandIndex:u+b,blockIndex:m,blockBandIndex:b};u+=x.bands.length}break;case"number":for(const[m,x]of this.dataIndex.entries()){if(l>=u&&lthis.cacheSize)throw new Ld(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:u,lastByte:m,blockIndices:x}}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:m}=this.getBlockForBand(l);if(u<0)throw new Ld(`Band not found: ${JSON.stringify(l)}`);const x=this._decodedBlocks.get(u.toString());if(!x)throw new Ld(`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),j=m*S,C=x.subarray(j,j+S);return{data:C,bytes:new Uint8Array(C.buffer).subarray(C.byteOffset,C.byteOffset+C.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}rP.setPbf=function(h){iB=h};class MQ{constructor(l,u,m){this.tasks=l,this._onCancel=u,this._onComplete=m,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(l,u){this._finalized||(this._onComplete(l,u),this._finalized=!0)}}rP.performDecoding=function(h,l){const u=new Uint8Array(h);return Promise.all(l.tasks.map(m=>{const{layerName:x,firstByte:b,lastByte:S,pixelFormat:j,blockShape:C,blockIndex:O,filters:z,codec:U}=m,q=u.subarray(b,S+1),K=new Uint32Array(C[0]*C[1]*C[2]);let X;if(U!=="gzip_data")throw new Ld(`Unhandled codec: ${U}`);return X=function(J,ne){if(!globalThis.DecompressionStream&&ne==="gzip_data")return Promise.resolve((Ee=function($e){$e[0]==31&&$e[1]==139&&$e[2]==8||jh(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&&jh(6,"invalid gzip data"),function($e,Ge,Ue,Ve){var yt=$e.length;if(!yt||Ge.f&&!Ge.l)return Ue||new Vu(0);var wt=!Ue,jt=wt||Ge.i!=2,It=Ge.i;wt&&(Ue=new Vu(3*yt));var kt=function(ms){var el=Ue.length;if(ms>el){var Wa=new Vu(Math.max(2*el,ms));Wa.set(Ue),Ue=Wa}},Bt=Ge.f||0,mt=Ge.p||0,Ct=Ge.b||0,Lt=Ge.l,Ut=Ge.d,Kt=Ge.m,_r=Ge.n,ir=8*yt;do{if(!Lt){Bt=Ah($e,mt,1);var nr=Ah($e,mt+1,3);if(mt+=3,!nr){var Yt=$e[(ni=QIe(mt)+4)-4]|$e[ni-3]<<8,pr=ni+Yt;if(pr>yt){It&&jh(0);break}jt&&kt(Ct+Yt),Ue.set($e.subarray(ni,pr),Ct),Ge.b=Ct+=Yt,Ge.p=mt=8*pr,Ge.f=Bt;continue}if(nr==1)Lt=ZIe,Ut=XIe,Kt=9,_r=5;else if(nr==2){var jr=Ah($e,mt,31)+257,zr=Ah($e,mt+10,15)+4,Rr=jr+Ah($e,mt+5,31)+1;mt+=14;for(var ln=new Vu(Rr),$n=new Vu(19),cn=0;cn>4)<16)ln[cn++]=ni;else{var Ii=0,ls=0;for(ni==16?(ls=3+Ah($e,mt,3),mt+=2,Ii=ln[cn-1]):ni==17?(ls=3+Ah($e,mt,7),mt+=3):ni==18&&(ls=11+Ah($e,mt,127),mt+=7);ls--;)ln[cn++]=Ii}}var Oa=ln.subarray(0,jr),cs=ln.subarray(jr);Kt=rB(Oa),_r=rB(cs),Lt=w2(Oa,Kt),Ut=w2(cs,_r)}else jh(1);if(mt>ir){It&&jh(0);break}}jt&&kt(Ct+131072);for(var bs=(1<>4;if((mt+=15&Ii)>ir){It&&jh(0);break}if(Ii||jh(2),So<256)Ue[Ct++]=So;else{if(So==256){ws=mt,Lt=null;break}var Fa=So-254;So>264&&(Fa=Ah($e,mt,(1<<(Ns=jQ[cn=So-257]))-1)+NQ[cn],mt+=Ns);var En=Ut[nB($e,mt)&Ws],bl=En>>4;if(En||jh(3),mt+=15&En,cs=YIe[bl],bl>3){var Ns=kQ[bl];cs+=nB($e,mt)&(1<ir){It&&jh(0);break}jt&&kt(Ct+131072);var Ha=Ct+Fa;if(Ctms.length)&&(Wa=ms.length),new Vu(ms.subarray(0,Wa))}(Ue,0,Ct):Ue.subarray(0,Ct)}(ae.subarray(Ee,-8),{i:2},new Vu(((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 ke=rNe[ne];if(!ke)throw new Error(`Unhandled codec: ${ne}`);const He=new globalThis.DecompressionStream(ke);return new Response(new Blob([J]).stream().pipeThrough(He)).arrayBuffer().then($e=>new Uint8Array($e))}(q,U).then(J=>(function(ne,ae){ne.readFields($Ie,ae)}(new iB(J),K),new iNe[j](K.buffer))),X.then(J=>{for(let ne=z.length-1;ne>=0;ne--)switch(z[ne]){case"delta_filter":VIe(J,C);break;case"zigzag_filter":qIe(J);break;case"bitshuffle_filter":GIe(J,j);break;default:throw new Ld(`Unhandled filter "${z[ne]}"`)}return{layerName:x,blockIndex:O,data:J}}).catch(J=>{throw J})}))},br(MQ,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),br(rP,"MapboxRasterTile"),br(DQ,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const OQ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class sB{static from(l){if(!(l instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[u,m]=new Uint8Array(l,0,2);if(u!==219)throw new Error("Data does not appear to be in a KDBush format.");const x=m>>4;if(x!==1)throw new Error(`Got v${x} data when expected v1.`);const b=OQ[15&m];if(!b)throw new Error("Unrecognized array type.");const[S]=new Uint16Array(l,2,1),[j]=new Uint32Array(l,4,1);return new sB(j,S,b,l)}constructor(l,u=64,m=Float64Array,x){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=m,this.IndexArrayType=l<65536?Uint16Array:Uint32Array;const b=OQ.indexOf(this.ArrayType),S=2*l*this.ArrayType.BYTES_PER_ELEMENT,j=l*this.IndexArrayType.BYTES_PER_ELEMENT,C=(8-j%8)%8;if(b<0)throw new Error(`Unexpected typed array class: ${m}.`);x&&x instanceof ArrayBuffer?(this.data=x,this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+j+C,2*l),this._pos=2*l,this._finished=!0):(this.data=new ArrayBuffer(8+S+j+C),this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+j+C,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 m=this._pos>>1;return this.ids[m]=m,this.coords[this._pos++]=l,this.coords[this._pos++]=u,m}finish(){const l=this._pos>>1;if(l!==this.numItems)throw new Error(`Added ${l} items when expected ${this.numItems}.`);return aB(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(l,u,m,x){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:S,nodeSize:j}=this,C=[0,b.length-1,0],O=[];for(;C.length;){const z=C.pop()||0,U=C.pop()||0,q=C.pop()||0;if(U-q<=j){for(let ne=q;ne<=U;ne++){const ae=S[2*ne],he=S[2*ne+1];ae>=l&&ae<=m&&he>=u&&he<=x&&O.push(b[ne])}continue}const K=q+U>>1,X=S[2*K],J=S[2*K+1];X>=l&&X<=m&&J>=u&&J<=x&&O.push(b[K]),(z===0?l<=X:u<=J)&&(C.push(q),C.push(K-1),C.push(1-z)),(z===0?m>=X:x>=J)&&(C.push(K+1),C.push(U),C.push(1-z))}return O}within(l,u,m){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:x,coords:b,nodeSize:S}=this,j=[0,x.length-1,0],C=[],O=m*m;for(;j.length;){const z=j.pop()||0,U=j.pop()||0,q=j.pop()||0;if(U-q<=S){for(let ne=q;ne<=U;ne++)BQ(b[2*ne],b[2*ne+1],l,u)<=O&&C.push(x[ne]);continue}const K=q+U>>1,X=b[2*K],J=b[2*K+1];BQ(X,J,l,u)<=O&&C.push(x[K]),(z===0?l-m<=X:u-m<=J)&&(j.push(q),j.push(K-1),j.push(1-z)),(z===0?l+m>=X:u+m>=J)&&(j.push(K+1),j.push(U),j.push(1-z))}return C}}function aB(h,l,u,m,x,b){if(x-m<=u)return;const S=m+x>>1;FQ(h,l,S,m,x,b),aB(h,l,u,m,S-1,1-b),aB(h,l,u,S+1,x,1-b)}function FQ(h,l,u,m,x,b){for(;x>m;){if(x-m>600){const O=x-m+1,z=u-m+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);FQ(h,l,u,Math.max(m,Math.floor(u-z*q/O+K)),Math.min(x,Math.floor(u+(O-z)*q/O+K)),b)}const S=l[2*u+b];let j=m,C=x;for(T2(h,l,m,u),l[2*x+b]>S&&T2(h,l,m,x);jS;)C--}l[2*m+b]===S?T2(h,l,m,C):(C++,T2(h,l,C,x)),C<=u&&(m=C+1),u<=C&&(x=C-1)}}function T2(h,l,u,m){oB(h,u,m),oB(l,2*u,2*m),oB(l,2*u+1,2*m+1)}function oB(h,l,u){const m=h[l];h[l]=h[u],h[u]=m}function BQ(h,l,u,m){const x=h-u,b=l-m;return x*x+b*b}s.$=gg,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 fIe}send(h,l,u,m,x=!1,b){const S=Math.round(1e18*Math.random()).toString(36).substring(0,10);u&&(u.metadata=b,this.callbacks[S]=u);const j=new Set;return this.target.postMessage({id:S,type:h,hasCallback:!!u,targetMapId:m,mustQueue:x,sourceMapId:this.mapId,data:gh(l,j)},j),{cancel:()=>{u&&delete this.callbacks[S],this.target.postMessage({id:S,type:"",targetMapId:m,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 m=this.cancelCallbacks[u];delete this.cancelCallbacks[u],m&&m.cancel()}else if(l.mustQueue||Pi(self)){const m=this.callbacks[u],x=this.scheduler.add(()=>this.processTask(u,l),m&&m.metadata||{type:"message"});x&&(this.cancelCallbacks[u]=x)}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(Sf(l.error)):u(null,Sf(l.data)))}else{const u=new Set,m=l.hasCallback?(b,S)=>{this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:b?gh(b):null,data:gh(S,u)},u)}:()=>{},x=Sf(l.data);if(this.parent[l.type])this.parent[l.type](l.sourceMapId,x,m);else if(this.parent.getWorkerSource){const b=l.type.split("."),{source:S,scope:j}=x;this.parent.getWorkerSource(l.sourceMapId,{type:b[0],source:S,scope:j,uid:0})[b[1]](x,m)}else m(new Error(`Could not find function ${l.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},s.B=og,s.C=Ou,s.D=du,s.E=Mx,s.F=qm,s.G=2,s.H=o2,s.I=lc,s.J=nX,s.K=Tv,s.L=OI,s.M=$x,s.N=Ux,s.O=Hv,s.P=Ot,s.Q=Gv,s.R=Lx,s.S=KT,s.T=Nf,s.U=o0,s.V=KN,s.W=ib,s.X=wf,s.Y=ZT,s.Z=Ad,s._=Om,s.a=function(h){return Mn.API_CDN_URL_REGEX.test(h)},s.a$=IN,s.a0=Da,s.a1=Vx,s.a2=Ev,s.a3=TT,s.a4=pE,s.a5=class extends KN{},s.a6=YT,s.a7=vI,s.a8=nt,s.a9=function(h){const l=h.value;return l?Ev(l)?K4(l,!0)?[]:[new KN(h.key,l,`invalid url "${l}"`)]:[new KN(h.key,l,`string expected, "${$x(l)}" found`)]:[]},s.aA=NZ,s.aB=function(h){let l=1/0,u=1/0,m=-1/0,x=-1/0;for(const b of h)l=Math.min(l,b.x),u=Math.min(u,b.y),m=Math.max(m,b.x),x=Math.max(x,b.y);return{min:new Ot(l,u),max:new Ot(m,x)}},s.aC=fe,s.aD=M,s.aE=hr,s.aF=Le,s.aG=Bl,s.aH=Rt,s.aI=yr,s.aJ=function(h,l){const u={};for(let m=0;m=0?l.slice(u+1):""}catch{return""}},s.aN=class{constructor(h){this.entries={},this.scheduler=h}request(h,l,u,m){const x=this.entries[h]=this.entries[h]||{callbacks:[]};if(x.result){const[b,S]=x.result;return this.scheduler?this.scheduler.add(()=>{m(b,S)},l):m(b,S),()=>{}}return x.callbacks.push(m),x.cancel||(x.cancel=u((b,S)=>{x.result=[b,S];for(const j of x.callbacks)this.scheduler?this.scheduler.add(()=>{j(b,S)},l):j(b,S);setTimeout(()=>delete this.entries[h],3e3)})),()=>{x.result||(x.callbacks=x.callbacks.filter(b=>b!==m),x.callbacks.length||(x.cancel(),delete this.entries[h]))}}},s.aO=function(h,l,u){const m=JSON.stringify(h.request);return h.data&&(this.deduped.entries[m]={result:[null,h.data]}),this.deduped.request(m,{type:"parseTile",renderSourceType:h.renderSourceType,zoom:h.tileZoom},x=>{const b=sg(h.request,(S,j,C)=>{S?bT(S)?x(null,null):x(S):j&&x(null,{rawData:j,vectorTile:u?void 0:new Jn(new IN(j)),responseHeaders:new Map(C.entries())})});return()=>{b.cancel(),x(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){yT++,yT>pv&&(h.getActor().send("enforceCacheSizeLimit",mv),yT=0)},s.aR=vl,s.aS=FX,s.aT=HX,s.aU=Qe,s.aV=OX,s.aW=function(h,l){const u=document.createElement("video");u.muted=!0,u.onloadstart=function(){l(null,u)};for(let m=0;m{}}},s.aX=r2,s.aY=O0,s.aZ=ht,s.a_=rP,s.aa=nb,s.ab=rs,s.ac=Qt,s.ad=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return Ln(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=ri,s.af=Bm,s.ag=Ar,s.ah=or,s.ai=Me,s.aj=Oe,s.ak=_h,s.al=Xm,s.am=Xr,s.an=ar,s.ao=Fu,s.ap=Yn,s.aq=Zn,s.ar=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return function([u,m]){const x=Ln([1,u,m]);return{x:x.x,y:x.y,z:x.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,m=!0){const x=new Ot(u,u),b=h.sub(x),S=l.add(x),j=[b,new Ot(S.x,b.y),S,new Ot(b.x,S.y)];return m&&j.push(b.clone()),j},s.at=function(h,l){const u=[];for(let m=0;mthis.buckets[U].layers.some(q=>S.has(q.fqid))),C=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!==m;this._lastAvailableImagesCount=b,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||m||this._hasAppearances||j||C||O)&&(!(this._hasAppearances||j||C||O)&&this._lastUpdatedBrightness&&m&&Math.abs(this._lastUpdatedBrightness-m)<.001||(this.updateBuckets(l,z,void 0,O||j||C,S,x),this._lastUpdatedBrightness=m))}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,m,x,b,S){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const j=this.evaluateQueryRenderedFeaturePadding(),C=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)}(x,this.tileID);return this.latestFeatureIndex.query(h,{tilespaceGeometry:l,pixelPosMatrix:C,transform:m,availableImages:u,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:j,scope:S})}querySourceFeatures(h,l){const u=this.latestFeatureIndex;if(!u||!u.rawTileData)return;const m=u.loadVTLayers(),x=l?l.sourceLayer:"",b=m._geojsonTileLayer||m[x];if(!b)return;const S=sb(l&&l.filter),{z:j,x:C,y:O}=this.tileID.canonical,z={z:j,x:C,y:O};for(let U=0;Uu)m=!1;else if(l)if(this.expirationTimeu.appearances&&u.appearances.length>0))return!0;return!1}updateBuckets(h,l,u,m,x,b){if(!this.latestFeatureIndex||!h.style)return;const S=b||h.style.listImages(),j=h.style.getBrightness(),C=x||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),X=z.layers.some(Ee=>C.has(Ee.fqid)),J=(m||X)&&z instanceof Eh?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||X||m){const Ee=this.latestFeatureIndex.loadVTLayers()[q];if(z.update(ne,Ee,S,ae,ce,l,j,this.tileID.canonical),(m||X)&&!l&&z instanceof Eh&&J&&J.type==="symbol"){const ke=z;ke.text&&ke.text.uboBinder&&ke.text.uboBinder.updateDynamicExpressions(J,Ee,this.tileID.canonical,S,ne,j),ke.icon&&ke.icon.uboBinder&&ke.icon.uboBinder.updateDynamicExpressions(J,Ee,this.tileID.canonical,S,ne,j)}if(z instanceof Eh){const ke=z,He=h.context;ke.text&&ke.text.uboBinder&&ke.text.uboBinder.upload(He),ke.icon&&ke.icon.uboBinder&&ke.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},ke=z.updateAppearances(this.tileID.canonical,ne,S,Ee,h.imageManager,he&&z.stateDependentLayers.length!==0);if(ke&&ke.hasUboChanges){const He=h.context;z instanceof Eh&&z.text&&z.text.uboBinder&&z.text.uboBinder.upload(He),z instanceof Eh&&z.icon&&z.icon.uboBinder&&z.icon.uboBinder.upload(He)}}(z instanceof CN||z instanceof uN)&&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=Fg[ne+0],he=Fg[ne+1],ce=Fg[ne+2],ye=Fg[ne+3],Ee=ae+ce>>1,ke=he+ye>>1,He=Ee+ke-he,$e=ke+ae-Ee,Ge=he*Pf+ae,Ue=ye*Pf+ce,Ve=ke*Pf+Ee,yt=Math.hypot((Rf[2*Ge+0]+Rf[2*Ue+0])/2-Rf[2*Ve+0],(Rf[2*Ge+1]+Rf[2*Ue+1])/2-Rf[2*Ve+1])>=16;Bg[Ve]=Bg[Ve]||(yt?1:0),J<1022&&(Bg[Ve]=Bg[Ve]||Bg[(he+$e>>1)*Pf+(ae+He>>1)]||Bg[(ye+$e>>1)*Pf+(ce+He>>1)])}const z=new bo,U=new vs;let q=0;function K(J,ne){const ae=ne*Pf+J;return ZN[ae]===0&&(z.emplaceBack(Rf[2*ae+0],Rf[2*ae+1],J*ar/Rd,ne*ar/Rd),ZN[ae]=++q),ZN[ae]-1}function X(J,ne,ae,he,ce,ye){const Ee=J+ae>>1,ke=ne+he>>1;if(Math.abs(J-ce)+Math.abs(ne-ye)>1&&Bg[ke*Pf+Ee])X(ce,ye,J,ne,Ee,ke),X(ae,he,ce,ye,Ee,ke);else{const He=K(J,ne),$e=K(ae,he),Ge=K(ce,ye);U.emplaceBack(He,$e,Ge)}}return X(0,0,Rd,Rd,Rd,0),X(Rd,Rd,0,0,0,Rd),{vertices:z,indices:U}}(this.tileID.canonical,l);m=b.vertices,x=b.indices}else{m=new bo,x=new vs;for(const{x:S,y:j}of u)m.emplaceBack(S,j,0,0);const b=vb(m.int16.subarray(0,4*m.length),void 0,4);for(let S=0;S0&&(S=D(new Float64Array(16),l.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(h,m,l,x,S,b),this._makeGlobeTileDebugTextBuffer(h,m,l,x,S,b)}_globePoint(h,l,u,m,x,b,S){let j=BE(h,l,u);if(b){const C=1<.5?q=-1:U<-.5&&(q=1);let K=(h/ar+u.x)/C+q,X=(l/ar+u.y)/C;K=(K-O)*m._pixelsPerMercatorPixel+O,X=(X-z)*m._pixelsPerMercatorPixel+z;const J=[K*m.worldSize,X*m.worldSize,0];or(J,J,b),j=Zm(j,J,S)}return or(j,j,x)}_makeGlobeTileDebugBorderBuffer(h,l,u,m,x,b){const S=new uc,j=new Wm,C=new Id,O=(U,q,K,X,J)=>{const ne=(K-U)/(J-1),ae=(X-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,m=1<1)return l;const x=m.getSource().maxzoom,b=1<{const j=this.getAtTileOffset(h,x,b,S),C=m.upVector(h.canonical,x.x,x.y);return We(C,C,j*m.upVectorScale(h.canonical,l,u).metersToTile),C}}getForTilePoints(h,l,u,m){if(this.isUsingMockSource())return!1;const x=Rb.create(this,h,m);return!!x&&(l.forEach(b=>{b[2]=this.exaggeration()*x.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,m=l.tileID,x=1<0&&(m+=(h[x]-0)*(h[x]-0)),l[x]<0&&(m+=(0-l[x])*(0-l[x]));return m},s.cL=function(h){return h*h*h*h*h},s.cM=ft,s.cN=45,s.cO=yb,s.cP=function(h,l,u){const m=Math.sqrt(h*h+l*l+u*u),x=m>0?Math.acos(u/m)*js:0;let b=h!==0||l!==0?Math.atan2(-l,-h)*js+90:0;return b<0&&(b+=360),[m,b,x]},s.cQ=Ae,s.cR=Ln,s.cS=Dt,s.cT=me,s.cU=oi,s.cV=Pe,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=mZ,s.cY=g4,s.cZ=_Z,s.c_=K4,s.ca=2,s.cb=7,s.cc=6,s.cd=vt,s.ce=we,s.cf=Ce,s.cg=0,s.ch=1,s.ci=4,s.cj=5,s.ck=_b,s.cl=dc,s.cm=gZ,s.cn=j0,s.co=GK,s.cp=function(h,l,u,m,x,b,S,j,C){if(C.name==="globe")return GK(h,l,new j0(u,m,x),!1);const O=L0({z:u,x:m,y:x},C);return new oi([(b+O.x/O.scale)*l,l*(O.y/O.scale),S],[(b+O.x2/O.scale)*l,l*(O.y2/O.scale),j])},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 au[l]},s.ct=St,s.cu=Mt,s.cv=6,s.cw=function(h){const l=R(new Float64Array(16));M(l,h.pixelMatrix,h.globeMatrix);const u=[0,ze,0],m=[0,Ke,0];return or(u,u,l),or(m,m,l),[u[0]>0&&u[0]<=h.width&&u[1]>0&&u[1]<=h.height&&!O5(h,new Qe(h.center.lat,90)),m[0]>0&&m[0]<=h.width&&m[1]>0&&m[1]<=h.height&&!O5(h,new Qe(h.center.lat,-90))]},s.cx=function(h,l){const{scale:u}=h.tileTransform,m=u*ar/(h.tileSize*Math.pow(2,l.zoom-h.tileID.overscaledZ+h.tileID.canonical.z));return function(x,b,S){var j=b[1],C=b[2],O=b[3],z=S[0],U=S[1];return x[0]=b[0]*z,x[1]=j*z,x[2]=C*U,x[3]=O*U,x}(new Float32Array(4),l.inverseAdjustmentMatrix,[m,m])},s.cy=SN,s.cz=_e,s.d=function(h){return Mn.API_TILEJSON_REGEX.test(h)},s.d$=fje,s.d0=hs,s.d1=class{static calculate(h,l,u){const m=new Set,x=new Map,b=new Set,S=new Set;for(const C of Object.values(h))for(const[O,z]of Object.entries(C.floors)){b.add(O),z.isDefault&&S.add(O),z.conflicts&&x.set(O,z.conflicts);const U=O===l,q=z.connections&&l&&z.connections.has(l);(U||q)&&m.add(O)}const j=C=>{const O=x.get(C)||new Set;for(const z of m)if((x.get(z)||new Set).has(C)||O.has(z))return!0;return!1};if(u)for(const C of u)b.has(C)&&(j(C)||m.add(C));for(const C of S)m.has(C)||j(C)||m.add(C);return m}},s.d2=LN,s.d3=D4,s.d4=Qn,s.d5=function(){return{API_URL:Mn.API_URL,DRACO_URL:Mn.DRACO_URL,MESHOPT_URL:Mn.MESHOPT_URL,MESHOPT_SIMD_URL:Mn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Mn.BUILDING_GEN_URL}},s.d6=LI,s.d7=pT,s.d8=mf,s.d9=mr,s.dA=tN,s.dB=uc,s.dC=vs,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),m=Math.cos(l);return h[0]=m,h[1]=u,h[2]=0,h[3]=-u,h[4]=m,h[5]=0,h[6]=0,h[7]=0,h[8]=1,h},s.dG=Sr,s.dH=WK,s.dI=Ri,s.dJ=as,s.dK=H4,s.dL=function(h,l){const u=[0,0,0];return or(u,u,zE(kf(l.canonical))),or(u,u,h),u},s.dM=h=>({u_matrix:new d(h),u_texsize:new gu(h),u_pixels_to_tile_units:new A(h),u_device_pixel_ratio:new da(h),u_width_scale:new da(h),u_floor_width_scale:new da(h),u_image:new E0(h),u_units_to_pixels:new gu(h),u_tile_units_to_pixels:new da(h),u_alpha_discard_threshold:new da(h),u_trim_offset:new gu(h),u_trim_fade_range:new gu(h),u_trim_gradient_mix_range:new gu(h),u_trim_color:new yb(h),u_zbias_factor:new da(h),u_tile_to_meter:new da(h),u_ground_shadow_factor:new A0(h),u_pattern_transition:new da(h)}),s.dN=h=>({u_matrix:new d(h),u_pixels_to_tile_units:new A(h),u_device_pixel_ratio:new da(h),u_width_scale:new da(h),u_floor_width_scale:new da(h),u_units_to_pixels:new gu(h),u_dash_image:new E0(h),u_gradient_image:new E0(h),u_image_height:new da(h),u_texsize:new gu(h),u_tile_units_to_pixels:new da(h),u_alpha_discard_threshold:new da(h),u_trim_offset:new gu(h),u_trim_fade_range:new gu(h),u_trim_gradient_mix_range:new gu(h),u_trim_color:new yb(h),u_zbias_factor:new da(h),u_tile_to_meter:new da(h),u_ground_shadow_factor:new A0(h)}),s.dO=h=>({u_camera_to_center_distance:new da(h),u_extrude_scale:new A(h),u_device_pixel_ratio:new da(h),u_matrix:new d(h),u_inv_rot_matrix:new d(h),u_merc_center:new gu(h),u_tile_id:new A0(h),u_zoom_transition:new da(h),u_up_dir:new A0(h),u_emissive_strength:new da(h)}),s.dP=jE,s.dQ=hCe,s.dR=class{constructor(h,l,u,m){this.context=h,this.format=m,this.size=u,this.texture=h.gl.createTexture();const[x,b,S]=this.size,{gl:j}=h;j.bindTexture(j.TEXTURE_3D,this.texture),h.pixelStoreUnpackFlipY.set(!1),h.pixelStoreUnpack.set(1),h.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in l&&l.data&&j.texImage3D(j.TEXTURE_3D,0,this.format,x,b,S,0,c4(this.format),u4(this.format),l.data)}bind(h,l){const{context:u}=this,{gl:m}=u;m.bindTexture(m.TEXTURE_3D,this.texture),h!==this.minFilter&&(m.texParameteri(m.TEXTURE_3D,m.TEXTURE_MAG_FILTER,h),m.texParameteri(m.TEXTURE_3D,m.TEXTURE_MIN_FILTER,h),this.minFilter=h),l!==this.wrapS&&(m.texParameteri(m.TEXTURE_3D,m.TEXTURE_WRAP_S,l),m.texParameteri(m.TEXTURE_3D,m.TEXTURE_WRAP_T,l),this.wrapS=l)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}},s.dS=XK,s.dT=(h,l,u,m,x,b)=>{const S=h.transform,j=S.projection.name==="globe";let C;if(b.paint.get("circle-pitch-alignment")==="map")if(j){const z=WK(S.zoom,l.canonical)*S._pixelsPerMercatorPixel;C=Float32Array.from([z,0,0,z])}else C=S.calculatePixelsToTileUnitsMatrix(u);else C=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:Ol.devicePixelRatio,u_extrude_scale:C,u_inv_rot_matrix:_je,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(j){O.u_inv_rot_matrix=m,O.u_merc_center=x,O.u_tile_id=[l.canonical.x,l.canonical.y,1<{const z=h.transform,U=z.pitch<15?PZ(.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:LZ(h,l,u,m),u_texsize:l.imageAtlasTexture?l.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:z.calculatePixelsToTileUnitsMatrix(l),u_device_pixel_ratio:x,u_width_scale:b,u_floor_width_scale:S,u_image:0,u_tile_units_to_pixels:RZ(l,z),u_units_to_pixels:[1/z.pixelsToGLUnits[0],1/z.pixelsToGLUnits[1]],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:U,u_tile_to_meter:Dt(l.tileID.canonical,0),u_ground_shadow_factor:C,u_pattern_transition:O}},s.dX=(h,l,u,m,x,b,S,j,C,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?PZ(.07,.7,fe((14-z.zoom)/5,0,1)):.07;return{u_matrix:LZ(h,l,u,m),u_pixels_to_tile_units:U,u_device_pixel_ratio:b,u_width_scale:S,u_floor_width_scale:j,u_units_to_pixels:[1/z.pixelsToGLUnits[0],1/z.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:x,u_texsize:MZ(u)&&l.lineAtlasTexture?l.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:RZ(l,h.transform),u_alpha_discard_threshold:0,u_trim_offset:C,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=$E,s.d_=bt,s.da=function(h){const l=h.indexOf(m0);return l>=0?h.slice(0,l):h},s.db=function(h){return h.indexOf(m0)>=0},s.dc=function(h){const l=h.lastIndexOf(m0);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,m){return h.type==="custom"?new sIe(h,l):new uIe[h.type](h,l,u,m)},s.df=Pt,s.dg=sb,s.dh=UI,s.di=class extends M0{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=dE,s.dk=function(h){return h({pluginStatus:Qo,pluginURL:jc}),dE.on("pluginStateChange",h),h},s.dl=P5,s.dm=class extends pu{constructor(h){super(h),this.current=g}set(h,l,u){if(this.fetchUniformLocation(h,l)){for(let m=0;m<9;m++)if(u[m]!==this.current[m]){this.current=u,this.gl.uniformMatrix3fv(this.location,!1,u);break}}}},s.dn=Px,s.dp=function(h,l,u){const m=Xm(u.zoom),x=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return m===0&&!x&&!b},s.dq=function(h){const l=h.pixelsPerMeter,u=l/ot(1,h.center.lat),m=R(new Float64Array(16));return B(m,m,[h.point.x,h.point.y,0]),V(m,m,[u,u,l]),Float32Array.from(m)},s.dr=rN,s.ds=function(h){const l=80.051129;h=fe(h,-80.051129,l)/l*90;const u=Math.pow(Math.abs(Math.sin(Yn(h))),3);return Math.round(u*(Ze.length-1))},s.dt=function(h,l,u,m){const x=l.getNorth(),b=l.getSouth(),S=l.getWest(),j=l.getEast(),C=1<0){const X=180/m;E(K,K,[X/O+1,0,0,0,X/z+1,0,-.5*X/U,.5*X/q,1])}return K[2]=C,K[5]=h.x,K[8]=h.y,K},s.du=zE,s.dv=kf,s.dw=function(h,l,u){const m=R(new Float64Array(16)),x=(l/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,l=!1){const u=NY(new Ot(0,0),new Ot(ar,ar),h),m=[];if(l&&!Q5(u,this._globalClipBounds))return m;for(const x of this._activeRegions){if(x.hiddenByOverlap||!Q5(u,x))continue;const b=tke(x.min,x.max,h);m.push({min:b.min,max:b.max,sourceId:this._sourceIds[x.priority],footprint:x.footprint,footprintTileId:x.tileId,order:x.order,clipMask:x.clipMask,clipScope:x.clipScope})}return m}setSources(h){this._setSources(h.map(l=>({getSourceId:()=>l.cache.id,getFootprints:()=>{const u=[];for(const m of l.cache.getVisibleCoordinates()){const x=l.cache.getTile(m).buckets[l.layer];x&&x.updateFootprints(m.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(),m=h.getClipMask(),x=h.getClipScope();for(const b of l){if(!b.footprint)continue;const S=NY(b.footprint.min,b.footprint.max,b.id);this._activeRegions.push({min:S.min,max:S.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:b.id,footprint:b.footprint,order:u,clipMask:m,clipScope:x})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((l,u)=>l.priority-u.priority||hN(l.min,u.min)||hN(l.max,u.max)||l.order-u.order||l.clipMask-u.clipMask||function(m,x){const b=(S,j)=>S+j;return m.length-x.length||m.reduce(b,"").localeCompare(x.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],m=this._prevRegions[l];h=u.priority!==m.priority||!IY(u,m)||u.order!==m.order||u.clipMask!==m.clipMask||!Ro(u.clipScope,m.clipScope),this._activeRegions[l].hiddenByOverlap=m.hiddenByOverlap,++l}}if(h){++this._updateTime;for(const u of this._activeRegions)u.order!==YE&&(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 m=this._activeRegions;if(u>=m.length)return u;const x=m[u].priority;for(;u1){let u=0,m=l(u);for(;u!==m;){let x=u;const b=u;for(;x!==m;){const S=this._activeRegions[x];S.hiddenByOverlap=!1;for(let j=0;j=0;l--)this._addSource(h[l]);this._computeReplacement()}},s.eH=bo,s.eI=GN,s.eJ=Wm,s.eK=YE,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 uc,m=new vs,x=[],b=h+1+2,S=l[0]+1,j=l[0]+1+(1+l.length),C=(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=VK,s.ed=D5,s.ee=fu,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=Gm,s.ei=v0,s.ej=function(h,l,u,m,x){return fe((h-l)/(u-l)*(x-m)+m,m,x)},s.ek=ci,s.el=function(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=l[4],j=l[5],C=l[6],O=l[7],z=l[8],U=z*S-j*O,q=-z*b+j*C,K=O*b-S*C,X=u*U+m*q+x*K;return X?(h[0]=U*(X=1/X),h[1]=(-z*m+x*O)*X,h[2]=(j*m-x*S)*X,h[3]=q*X,h[4]=(z*u-x*C)*X,h[5]=(-j*u+x*b)*X,h[6]=K*X,h[7]=(-O*u+m*C)*X,h[8]=(S*u-m*b)*X,h):null},s.em=gI,s.en=2,s.eo=Vt,s.ep=Xt,s.eq=se,s.er=function(h,l){var u=new p(3);se(u,l);var m=1/u[0],x=1/u[1],b=1/u[2],S=l[0]*m,j=l[1]*x,C=l[2]*b,O=l[4]*m,z=l[5]*x,U=l[6]*b,q=l[8]*m,K=l[9]*x,X=l[10]*b,J=S+z+X,ne=0;return J>0?(ne=2*Math.sqrt(J+1),h[3]=.25*ne,h[0]=(U-K)/ne,h[1]=(q-C)/ne,h[2]=(j-O)/ne):S>z&&S>X?(ne=2*Math.sqrt(1+S-z-X),h[3]=(U-K)/ne,h[0]=.25*ne,h[1]=(j+O)/ne,h[2]=(q+C)/ne):z>X?(ne=2*Math.sqrt(1+z-S-X),h[3]=(q-C)/ne,h[0]=(j+O)/ne,h[1]=.25*ne,h[2]=(U+K)/ne):(ne=2*Math.sqrt(1+X-S-z),h[3]=(j-O)/ne,h[0]=(q+C)/ne,h[1]=(U+K)/ne,h[2]=.25*ne),h},s.es=function(h,l){var u=2*Math.acos(l[3]),m=Math.sin(u/2);return m>f?(h[0]=l[0]/m,h[1]=l[1]/m,h[2]=l[2]/m):(h[0]=1,h[1]=0,h[2]=0),u},s.et=X4,s.eu=AN,s.ev=EN,s.ew=[1,1,1],s.ex=Rb,s.ey=function(h,l,u,m){var x=l[0],b=l[1],S=l[2],j=l[3];return h[0]=x+m*(u[0]-x),h[1]=b+m*(u[1]-b),h[2]=S+m*(u[2]-S),h[3]=j+m*(u[3]-j),h},s.ez=Eb,s.f=sc,s.f0=YK,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 Ot(l[0],l[1])},s.f2=hE,s.f3=function(h,l,u=!1){if(Qo===cc.deferred||Qo===cc.loading||Qo===cc.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");jc=Ol.resolveURL(h),Qo=cc.deferred,Cd=l,uE(),u||DI()},s.f4=co,s.f5=vo,s.f6=Ta,s.f7=function(h){const l=VC();if(!l)return;const u=l.delete(jm);h&&u.then(()=>h()).catch(h)},s.f8=br,s.f9=Pg,s.fA=tn,s.fB=function(h){let l=0;if(new Uint32Array(h,0,1)[0]!==cZ){const u=new Uint32Array(h,0,7),[,,m,x,b,S]=u;l=u.byteLength+x+b+S+b,(m!==h.byteLength||l>=h.byteLength)&&Br("Invalid b3dm header information.")}return fZ(h,l)},s.fC=function(h,l){const u=g4(h);for(const m of u){for(const x of m.meshes)Pke(x);m.lights&&(m.lightMeshIndex=m.meshes.length,m.meshes.push(Rke(m.lights,l)))}return u},s.fD=YN,s.fE=Pi,s.fF=xh,s.fG=cc,s.fH=function(h){gv(),Ed!=null&&Ed.then(l=>{l.keys().then(u=>{for(let m=0;mBr(x.message))}).catch(u=>Br(u.message))}).catch(l=>Br(l.message))},s.fa=2,s.fb=ph,s.fc=L0,s.fd=RE,s.fe=JX,s.ff=eQ,s.fg=kZ,s.fh=yn,s.fi="hd_road_elevation",s.fj=Li,s.fk=$t,s.fl=uN,s.fm=Qm,s.fn=R4,s.fo=1,s.fp=Eh,s.fq=function(h,l,u,m,x,b,S,j=1,C,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,X={};X.scaleFactor=j,X.textSizeScaleRange=q.get("text-size-scale-range"),X.iconSizeScaleRange=q.get("icon-size-scale-range");const[J,ne]=X.textSizeScaleRange,[ae,he]=X.iconSizeScaleRange;X.textScaleFactor=fe(X.scaleFactor,J,ne),X.iconScaleFactor=fe(X.scaleFactor,ae,he);const ce=K["text-size"],ye=K["icon-size"];if(h.textSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.textSizeData;X.compositeTextSizes=[ce.possiblyEvaluate(new ri(Ue,{worldview:z}),b),ce.possiblyEvaluate(new ri(Ve,{worldview:z}),b)]}if(h.iconSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.iconSizeData;X.compositeIconSizes=[ye.possiblyEvaluate(new ri(Ue,{worldview:z}),b,U),ye.possiblyEvaluate(new ri(Ve,{worldview:z}),b,U)]}X.layoutTextSize=ce.possiblyEvaluate(new ri(S+1,{worldview:z}),b),X.layoutIconSize=ye.possiblyEvaluate(new ri(S+1,{worldview:z}),b,U),X.textMaxSize=ce.possiblyEvaluate(new ri(18,{worldview:z}),b);const Ee=q.get("symbol-placement"),ke=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)*X.textScaleFactor,wt=X.layoutTextSize.evaluate(Ue,{},b)*X.textScaleFactor,jt=X.layoutIconSize.evaluate(Ue,{},b,U)*X.iconScaleFactor,It={horizontal:{},vertical:void 0},kt=Ue.text;let Bt,mt=[0,0];if(kt){const Sn=kt.toString(),fs=q.get("text-letter-spacing").evaluate(Ue,{},b)*Ma,ni=q.get("text-line-height").evaluate(Ue,{},b)*Ma,Hn=x5(Sn)?fs:0,Ii=q.get("text-anchor").evaluate(Ue,{},b),ls=q.get("text-variable-anchor");if(!ls){const ws=q.get("text-radial-offset").evaluate(Ue,{},b);if(ws)mt=fX(Ii,[ws*Ma,O4]);else{const So=q.get("text-offset").evaluate(Ue,{},b);mt=[So[0]*Ma,So[1]*Ma]}}let Oa=ke?"center":q.get("text-justify").evaluate(Ue,{},b);const cs=Ee==="point",bs=cs?q.get("text-max-width").evaluate(Ue,{},b)*Ma:1/0,Ws=ws=>{h.allowVerticalPlacement&&oE(Sn)&&(It.vertical=A4(kt,l,u,x,Ve,bs,ni,Ii,ws,Hn,mt,Lc.vertical,!0,wt,yt,C,X.textScaleFactor))};if(!ke&&ls){const ws=Oa==="auto"?ls.map(Fa=>F4(Fa)):[Oa];let So=!1;for(let Fa=0;Fa=0||!oE(Sn)){const ws=A4(kt,l,u,x,Ve,bs,ni,Ii,Oa,Hn,mt,Lc.horizontal,!1,wt,yt,C,X.textScaleFactor);ws&&(It.horizontal[Oa]=ws)}Ws(cs?"left":Oa)}}let Ct,Lt,Ut,Kt,_r,ir,nr=!1;const Yt=q.get("icon-text-fit").evaluate(Ue,{},b);if(Ue.icon&&Ue.icon.hasPrimary()){const Sn=u2(Ue.icon,h.iconSizeData,K["icon-size"],b,h.zoom,Ue,C,X.iconScaleFactor,z,U);Ct=Sn.iconPrimary,Ut=Sn.iconSecondary;const fs=Ct.toString();if(Lt=m.get(fs),Lt&&(_r=q.get("icon-offset").evaluate(Ue,{},b),ir=q.get("icon-anchor").evaluate(Ue,{},b),Bt=PN(x.get(fs),Ut?x.get(Ut.toString()):void 0,_r,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)),Ut){const ni=Ut.toString();Kt=m.get(ni)}}$e=$e||!(!Ue.icon||!Ue.icon.hasSecondary());const pr=BN(It.horizontal)||It.vertical;h.iconsInText||(h.iconsInText=!!pr&&pr.iconsInText);const jr=wt*X.textScaleFactor/Ma,{defaultShapedIcon:zr,verticallyShapedIcon:Rr}=VCe(h,Bt,q,Ue,b,It,jr,_r,Yt);Yt!=="none"&&Bt&&(YZ(Bt)||ZZ(Bt))&&(FN(0,Lt,Ct,Bt,zr,Yt,O,m,x),FN(0,Kt,Ut,Bt,zr,Yt,O,m,x),Rr&&(FN(0,Lt,Ct,Bt,Rr,Yt,O,m,x),FN(0,Kt,Ut,Bt,Rr,Yt,O,m,x))),Bt=zr;const{iconBBox:ln,iconVerticalBBox:$n,textBBox:cn,textVerticalBBox:Vn}=FCe(h,Bt,Rr,q,Ue,b,jt,_r,X,x,ir,It,wt,mt,U);Ge.push({feature:Ue,shapedTextOrientations:It,shapedText:pr,shapedIcon:Bt,iconPrimary:Ct,iconSecondary:Ut,iconOffset:_r,iconAnchor:ir,verticallyShapedIcon:Rr,layoutTextSize:wt,layoutIconSize:jt,textOffset:mt,isSDFIcon:nr,iconTextFit:Yt,iconCollisionBounds:ln,iconVerticalCollisionBounds:$n,textCollisionBounds:cn,textVerticalCollisionBounds:Vn})}return{featureData:Ge,sizes:X,hasAnySecondaryIcon:$e,textAlongLine:ke,symbolPlacement:Ee}},s.fr=L4,s.fs=P4,s.ft=sX,s.fu=aX,s.fv=function(h,l,u,m,x,b,S,j,C,O){h.iconAtlasPositions=O.iconPositions;const{featureData:z,hasAnySecondaryIcon:U,sizes:q,textAlongLine:K,symbolPlacement:X}=l;for(const J of z){const{shapedIcon:ne,verticallyShapedIcon:ae,feature:he,shapedTextOrientations:ce,shapedText:ye,layoutTextSize:Ee,textOffset:ke,isSDFIcon:He,iconPrimary:$e,iconSecondary:Ge,iconTextFit:Ue,iconOffset:Ve,iconCollisionBounds:yt,iconVerticalCollisionBounds:wt,textCollisionBounds:jt}=J;yX(ne,O.iconPositions,$e,Ge),yX(ae,O.iconPositions,$e,Ge),UCe(ce,O.iconPositions),$Ce($e,Ge,O.iconPositions),(ye||ne)&&qCe(h,he,ce,ne,ae,C,q,Ee,0,ke,He,m,x,S,j,U,Ue,Ve,K,X,yt,wt,jt)}u&&h.generateCollisionDebugBuffers(b,h.collisionBoxArray,q.textScaleFactor)},s.fw=CN,s.fx=Jn,s.fy=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},s.fz=tP,s.g=Mn,s.h=function(h,l){return ig(Object.assign(h,{method:"GET"}),l)},s.i=function(h){return Mn.API_STYLE_REGEX.test(h)&&!ac(h)},s.j=function(h){return btoa(encodeURIComponent(h).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(+("0x"+u))))},s.k=yv,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 ig(Object.assign(h,{type:"json"}),l)},s.n=ag,s.o=Ol,s.p=function(h,l){return ig(Object.assign(h,{method:"POST"}),l)},s.q=Oo,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[m]of this.textures.entries()){const x=this.textureAccessTimes.get(m)||0;xthis._layers[mr.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 $t=dt.sourceLayer||"_geojsonTileLayer";let Pt=ht[$t];Pt||(Pt=ht[$t]=[]),Pt.push(tt)}}}const k=1*f.fa;class P{constructor(de){const fe={},Oe=[];for(const dt in de){const it=de[dt],ht=fe[dt]={};for(const $t in it.glyphs){const Pt=it.glyphs[+$t];if(!Pt||Pt.bitmap.width===0||Pt.bitmap.height===0)continue;const mr=Pt.metrics.localGlyph?k:1,Fr={x:0,y:0,w:Pt.bitmap.width+2*mr,h:Pt.bitmap.height+2*mr};Oe.push(Fr),ht[$t]=Fr}}const{w:Ye,h:Je}=f.J(Oe),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 $t=it.glyphs[+ht];if(!$t||$t.bitmap.width===0||$t.bitmap.height===0)continue;const Pt=fe[dt][ht],mr=$t.metrics.localGlyph?k:1;f.f9.copy($t.bitmap,tt,{x:0,y:0},{x:Pt.x+mr,y:Pt.y+mr},$t.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,Oe){for(const Ye of de)R(ct,Ye),ct[Ye].floors[fe]=Oe,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(),Oe=!!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($t,Pt){const mr=$t.loadGeometry();if(!mr||mr.length===0)return;const Fr=mr.map(qr=>qr.map(Br=>f.fb(Br,Pt,$t.extent)));return Fr.length===0?void 0:{type:"Polygon",coordinates:[Fr[0]]}}(ct,de);return{id:fe,isDefault:Oe,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(P,"GlyphAtlas");class Z{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,Oe,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={},$t=new f.fg(256,256),Pt={featureIndex:it,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:$t,availableImages:Oe,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Pt.activeFloors=function(Br,an,kn,Ln){const Pi=an.indoorState.activeFloorsVisible;if(!an.sourceLayers)return Pi?an.indoorState.activeFloors:void 0;const Ms=function(vi,ss){if(!vi)return f.w("No source layers defined in indoor specification"),ss;if(vi.size===0)return ss;const ca=vi.difference(ss);for(const Ri of ca)f.w(`Missing source layer required in indoor specification: ${Ri}`);return ss.intersection(ss)}(an.sourceLayers,new Set(Object.keys(Br.layers))),ks=an.indoorState,gs=function(vi,ss,ca,Ri,as){const ys={};for(const Mn of ss){const Ta=vi.layers[Mn];if(Ta)for(let vo=0;vo=Ri.maxzoom||Ri.visibility==="none")continue;Q(ca,this.zoom,Pt.brightness,Oe,this.worldview,Pt.activeFloors);const as=ht[Ri.id]=Ri.createBucket({index:it.bucketLayerIDs.length,layers:ca,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:ks,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Ye,worldview:this.worldview,localizable:vi,availableImages:Oe,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});it.bucketLayerIDs.push(ca.map(Mn=>f.F(Mn.id,Mn.scope)));let ys=as.prepare?as.prepare():null;ys!=null?(ys=ys.then(()=>as.populate(gs,Pt,this.tileID.canonical,this.tileTransform)),mr.push(ys)):as.populate(gs,Pt,this.tileID.canonical,this.tileTransform)}}const qr=()=>{$t.trim();const Br=!(!Pt.elevationFeatures||!Pt.elevationFeatures.some(Ri=>Ri.heightRange.min<0));let an,kn,Ln,Pi,Ms,ks,gs;const vi={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},ss=()=>{if(an)return this.status="done",tt(an);if(this.extraShadowCaster)this.status="done",tt(null,{buckets:Object.values(ht).filter(Ri=>!Ri.isEmpty()),featureIndex:it,collisionBoxArray:null,hasTunnelGeometry:Br,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Pt.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(kn&&Ln&&Pi&&gs){const as=new P(kn),ys=new Map;for(const[vo,co]of Ln.entries()){const{imagePosition:sc}=f.fn(vo,co,f.fo);ys.set(vo,sc)}const Mn={};for(const vo in ht){const co=ht[vo];co instanceof f.fp&&(Q(co.layers,this.zoom,Pt.brightness,Oe,this.worldview,Pt.activeFloors),Mn[vo]=f.fq(co,kn,as.positions,Ln,ys,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ms,this.worldview,Oe))}const Ta={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Je,Ln,Ms,()=>{Ta.iconsPending=!1,ca(Mn,as,Ta,void 0,gs)}),this.rasterizeIfNeeded(Je,Pi,ks,()=>{Ta.patternsPending=!1,ca(Mn,as,Ta,void 0,gs)})}},ca=(Ri,as,ys,Mn,Ta)=>{if(ys.iconsPending||ys.patternsPending)return;const vo=Ln.size>0||Pi.size>0,co=Object.keys(Ri).length>0;if(!vo&&!co)return this.status="done",void tt(null,{buckets:Object.values(ht).filter(ac=>!ac.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:as.image,lineAtlas:$t,imageAtlas:null,brightness:Pt.brightness});const sc=(ac,wd)=>{for(const xl in ht){const oc=ht[xl];if(xl in Ri)f.fv(oc,Ri[xl],this.showCollisionBoxes,Oe,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Ln,wd);else if(oc.hasPattern&&(oc instanceof f.fw||oc instanceof f.fl||oc instanceof f.e0)){Q(oc.layers,this.zoom,Pt.brightness,Oe,this.worldview,Pt.activeFloors);const Sd=Object.fromEntries(wd.patternPositions);oc.addFeatures(Pt,this.tileID.canonical,Sd,Oe,this.tileTransform,this.brightness)}}this.status="done",tt(null,{buckets:Object.values(ht).filter(xl=>!xl.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:as.image,lineAtlas:$t,imageAtlas:ac,brightness:Pt.brightness})};if(vo){const ac=new Map,wd=f.fr(Ln,ac),xl=f.fr(Pi,ac),oc=new f.fs(wd,xl,Ta,this.lut,ac);Je.send("checkAtlasCache",{descriptor:oc,scope:this.scope},(Sd,Tc)=>{let Td,ou;if(Sd&&f.w(`[Worker] Error checking atlas cache: ${Sd.message}`),Tc)Td=new f.ft(Tc.sourceHash),ou=Tc;else{const Ol=new f.fu(Ln,Pi,this.lut,Ta);Td=Ol,ou=Ol}sc(Td,ou)})}else sc(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Ri=f.fk(Pt.glyphDependencies,Mn=>Object.keys(Mn).map(Number));Object.keys(Ri).length?Je.send("getGlyphs",{uid:this.uid,stacks:Ri},(Mn,Ta)=>{an||(an=Mn,kn=Ta,ss())},void 0,!1,vi):kn={},gs=new Map;const as=Array.from(Pt.iconDependencies.keys()).map(Mn=>f.I.parse(Mn));as.length?Je.send("getImages",{images:as,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Mn,Ta)=>{if(!an){an=Mn,Ln=new Map,Ms=this.updateImageMapAndGetImageTaskQueue(Ln,Ta.images,Pt.iconDependencies);for(const[vo,co]of Ta.versions.entries())gs.set(vo,co);ss()}},void 0,!1,vi):(Ln=new Map,Ms=new Map);const ys=Array.from(Pt.patternDependencies.keys()).map(Mn=>f.I.parse(Mn));ys.length?Je.send("getImages",{images:ys,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Mn,Ta)=>{if(!an){an=Mn,Pi=new Map,ks=this.updateImageMapAndGetImageTaskQueue(Pi,Ta.images,Pt.patternDependencies);for(const[vo,co]of Ta.versions.entries())gs.set(vo,co);ss()}},void 0,!1,vi):(Pi=new Map,ks=new Map)}if(Pt.elevationFeatures&&Pt.elevationFeatures.length>0){const Ri=[];for(const ys of Object.values(ht))if(ys instanceof f.fl){const Mn=ys.getUnevaluatedPortalGraph();Mn&&Ri.push(Mn)}const as=f.fm.evaluate(Ri);for(const ys of Object.values(ht))if(ys instanceof f.fl){const Mn=de.layers[dt.decode(ys.sourceLayerIndex)];ys.setEvaluatedPortalGraph(as,Mn,this.tileID.canonical,Pt.availableImages,Pt.brightness)}}ss()};mr.length>0?Promise.allSettled(mr).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,Oe,Ye){Array.from(fe.values()).some(Je=>Je.usvg)?this.rasterize(de,fe,Oe,Ye):Ye()}updateImageMapAndGetImageTaskQueue(de,fe,Oe){const Ye=new Map;for(const Je of fe.keys()){const tt=Oe.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,Oe,Ye){this.rasterizeTask=de.send("rasterizeImages",{scope:this.scope,tasks:Oe},(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,Oe,Ye,Je){const tt=new f.ae(de,{brightness:fe,worldview:Ye,activeFloors:Je});for(const dt of ct)dt.recalculate(tt,Oe)}class re extends f.E{constructor({actor:de,layerIndex:fe,availableImages:Oe,availableModels:Ye,isSpriteLoaded:Je,tileProvider:tt,brightness:dt,maxUniformBufferBindings:it,maxUniformBlockSizeDwords:ht,disableSymbolUBO:$t}){super(),this.actor=de,this.layerIndex=fe,this.availableImages=Oe,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=$t}loadTileData(de,fe){if(!this.tileProvider)return this.loadVectorData(de,fe);const Oe=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:Oe.signal}).then(dt=>{if(Oe.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=>{Oe.signal.aborted||fe(dt instanceof Error?dt:new Error(String(dt)))}),()=>Oe.abort()}loadTile(de,fe){const Oe=de.uid,Ye=de&&de.request,Je=Ye&&Ye.collectResourceTiming,tt=this.loading[Oe]=new Z(de);tt.maxUniformBufferBindings=this.maxUniformBufferBindings,tt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,tt.disableSymbolUBO=this.disableSymbolUBO,tt.abort=this.loadTileData(de,(dt,it)=>{const ht=!this.loading[Oe];if(delete this.loading[Oe],tt.cancelRasterize(),ht||dt||!it)return tt.status="done",ht||(this.loaded[Oe]=tt),fe(dt);const $t=it.rawData,Pt={},mr=f.aP(it.responseHeaders);mr&&mr.expires&&(Pt.expires=mr.expires),mr&&mr.cacheControl&&(Pt.cacheControl=mr.cacheControl),tt.vectorTile=it.vectorTile||new f.fx(new f.a$($t));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=p(Ye);kn.length>0&&(an.resourceTiming=JSON.parse(JSON.stringify(kn)))}fe(null,Object.assign({rawTileData:$t.slice(0),responseHeaders:it.responseHeaders},Br,Pt,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[Oe]=tt})}reloadTile(de,fe){const Oe=this.loaded,Ye=de.uid;if(Oe&&Oe[Ye]){const Je=Oe[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 Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Oe]),fe()}removeTile(de,fe){const Oe=this.loaded,Ye=de.uid;Oe&&Oe[Ye]&&delete Oe[Ye],fe()}}class se{constructor(de){this.loading={}}loadTile(de,fe){const Oe=de.uid,{cancel:Ye}=f.b1(de.request,(Je,tt,dt)=>{const it=!this.loading[Oe];if(delete this.loading[Oe],it||Je||!tt)return fe(Je);this.decodeTile(Oe,tt,de.encoding).then(ht=>{const{expires:$t,cacheControl:Pt}=f.aP(dt);fe(null,Object.assign(ht,{expires:$t,cacheControl:Pt}))}).catch(ht=>fe(ht))});this.loading[Oe]={cancel:Ye}}async decodeTile(de,fe,Oe){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,Oe,tt),borderReady:tt}}reloadTile(de,fe){fe(null,null)}abortTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.cancel(),delete this.loading[Oe]),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 Oe=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),Oe}}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 Oe=this._mrt;this.status="parsing",this._entireBuffer=de;try{Oe.parseHeader(de),this._isHeaderLoaded=!0;const Ye=[];for(const Je in Oe.layers){const tt=Oe.getLayer(Je),dt=tt.getDataRange(tt.getBandList()),it=Oe.createDecodingTask(dt),ht=de.slice(dt.firstByte,dt.lastByte+1),$t=f.a_.performDecoding(ht,it).then(Pt=>it.complete(null,Pt)).catch(Pt=>it.complete(Pt,null));Ye.push($t)}Promise.allSettled(Ye).then(()=>fe(null,Oe)).catch(Je=>fe(Je))}catch(Ye){fe(Ye)}}}class _e{constructor({actor:de}){this.actor=de,this.loading={},this.loaded={}}loadTile(de,fe){const Oe=de.uid,Ye=de.request,Je=this.loading[Oe]=new ue(de),{cancel:tt}=f.b1(Ye,(dt,it,ht)=>{const $t=!this.loading[Oe];if(delete this.loading[Oe],$t||dt||!it)return Je.status="done",$t||(this.loaded[Oe]=Je),fe(dt);Je.parse(it,(Pt,mr)=>{if(Pt||!mr)return fe(Pt);fe(null,mr,ht)}),this.loaded[Oe]=Je});Je.abort=tt}reloadTile(de,fe){fe(null,void 0)}abortTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Oe]),fe()}removeTile(de,fe){const Oe=de.uid;this.loaded[Oe]&&delete this.loaded[Oe],fe()}decodeRasterArray(de,fe){f.a_.performDecoding(de.buffer,de.task).then(Oe=>fe(null,Oe)).catch(Oe=>fe(Oe))}}const we=f.fA.prototype.toGeoJSON;class Ce{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 Oe=[];for(const Ye of fe)Oe.push(new f.P(Ye[0],Ye[1]));de.push(Oe)}return de}}toGeoJSON(de,fe,Oe){return we.call(this,de,fe,Oe)}}class Me{constructor(de,fe){this.name=de,this.extent=f.an,this.length=fe.length,this._jsonFeatures=fe}feature(de){return new Ce(this._jsonFeatures[de])}}class Ae{constructor(de){this.layers={},this.extent=f.an;for(const fe of Object.keys(de))this.layers[fe]=new Me(fe,de[fe])}}const be=64/4096;class me{constructor(){this.features=new Map}clear(){this.features.clear()}load(de=[],fe){for(const Oe of de){const Ye=Oe.id;if(Ye==null)continue;let Je=this.features.get(Ye);Je&&this.updateCache(Je,fe),Oe.geometry?(Je=Ie(Oe),this.updateCache(Je,fe),this.features.set(Ye,Je)):this.features.delete(Ye),this.updateCache(Je,fe)}}updateCache(de,fe){for(const{canonical:Oe,uid:Ye}of Object.values(fe)){const{z:Je,x:tt,y:dt}=Oe;Pe(de,Math.pow(2,Je),tt,dt)&&delete fe[Ye]}}getTile(de,fe,Oe){const Ye=Math.pow(2,de),Je=[];for(const tt of this.features.values())Pe(tt,Ye,fe,Oe)&&Je.push(rt(tt,Ye,fe,Oe));return{features:Je}}getFeatures(){return[...this.features.values()]}}function Pe({minX:ct,minY:de,maxX:fe,maxY:Oe},Ye,Je,tt){return ct<(Je+1+be)/Ye&&de<(tt+1+be)/Ye&&fe>(Je-be)/Ye&&Oe>(tt-be)/Ye}function Ie(ct){const{id:de,geometry:fe,properties:Oe}=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:Oe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},dt=tt.geometry;if(Ye==="Point")Se(Je,dt,tt);else if(Ye==="MultiPoint")for(const it of Je)Se(it,dt,tt);else if(Ye==="LineString")tt.type=2,ve(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 Se([ct,de],fe,Oe){const Ye=f.aH(ct);let Je=f.aL(de);Je=Je<0?0:Je>1?1:Je,fe.push(Ye,Je),Oe.minX=Math.min(Oe.minX,Ye),Oe.minY=Math.min(Oe.minY,Je),Oe.maxX=Math.max(Oe.maxX,Ye),Oe.maxY=Math.max(Oe.maxY,Je)}function ve(ct,de,fe,Oe=!1,Ye=!1){const Je=[];for(const tt of ct)Se(tt,Je,fe);de.push(Je),Oe&&function(tt,dt){let it=0;for(let ht=0,$t=tt.length,Pt=$t-2;ht<$t;Pt=ht,ht+=2)it+=(tt[ht]-tt[Pt])*(tt[ht+1]+tt[Pt+1]);if(it>0===dt)for(let ht=0,$t=tt.length;ht<$t/2;ht+=2){const Pt=tt[ht],mr=tt[ht+1];tt[ht]=tt[$t-2-ht],tt[ht+1]=tt[$t-1-ht],tt[$t-2-ht]=Pt,tt[$t-1-ht]=mr}}(Je,Ye)}function We(ct,de,fe,Oe=!1){for(let Ye=0;Ye=tt&&Pt>=tt||(ht>=tt?($t+=Math.round(qr*((tt-ht)/Fr)),ht=tt):Pt>=tt&&(mr=$t+Math.round(qr*((tt-ht)/Fr)),Pt=tt),$t>=tt&&mr>=tt||($t>=tt?(ht+=Math.round(Fr*((tt-$t)/qr)),$t=tt):mr>=tt&&(Pt=ht+Math.round(Fr*((tt-$t)/qr)),mr=tt),dt&&ht===dt[dt.length-1][0]&&$t===dt[dt.length-1][1]||(dt=[[ht,$t]],Ye.push(dt)),dt.push([Pt,mr])))))}}function Et(ct,de,fe,Oe,Ye){const Je=(fe-be)/de,tt=(Oe-be)/de,dt=(fe+1+be)/de,it=(Oe+1+be)/de;function ht(mr,Fr){let qr=0;return mrdt&&(qr|=2),Frit&&(qr|=8),qr}let $t=[];for(let mr=1;mr<=8;mr*=2){let Fr=ct[ct.length-2],qr=ct[ct.length-1],Br=!(ht(Fr,qr)&mr);for(let an=0;an>31}function vt(ct,de){const{geometry:fe,type:Oe}=ct;let Ye=0,Je=0;if(Oe===1){de.writeVarint(Nt(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(Nt(1,1));const dt=tt.length-(Oe===3?1:0);for(let it=0;itct},nn=Math.fround||(cr=new Float32Array(1),ct=>(cr[0]=+ct,cr[0]));var cr;class xr{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:Oe,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=Oe;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 Oe=((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)Oe=-180,Je=180;else if(Oe>Je){const Pt=this.getClusters([Oe,Ye,180,tt],fe),mr=this.getClusters([-180,Ye,Je,tt],fe);return Pt.concat(mr)}const dt=this.trees[this._limitZoom(fe)],it=dt.range(lt(Oe),At(tt),lt(Je),At(Ye)),ht=dt.data,$t=[];for(const Pt of it){const mr=this.stride*Pt;$t.push(ht[mr+5]>1?tr(ht,mr,this.clusterProps):this.points[ht[mr+3]])}return $t}getChildren(de){const fe=this._getOriginId(de),Oe=this._getOriginZoom(de),Ye="No cluster with the specified id.",Je=this.trees[Oe];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,Oe-1)),it=Je.within(tt[fe*this.stride],tt[fe*this.stride+1],dt),ht=[];for(const $t of it){const Pt=$t*this.stride;tt[Pt+4]===de&&ht.push(tt[Pt+5]>1?tr(tt,Pt,this.clusterProps):this.points[tt[Pt+3]])}if(ht.length===0)throw new Error(Ye);return ht}getLeaves(de,fe,Oe){const Ye=[];return this._appendLeaves(Ye,de,fe=fe||10,Oe=Oe||0,0),Ye}getTile(de,fe,Oe){const Ye=this.trees[this._limitZoom(de)],Je=Math.pow(2,de),{extent:tt,radius:dt}=this.options,it=dt/tt,ht=(Oe-it)/Je,$t=(Oe+1+it)/Je,Pt={features:[]};return this._addTileFeatures(Ye.range((fe-it)/Je,ht,(fe+1+it)/Je,$t),Ye.data,fe,Oe,Je,Pt),fe===0&&this._addTileFeatures(Ye.range(1-it/Je,ht,1,$t),Ye.data,Je,Oe,Je,Pt),fe===Je-1&&this._addTileFeatures(Ye.range(0,ht,it/Je,$t),Ye.data,-1,Oe,Je,Pt),Pt.features.length?Pt:null}getClusterExpansionZoom(de){let fe=this._getOriginZoom(de)-1;for(;fe<=this.options.maxZoom;){const Oe=this.getChildren(de);if(fe++,Oe.length!==1)break;de=Oe[0].properties.cluster_id}return fe}_appendLeaves(de,fe,Oe,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,Oe,Ye,Je):Je1;let $t,Pt,mr;if(ht)$t=_n(fe,it,this.clusterProps),Pt=fe[it],mr=fe[it+1];else{const Br=this.points[fe[it+3]];$t=Br.properties;const[an,kn]=Br.geometry.coordinates;Pt=lt(an),mr=At(kn)}const Fr={type:1,geometry:[[Math.round(this.options.extent*(Pt*Je-Oe)),Math.round(this.options.extent*(mr*Je-Ye))]],tags:$t};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:Oe,extent:Ye,reduce:Je,minPoints:tt}=this.options,dt=Oe/(Ye*Math.pow(2,fe)),it=de.data,ht=[],$t=this.stride;for(let Pt=0;Ptfe&&(an+=it[Ln+5])}if(an>Br&&an>=tt){let kn,Ln=mr*Br,Pi=Fr*Br,Ms=-1;const ks=(Pt/$t<<5)+(fe+1)+this.points.length;for(const gs of qr){const vi=gs*$t;if(it[vi+2]<=fe)continue;it[vi+2]=fe;const ss=it[vi+5];Ln+=it[vi]*ss,Pi+=it[vi+1]*ss,it[vi+4]=ks,Je&&(kn||(kn=this._map(it,Pt,!0),Ms=this.clusterProps.length,this.clusterProps.push(kn)),Je(kn,this._map(it,vi)))}it[Pt+4]=ks,ht.push(Ln/an,Pi/an,1/0,ks,-1,an),Je&&ht.push(Ms)}else{for(let kn=0;kn<$t;kn++)ht.push(it[Pt+kn]);if(an>1)for(const kn of qr){const Ln=kn*$t;if(!(it[Ln+2]<=fe)){it[Ln+2]=fe;for(let Pi=0;Pi<$t;Pi++)ht.push(it[Ln+Pi])}}}}return ht}_getOriginId(de){return de-this.points.length>>5}_getOriginZoom(de){return(de-this.points.length)%32}_map(de,fe,Oe){if(de[fe+5]>1){const tt=this.clusterProps[de[fe+6]];return Oe?Object.assign({},tt):tt}const Ye=this.points[de[fe+3]].properties,Je=this.options.map(Ye);return Oe&&Je===Ye?Object.assign({},Je):Je}}function tr(ct,de,fe){return{type:"Feature",id:ct[de+3],properties:_n(ct,de,fe),geometry:{type:"Point",coordinates:[(Oe=ct[de],360*(Oe-.5)),Mt(ct[de+1])]}};var Oe}function _n(ct,de,fe){const Oe=ct[de+5],Ye=Oe>=1e4?`${Math.round(Oe/1e3)}k`:Oe>=1e3?Math.round(Oe/100)/10+"k":Oe,Je=ct[de+6],tt=Je===-1?{}:Object.assign({},fe[Je]);return Object.assign(tt,{cluster:!0,cluster_id:ct[de+3],point_count:Oe,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 Mt(ct){const de=(180-360*ct)*Math.PI/180;return 360*Math.atan(Math.exp(de))/Math.PI-90}function dr(ct,de,fe,Oe){let Ye=Oe;const Je=de+(fe-de>>1);let tt,dt=fe-de;const it=ct[de],ht=ct[de+1],$t=ct[fe],Pt=ct[fe+1];for(let mr=de+3;mrYe)tt=mr,Ye=Fr;else if(Fr===Ye){const qr=Math.abs(mr-Je);qrOe&&(tt-de>3&&dr(ct,de,tt,Oe),ct[tt+2]=Ye,fe-tt>3&&dr(ct,tt,fe,Oe))}function ur(ct,de,fe,Oe,Ye,Je){let tt=Ye-fe,dt=Je-Oe;if(tt!==0||dt!==0){const it=((ct-fe)*tt+(de-Oe)*dt)/(tt*tt+dt*dt);it>1?(fe=Ye,Oe=Je):it>0&&(fe+=tt*it,Oe+=dt*it)}return tt=ct-fe,dt=de-Oe,tt*tt+dt*dt}function hr(ct,de,fe,Oe){const Ye={id:ct??null,type:de,geometry:fe,tags:Oe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(de==="Point"||de==="MultiPoint"||de==="LineString")Xt(Ye,fe);else if(de==="Polygon")Xt(Ye,fe[0]);else if(de==="MultiLineString")for(const Je of fe)Xt(Ye,Je);else if(de==="MultiPolygon")for(const Je of fe)Xt(Ye,Je[0]);return Ye}function Xt(ct,de){for(let fe=0;fe0&&(tt+=Oe?(Ye*$t-ht*Je)/2:Math.sqrt(Math.pow(ht-Ye,2)+Math.pow($t-Je,2))),Ye=ht,Je=$t}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 ti(ct,de,fe,Oe){for(let Ye=0;Ye1?1:fe}function xi(ct,de,fe,Oe,Ye,Je,tt,dt){if(Oe/=de,Je>=(fe/=de)&&tt=Oe)return null;const it=[];for(const ht of ct){const $t=ht.geometry;let Pt=ht.type;const mr=Ye===0?ht.minX:ht.minY,Fr=Ye===0?ht.maxX:ht.maxY;if(mr>=fe&&Fr=Oe)continue;let qr=[];if(Pt==="Point"||Pt==="MultiPoint")la($t,qr,fe,Oe,Ye);else if(Pt==="LineString")Cr($t,qr,fe,Oe,Ye,!1,dt.lineMetrics);else if(Pt==="MultiLineString")As($t,qr,fe,Oe,Ye,!1);else if(Pt==="Polygon")As($t,qr,fe,Oe,Ye,!0);else if(Pt==="MultiPolygon")for(const Br of $t){const an=[];As(Br,an,fe,Oe,Ye,!0),an.length&&qr.push(an)}if(qr.length){if(dt.lineMetrics&&Pt==="LineString"){for(const Br of qr)it.push(hr(ht.id,Pt,Br,ht.tags));continue}Pt!=="LineString"&&Pt!=="MultiLineString"||(qr.length===1?(Pt="LineString",qr=qr[0]):Pt="MultiLineString"),Pt!=="Point"&&Pt!=="MultiPoint"||(Pt=qr.length===3?"Point":"MultiPoint"),it.push(hr(ht.id,Pt,qr,ht.tags))}}return it.length?it:null}function la(ct,de,fe,Oe,Ye){for(let Je=0;Je=fe&&tt<=Oe&&Sa(de,ct[Je],ct[Je+1],ct[Je+2])}}function Cr(ct,de,fe,Oe,Ye,Je,tt){let dt=Fn(ct);const it=Ye===0?_o:Yr;let ht,$t,Pt=ct.start;for(let an=0;anfe&&($t=it(dt,kn,Ln,Ms,ks,fe),tt&&(dt.start=Pt+ht*$t)):gs>Oe?vi=fe&&($t=it(dt,kn,Ln,Ms,ks,fe),ss=!0),vi>Oe&&gs<=Oe&&($t=it(dt,kn,Ln,Ms,ks,Oe),ss=!0),!Je&&ss&&(tt&&(dt.end=Pt+ht*$t),de.push(dt),dt=Fn(ct)),tt&&(Pt+=ht)}let mr=ct.length-3;const Fr=ct[mr],qr=ct[mr+1],Br=Ye===0?Fr:qr;Br>=fe&&Br<=Oe&&Sa(dt,Fr,qr,ct[mr+2]),mr=dt.length-3,Je&&mr>=3&&(dt[mr]!==dt[0]||dt[mr+1]!==dt[1])&&Sa(dt,dt[0],dt[1],dt[2]),dt.length&&de.push(dt)}function Fn(ct){const de=[];return de.size=ct.size,de.start=ct.start,de.end=ct.end,de}function As(ct,de,fe,Oe,Ye,Je){for(const tt of ct)Cr(tt,de,fe,Oe,Ye,Je,!1)}function Sa(ct,de,fe,Oe){ct.push(de,fe,Oe)}function _o(ct,de,fe,Oe,Ye,Je){const tt=(Je-de)/(Oe-de);return Sa(ct,Je,fe+(Ye-fe)*tt,1),tt}function Yr(ct,de,fe,Oe,Ye,Je){const tt=(Je-fe)/(Ye-fe);return Sa(ct,de+(Oe-de)*tt,Je,1),tt}function hn(ct,de){const fe=[];for(let Oe=0;Oe0&&de.size<(Ye?tt:Oe))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 $t=0;for(let Pt=0,mr=it.length,Fr=mr-2;Pt0===ht)for(let Pt=0,mr=it.length;Pt24)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[mr]=Jr(de,fe,Oe,Ye,ht),this.tileCoords.push({z:fe,x:Oe,y:Ye}),$t)){$t>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",fe,Oe,Ye,Fr.numFeatures,Fr.numPoints,Fr.numSimplified),console.timeEnd("creation"));const ss=`z${fe}`;this.stats[ss]=(this.stats[ss]||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 ss=Je-fe;if(Oe!==tt>>ss||Ye!==dt>>ss)continue}}if(Fr.source=null,de.length===0)continue;$t>1&&console.time("clipping");const qr=.5*ht.buffer/ht.extent,Br=.5-qr,an=.5+qr,kn=1+qr;let Ln=null,Pi=null,Ms=null,ks=null,gs=xi(de,Pt,Oe-qr,Oe+an,0,Fr.minX,Fr.maxX,ht),vi=xi(de,Pt,Oe+Br,Oe+kn,0,Fr.minX,Fr.maxX,ht);de=null,gs&&(Ln=xi(gs,Pt,Ye-qr,Ye+an,1,Fr.minY,Fr.maxY,ht),Pi=xi(gs,Pt,Ye+Br,Ye+kn,1,Fr.minY,Fr.maxY,ht),gs=null),vi&&(Ms=xi(vi,Pt,Ye-qr,Ye+an,1,Fr.minY,Fr.maxY,ht),ks=xi(vi,Pt,Ye+Br,Ye+kn,1,Fr.minY,Fr.maxY,ht),vi=null),$t>1&&console.timeEnd("clipping"),it.push(Ln||[],fe+1,2*Oe,2*Ye),it.push(Pi||[],fe+1,2*Oe,2*Ye+1),it.push(Ms||[],fe+1,2*Oe+1,2*Ye),it.push(ks||[],fe+1,2*Oe+1,2*Ye+1)}}getTile(de,fe,Oe){de=+de,fe=+fe,Oe=+Oe;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,Oe);let ht,$t=de,Pt=fe,mr=Oe;for(;!ht&&$t>0;)$t--,Pt>>=1,mr>>=1,ht=this.tiles[Ot($t,Pt,mr)];return ht&&ht.source?(tt>1&&(console.log("found parent tile z%d-%d-%d",$t,Pt,mr),console.time("drilling down")),this.splitTile(ht.source,$t,Pt,mr,de,fe,Oe),tt>1&&console.timeEnd("drilling down"),this.tiles[it]?Zr(this.tiles[it],Je):null):null}}function Ot(ct,de,fe){return 32*((1<ht.tags&&"3d_elevation_id"in ht.tags&&"source"in ht.tags&&ht.tags.source==="elevation",Je=Oe.features.filter(ht=>Ye(ht));let tt={_geojsonTileLayer:Oe.features};Je.length>0&&(tt={_geojsonTileLayer:Oe.features.filter(ht=>!Ye(ht)),hd_road_elevation:Je});const dt=new Ae(tt),it=function(ht){const $t=new f.a$;for(const Pt of Object.keys(ht))$t.writeMessage(3,_t,{name:Pt,features:ht[Pt]});return $t.finish()}(tt).buffer;de(null,{vectorTile:dt,rawData:it})}class Ei extends re{constructor(de){super(de),this.loadVectorData=Ro,this._dynamicIndex=new me}loadData(de,fe){const Oe=de&&de.request,Ye=Oe&&Oe.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 xr(function({superclusterOptions:it,clusterProperties:ht}){if(!ht||!it)return it;const $t={},Pt={},mr={accumulated:null,zoom:0},Fr={properties:null},qr=Object.keys(ht);for(const Br of qr){const[an,kn]=ht[Br],Ln=f.X(kn),Pi=f.X(typeof an=="string"?[an,["accumulated"],["get",Br]]:an);$t[Br]=Ln.value,Pt[Br]=Pi.value}return it.map=Br=>{Fr.properties=Br;const an={};for(const kn of qr)an[kn]=$t[kn].evaluate(mr,Fr);return an},it.reduce=(Br,an)=>{Fr.properties=an;for(const kn of qr)mr.accumulated=Br[kn],Br[kn]=Pt[kn].evaluate(mr,Fr)},it}(de)).load(tt.features):de.dynamic?this._dynamicIndex:function(it,ht){return new Zo(it,ht)}(tt,de.geojsonVtOptions)}catch(it){return fe(it)}const dt={};if(Ye){const it=p(Oe);it&&(dt.resourceTiming={},dt.resourceTiming[de.source]=JSON.parse(JSON.stringify(it)))}fe(null,dt)}})}reloadTile(de,fe){const Oe=this.loaded;return Oe&&Oe[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(Oe){fe(Oe)}}getClusterChildren(de,fe){try{fe(null,this._geoJSONIndex.getChildren(de.clusterId))}catch(Oe){fe(Oe)}}getClusterLeaves(de,fe){try{fe(null,this._geoJSONIndex.getLeaves(de.clusterId,de.limit,de.offset))}catch(Oe){fe(Oe)}}}class js{constructor(de,fe,Oe){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=Oe}parse(de,fe,Oe,Ye){this.status="parsing";const Je=new f.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),tt=[],dt=fe.familiesBySource[Oe.source],it=new f.ff(Je,Oe.promoteId);it.bucketLayerIDs=[],it.is3DTile=!0,f.fB(de).then(ht=>{const $t=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("MAPBOX_mesh_features")||ht.json.asset.extras&&ht.json.asset.extras.MAPBOX_mesh_features,Pt=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("EXT_meshopt_compression"),mr=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(Ln=>f.F(Ln.id,Ln.scope))),Br.recalculate(mr,[]);const an=f.fC(ht,1/f.cS(Oe.tileID.canonical)),kn=new f.fD(qr,an,Je,$t,Pt,this.brightness,it,this.worldview);$t||(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 Yn{constructor({actor:de,layerIndex:fe,availableImages:Oe,availableModels:Ye,brightness:Je,worldview:tt}){this.actor=de,this.layerIndex=fe,this.availableImages=Oe,this.availableModels=Ye,this.brightness=Je,this.loading={},this.loaded={},this.worldview=tt}loadTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe]=new js(de,this.brightness,this.worldview);f.b1(de.request,(Je,tt)=>{const dt=!this.loading[Oe];return delete this.loading[Oe],dt||Je?(Ye.status="done",dt||(this.loaded[Oe]=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[Oe]=Ye,it||!ht?fe(it):fe(null,ht)}):(Ye.status="done",this.loaded[Oe]=Ye,fe())})}reloadTile(de,fe){const Oe=this.loaded,Ye=de.uid;if(Oe&&Oe[Ye]){const Je=Oe[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 Oe=de.uid;this.loading[Oe]&&delete this.loading[Oe],fe()}removeTile(de,fe){const Oe=this.loaded,Ye=de.uid;Oe&&Oe[Ye]&&delete Oe[Ye],fe()}}const lo=new Map,au=new Map;class Px{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:Ei,"raster-dem":se,"raster-array":_e,"batched-model":Yn},this.workerSources={},this.self.registerWorkerSource=(fe,Oe)=>{if(this.workerSourceTypes[fe])throw new Error(`Worker source with name "${fe}" already registered.`);this.workerSourceTypes[fe]=Oe},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 Oe of this.rtlPluginParsingListeners)Oe(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(de,fe,Oe){delete this.layerIndexes[de],delete this.availableImages[de],delete this.availableModels[de],delete this.workerSources[de],Oe()}checkIfReady(de,fe,Oe){Oe()}setReferrer(de,fe){this.referrer=fe}spriteLoaded(de,fe){this.isSpriteLoaded[de]||(this.isSpriteLoaded[de]={});const{scope:Oe,isLoaded:Ye}=fe;if(this.isSpriteLoaded[de][Oe]=Ye,this.workerSources[de]&&this.workerSources[de][Oe])for(const Je in this.workerSources[de][Oe]){const tt=this.workerSources[de][Oe][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,Oe){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}Oe()}else Oe()}setModels(de,{scope:fe,models:Oe},Ye){if(this.availableModels[de]||(this.availableModels[de]={}),this.availableModels[de][fe]=Oe,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=Oe}Ye()}else Ye()}setProjection(de,fe){this.projections[de]=f.c0(fe)}setBrightness(de,fe,Oe){this.brightness=fe,Oe()}setContextParams(de,fe,Oe){this.maxUniformBufferBindings=fe.maxBindingPoints,this.maxUniformBlockSizeDwords=fe.maxUniformBlockSizeDwords,this.disableSymbolUBO=fe.disableSymbolUBO,Oe()}setWorldview(de,fe,Oe){this.worldview=fe,Oe()}setLayers(de,fe,Oe){this.getLayerIndex(de,fe.scope).replace(fe.layers,fe.options),Oe()}updateLayers(de,fe,Oe){this.getLayerIndex(de,fe.scope).update(fe.layers,fe.removedIds,fe.options),Oe()}loadTile(de,fe,Oe){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).loadTile(fe,Oe)}decodeRasterArray(de,fe,Oe){this.getWorkerSource(de,fe).decodeRasterArray(fe,Oe)}reloadTile(de,fe,Oe){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).reloadTile(fe,Oe)}abortTile(de,fe,Oe){this.getWorkerSource(de,fe).abortTile(fe,Oe)}removeTile(de,fe,Oe){this.getWorkerSource(de,fe).removeTile(fe,Oe)}removeSource(de,fe,Oe){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,Oe):Oe()}loadTileProvider(de,fe,Oe){(async function(Ye,Je){const tt=au.get(Ye);if(tt)return tt;const dt=lo.get(Ye);if(dt!==void 0)return dt;const it=import(Je).then(ht=>{const $t=ht.default;if(typeof $t!="function")throw new Error(`TileProvider "${Ye}" module must default-export a class`);if(typeof $t.prototype.loadTile!="function")throw new Error(`TileProvider "${Ye}" class must have a loadTile method`);return au.set(Ye,$t),$t}).finally(()=>{lo.delete(Ye)});return lo.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=>Oe(null,Ye)).catch(Ye=>Oe(Ye instanceof Error?Ye:new Error(typeof Ye=="string"?Ye:"Unknown error")))}loadWorkerSource(de,fe,Oe){try{this.self.importScripts(fe.url),Oe()}catch(Ye){Oe(Ye)}}syncRTLPluginState(de,fe,Oe){if(f.fF.isParsed())Oe(null,!0);else if(f.fF.isParsing())this.rtlPluginParsingListeners.push(Oe);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()?Oe(null,!0):this.rtlPluginParsingListeners.push(Oe))}catch(Ye){Oe(Ye)}}setConfig(de,fe){Object.assign(f.g,fe)}getAvailableImages(de,fe){this.availableImages[de]||(this.availableImages[de]={});let Oe=this.availableImages[de][fe];return Oe||(Oe=[]),Oe}getAvailableModels(de,fe){this.availableModels[de]||(this.availableModels[de]={});let Oe=this.availableModels[de][fe];return Oe||(Oe={}),Oe}getLayerIndex(de,fe){this.layerIndexes[de]||(this.layerIndexes[de]={});let Oe=this.layerIndexes[de][fe];return Oe||(Oe=this.layerIndexes[de][fe]=new E,Oe.scope=fe),Oe}getWorkerSource(de,fe,Oe){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:($t,Pt,mr,Fr,qr,Br)=>this.actor.send($t,Pt,mr,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:Oe,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return dt[de][tt][Ye][Je]}rasterizeImagesWorker(de,fe,Oe){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)}Oe(void 0,Ye)}removeRasterizedImages(de,fe,Oe){this.imageRasterizer.removeImagesFromCacheByIds(fe.imageIds,fe.scope,de),Oe()}enforceCacheSizeLimit(de,fe){f.fH(fe)}getWorkerPerformanceMetrics(de,fe,Oe){Oe(void 0,void 0)}}return f.fE(self)&&(self.worker=new Px(self)),Px}),o(["./shared"],function(s){var f="3.22.0";const p={create:"create",load:"load",fullLoad:"fullLoad"},y={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={},k=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 N,L,F=new Blob([""],{type:"text/javascript"}),$=URL.createObjectURL(F);try{L=new Worker($),N=!0}catch{N=!1}return L&&L.terminate(),URL.revokeObjectURL($),N}()?function(){var N=document.createElement("canvas");N.width=N.height=1;var L=N.getContext("2d");if(!L)return!1;var F=L.getImageData(0,0,1,1);return F&&F.width===N.width}()?(g[A=w&&w.failIfMajorPerformanceCaveat]===void 0&&(g[A]=function(N){var L,F=function($){var H=document.createElement("canvas"),Y=Object.create(v.webGLContextAttributes);return Y.failIfMajorPerformanceCaveat=$,H.getContext("webgl2",Y)}(N);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 P(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 Z(){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 N=Ae(d);return N.path=`/v4/${N.authority}.json`,N.params.push("secure"),w&&N.params.push(`language=${w}`),A&&N.params.push(`worldview=${A}`),this._makeAPIURL(N,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)):be(w)}normalizeSpriteURL(d,g,w,A){const N=Ae(d);return s.e(d)?(N.path=`/styles/v1${N.path}/sprite${g}${w}`,this._makeAPIURL(N,this._customAccessToken||A)):(N.path+=`${g}${w}`,be(N))}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 N=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&&N&&this._skuToken&&A.params.push(`sku=${this._skuToken}`),this._makeAPIURL(A,N)}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 N=w.params;return g&&(N=N.filter(L=>!L.match(/^access_token=/))),N.length&&(A+=`?${N.join("&")}`),A}canonicalizeTileset(d,g){const w=!!g&&s.e(g),A=[];for(const N of d.tiles||[])s.f(N)?A.push(this.canonicalizeTileURL(N,w)):A.push(N);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 N=d.params.indexOf("secure");N>=0&&d.params.splice(N,1)}if(A.path!=="/"&&(d.path=`${A.path}${d.path}`),!s.g.REQUIRE_ACCESS_TOKEN)return be(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(N=>N.indexOf("access_token")===-1),d.params.push(`access_token=${g||""}`),be(d)}}const Me=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Ae(v){const d=v.match(Me);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 be(v){const d=v.params.length?`?${v.params.join("&")}`:"";return`${v.protocol}://${v.authority}${v.path}${d}`}const me="mapbox.eventData";function Pe(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 Se{constructor(d){this.type=d,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(d){const g=Pe(s.g.ACCESS_TOKEN);let w="";return w=g&&g.u?s.j(g.u):s.g.ACCESS_TOKEN||"",d?`${me}.${d}:${w}`:`${me}:${w}`}fetchEventData(){const d=s.s("localStorage"),g=this.getStorageKey(),w=this.getStorageKey("uuid"),A=this.getStorageKey("uuidTimestamp");if(d)try{const N=localStorage.getItem(g);N&&(this.eventData=JSON.parse(N));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"),N=this.anonId,L=this.anonIdTimestamp;if(d&&N)try{localStorage.setItem(w,N),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 N=Ae(s.g.EVENTS_URL);N.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:be(N),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 ve extends Se{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 Se{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=Pe(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 N=new Date(this.eventData.lastSuccess),L=new Date(A),F=(A-this.eventData.lastSuccess)/864e5;w=w||F>=1||F<-1||N.getDate()!==L.getDate()}else w=!0;w?this.postEvent(A,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:_e,"enabled.telemetry":!1,userId:this.anonId},N=>{N||(this.eventData.lastSuccess=A,this.eventData.tokenU=g)},v):this.processRequests()}},rt=We.postTurnstileEvent.bind(We),at=new class extends Se{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(we)))}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 Se{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 N=this.getMapInstanceId(g),L={mapInstanceId:N,eventId:this.getEventId(N),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),pt=new ve({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Nt=pt.postMetricsEvent.bind(pt),er=new ve({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),vt=er.postMetricsEvent.bind(er),or=new class extends Se{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 N=performance.getEntriesByType("resource"),L=performance.getEntriesByType("mark"),F=function(ie){const le={};if(ie){for(const oe in ie)if(oe!=="other")for(const ge of ie[oe]){const pe=`${oe}ResolveRangeMin`,Ne=`${oe}ResolveRangeMax`,Le=`${oe}RequestCount`,xe=`${oe}RequestCachedCount`;le[pe]=Math.min(le[pe]||1/0,ge.startTime),le[Ne]=Math.max(le[Ne]||-1/0,ge.responseEnd);const Ze=ze=>{le[ze]===void 0&&(le[ze]=0),++le[ze]};ge.transferSize!==void 0&&ge.transferSize===0&&Ze(xe),Ze(Le)}}return le}(function(ie,le){const oe={};if(ie)for(const ge of ie){const pe=le(ge);oe[pe]===void 0&&(oe[pe]=[]),oe[pe].push(ge)}return oe}(N,_)),$=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(p)){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 ge=oe.split("/").slice(-2);if(ge.length===2)return`mapbox://styles/${ge[0]}/${ge[1]}`}}}(N)),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 Se{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 N={url:be(A),headers:{"Content-Type":"text/plain"}};this.pendingRequest=s.h(N,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(we)))}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}},cr=nn.getSessionAPI.bind(nn),xr=new Set;function tr(v,d){d?xr.add(v):xr.delete(v)}class _n{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 Mt(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 ur{constructor(d){this.active={},this.name=d}acquire(d,g=ur.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}}ur.workerCount=2;class hr{constructor(d,g,w="Worker",A=ur.workerCount){this.workerPool=d,this.actors=[],this.currentActor=0,this.id=s.r();const N=this.workerPool.acquire(this.id,A);for(let L=0;L{this.ready=!0})}broadcast(d,g,w){s.t(this.actors,(A,N)=>{A.send(d,g,N)},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 Xt,Pr;function Rn(){return Xt||(Xt=new ur),Xt}hr.Actor=s.A;class ci 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 ur("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),N=A.get(d.toString())||0;A.set(d.toString(),N+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=[],N=[],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)?N.push(Y):te.addPendingRequest(Y))}if(A.length===0)return void this._notify(N,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:N}=d;for(const[L,F]of A.entries()){const $=this.getImage(F.id,N);$&&w.set(L,{image:$,imageVariant:F})}this._rasterizeImages(N,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[N,{image:L,imageVariant:F}]of g.entries())A.set(N,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),N=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}),N.set(s.I.toString(L),$)}w(null,{images:N,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(),N=this.patterns.get(g),L=N.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),N.get(A).position}getPatternInFlightId(d,g){return s.F(d,g)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(d,g,w,A,N){const L=d.toString(),F=N?N.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},N=new s.H(A,w,s.G);this.patterns.get(g).set(d.toString(),{bin:A,position:N})}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:N,h:L}=s.J(A),F=this.atlasImage.get(d);F.resize({width:N||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,ge=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:ge,height:pe},g),s.q.copy(oe,F,{x:0,y:pe-ee},{x:ie,y:le-ee},{width:ge,height:ee},g),s.q.copy(oe,F,{x:0,y:0},{x:ie,y:le+pe},{width:ge,height:ee},g),s.q.copy(oe,F,{x:ge-ee,y:0},{x:ie-ee,y:le},{width:ee,height:pe},g),s.q.copy(oe,F,{x:0,y:0},{x:ie+ge,y:le},{width:ee,height:pe},g),s.q.copy(oe,F,{x:ge-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+ge,y:le-ee},{width:ee,height:ee},g),s.q.copy(oe,F,{x:0,y:0},{x:ie+ge,y:le+pe},{width:ee,height:ee},g),s.q.copy(oe,F,{x:ge-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 N=w.get(A.toString());lt(N)&&this.updateImage(A,g,N)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function ti(v){const d=v.value,g=v.valueSpec,w=v.style,A=v.styleSpec,N=v.key,L=v.arrayElementValidator||Ei;if(!Array.isArray(d))return[new s.V(N,d,`array expected, ${s.M(d)} found`)];if(g.length&&d.length!==g.length)return[new s.V(N,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 wa(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 N,L,F,$={};const H=A!=="categorical"&&g.property===void 0,Y=!H,te=function(oe){const ge=oe.stops;return Array.isArray(ge)&&Array.isArray(ge[0])&&s.K(ge[0][0])}(g),ee=js({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 ge=[];const pe=oe.value;return ge=ge.concat(ti({key:oe.key,value:pe,valueSpec:oe.valueSpec,style:oe.style,styleSpec:oe.styleSpec,arrayElementValidator:ie})),Array.isArray(pe)&&pe.length===0&&ge.push(new s.V(oe.key,pe,"array must have at least one stop")),ge},default:function(oe){return Ei({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 ge=[];const pe=oe.value,Ne=oe.key;if(!Array.isArray(pe))return[new s.V(Ne,pe,`array expected, ${s.M(pe)} found`)];if(pe.length!==2)return[new s.V(Ne,pe,`array length 2 expected, length ${pe.length} found`)];if(te){if(!s.K(pe[0]))return[new s.V(Ne,pe,`object expected, ${s.M(pe[0])} found`)];const Le=pe[0];if(Le.zoom===void 0)return[new s.V(Ne,pe,"object stop key must have zoom")];if(Le.value===void 0)return[new s.V(Ne,pe,"object stop key must have value")];const xe=s.L(Le.zoom);if(typeof xe!="number")return[new s.V(Ne,Le.zoom,"stop zoom values must be numbers")];if(F&&F>xe)return[new s.V(Ne,Le.zoom,"stop zoom values must appear in ascending order")];xe!==F&&(F=xe,L=void 0,$={}),ge=ge.concat(js({key:`${Ne}[0]`,value:pe[0],valueSpec:{zoom:{}},style:oe.style,styleSpec:oe.styleSpec,objectElementValidators:{zoom:zi,value:le}}))}else ge=ge.concat(le({key:`${Ne}[0]`,value:pe[0],style:oe.style,styleSpec:oe.styleSpec},pe));return s.U(s.W(pe[1]))?ge.concat([new s.V(`${Ne}[1]`,pe[1],"expressions are not allowed in function stops.")]):ge.concat(Ei({key:`${Ne}[1]`,value:pe[1],valueSpec:w,style:oe.style,styleSpec:oe.styleSpec}))}function le(oe,ge){const pe=s.M(oe.value),Ne=s.L(oe.value),Le=oe.value!==null?oe.value:ge;if(N){if(pe!==N)return[new s.V(oe.key,Le,`${pe} stop domain type must match previous stop domain type ${N}`)]}else N=pe;if(pe!=="number"&&pe!=="string"&&pe!=="boolean"&&typeof Ne!="number"&&typeof Ne!="string"&&typeof Ne!="boolean")return[new s.V(oe.key,Le,"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,Le,xe)]}return A!=="categorical"||pe!=="number"||typeof Ne=="number"&&isFinite(Ne)&&Math.floor(Ne)===Ne?A!=="categorical"&&pe==="number"&&typeof Ne=="number"&&typeof L=="number"&&L!==void 0&&Nenew 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 la(g,v);if(v.expressionContext==="appearance")return Cr(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 la(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(...la(A,d))}),w)}function Cr(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(...Cr(A,d))}),w)}function Fn(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))?xi(Object.assign({},v,{expressionContext:"filter",valueSpec:v.styleSpec[`filter_${v.layerType||"fill"}`]})):Sa(v)}function Sa(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=Fn({key:`${g}[0]`,value:d[0],valueSpec:w.filter_operator});const N=()=>{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`)),N();break;case"==":case"!=":d.length!==3&&A.push(new s.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),N();break;case"in":case"!in":N();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(js({key:w,value:g,valueSpec:N.layer,style:v.style,styleSpec:v.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Ei({key:`${w}.type`,value:g.type,valueSpec:N.layer.type,style:v.style,styleSpec:v.styleSpec,object:g,objectKey:"type"}),filter:$=>As(Object.assign({layerType:L},$)),layout:$=>js({layer:g,key:$.key,value:$.value,valueSpec:{},style:$.style,styleSpec:$.styleSpec,objectElementValidators:{"*":H=>hn(Object.assign({layerType:L},H))}}),paint:$=>js({layer:g,key:$.key,value:$.value,valueSpec:{},style:$.style,styleSpec:$.styleSpec,objectElementValidators:{"*":H=>Yr(Object.assign({layerType:L,layer:g},H))}}),appearances($){const H=ti({key:$.key,value:$.value,valueSpec:$.valueSpec,style:$.style,styleSpec:$.styleSpec,arrayElementValidator:ee=>function(ie){const{key:le,layer:oe,layerType:ge}=ie,pe=s.L(ie.value),Ne=s.L(pe.name),Le=s.L(pe.condition),xe=js({key:le,value:pe,valueSpec:ie.styleSpec.appearance,style:ie.style,styleSpec:ie.styleSpec,objectElementValidators:{condition:Ze=>function(ze){const Ke=[];return Ke.push(...xi({key:ze.key,value:ze.object.condition,valueSpec:s.a8.appearance.condition,expressionContext:"appearance"})),Ke}(Object.assign({layer:oe,layerType:ge},Ze)),properties:Ze=>function(ze){const Ke=[],{styleSpec:De,layer:Be,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:Be,layerType:qe,value:xt[ft],valueSpec:Rt==="paint"?st[ft]:Qe[ft]});Ke.push(..._o(Ft,Rt))}return Ke}(Object.assign({layer:oe,layerType:ge},Ze))}});return Ne!=="hidden"&&Le===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 ui={promoteId:function v({key:d,value:g}){if(s.a2(g))return Zr({key:d,value:g});if(Array.isArray(g)){const A=[],N=s.W(g),L=s.X(N);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 N=s.L(d.type);let L=[];switch(["vector","raster","raster-dem","raster-array"].includes(N)&&("url"in d||"tiles"in d||L.push(new s.a5(g,d,'Either "url" or "tiles" is required.'))),N){case"vector":case"raster":case"raster-dem":case"raster-array":return L=L.concat(js({key:g,value:d,valueSpec:w[`source_${N.replace("-","_")}`],style:v.style,styleSpec:w,objectElementValidators:ui})),L;case"geojson":if(L=js({key:g,value:d,valueSpec:w.source_geojson,style:A,styleSpec:w,objectElementValidators:ui}),"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(...xi({key:`${g}.${F}.map`,value:Y,expressionContext:"cluster-map"})),L.push(...xi({key:`${g}.${F}.reduce`,value:te,expressionContext:"cluster-reduce"}))}}return L;case"video":return js({key:g,value:d,valueSpec:w.source_video,style:A,styleSpec:w});case"image":return js({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 Fn({key:`${g}.type`,value:d.type,valueSpec:{values:Bn(w)}})}}function Bn(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 ts(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 N=[];for(const L in d){const F=L.match(/^(.*)-transition$/),$=L.match(/^(.*)-use-theme$/);N=N.concat($&&w[$[1]]?Ei({key:L,value:d[L],valueSpec:{type:"string"},style:A,styleSpec:g}):F&&w[F[1]]&&w[F[1]].transition?Ei({key:L,value:d[L],valueSpec:g.transition,style:A,styleSpec:g}):w[L]?Ei({key:L,value:d[L],valueSpec:w[L],style:A,styleSpec:g}):[new s.V(L,d[L],`unknown property "${L}"`)])}return N}function yl(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,N=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:ti,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:zi,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:Fn,filter:As,function:wa,layer:xn,object:js,source:Jr,model:s.a9,light:ts,"light-3d":yl,terrain:Zo,fog:Ot,string:Zr,formatted:function(v){return Zr(v).length===0?[]:xi(v)},resolvedImage:function(v){return Zr(v).length===0?[]:xi(v)},projection:function(v){const d=v.value,g=v.styleSpec,w=g.projection,A=v.style;if(s.K(d)){let N=[];for(const L in d)N=N.concat(Ei({key:L,value:d[L],valueSpec:w[L],style:A,styleSpec:g}));return N}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,...N}=g;Object.defineProperty(N,"__line__",{value:g.__line__,enumerable:!1});let L=js(Object.assign({},v,{value:N,valueSpec:w.import}));return s.L(N.id)===""&&L.push(new s.V(`${v.key}.id`,N,"import id can't be an empty string")),A&&(L=L.concat(lo(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 N=s.L(d.type);let L=[];if(L=L.concat(js({key:g,value:d,valueSpec:w[`iconset_${N}`],style:A,styleSpec:w})),function(F,$){return!(F!=="source"||!$.source)}(N,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 Ei(v,d=!1){const g=v.value,w=v.valueSpec,A=v.styleSpec;if(w.expression){if(s.a6(s.L(g)))return wa(v);if(s.U(s.W(g)))return xi(v)}if(w.type&&Ro[w.type]){const N=Ro[w.type](v);return d===!0&&N.length>0&&Array.isArray(v.value)?xi(v):N}return js(Object.assign({},v,{valueSpec:w.type?A[w.type]:w}))}function js(v){const d=v.key,g=v.value,w=v.valueSpec||{},A=v.objectElementValidators||{},N=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=Ei:A["*"]?Y=A["*"]:w["*"]&&(Y=Ei),Y?F=F.concat(Y({key:(d&&`${d}.`)+$,value:g[$],valueSpec:w[H]||w["*"],style:N,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 Yn({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 lo(v,d=s.a8,g={}){return js({key:g.key||"",value:v,valueSpec:Object.assign(d.$root,{"*":{type:"*"}}),styleSpec:d,style:v,objectElementValidators:{glyphs:Yn}})}function au(v,d=s.a8){return Pt(lo(v,d))}const Px=v=>Pt(Jr(v)),ct=v=>Pt(ts(v)),de=v=>Pt(yl(v)),fe=v=>Pt(Zo(v)),Oe=v=>Pt(Ot(v)),Ye=v=>Pt(function(d){const g=d.value,w=d.style,A=d.styleSpec,N=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($&&N[$[1]]&&N[$[1]].transition?Ei({key:F,value:g[F],valueSpec:A.transition,style:w,styleSpec:A}):N[F]?Ei({key:F,value:g[F],valueSpec:N[F],style:w,styleSpec:A}):[new s.a5(F,g[F],`unknown property "${F}"`)])}return L}(v)),Je=v=>Pt(function(d){const g=d.value,w=d.style,A=d.styleSpec,N=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($&&N[$[1]]&&N[$[1]].transition?Ei({key:F,value:g[F],valueSpec:A.transition,style:w,styleSpec:A}):N[F]?Ei({key:F,value:g[F],valueSpec:N[F],style:w,styleSpec:A}):[new s.a5(F,g[F],`unknown property "${F}"`)])}return L}(v)),tt=v=>Pt(xn(v)),dt=v=>Pt(As(v)),it=v=>Pt(Yr(v)),ht=v=>Pt(hn(v)),$t=v=>Pt(s.a9(v));function Pt(v){return v.slice().sort((d,g)=>d.line&&g.line?d.line-g.line:0)}function mr(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)&&mr(this,d.call(au,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 N of d.zoomStops)A=d.evaluate(new s.ae(N,{worldview:this.worldview})),A>.01?(g=N,w=-1):w=N;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 Ln=.05;function Pi(v,d,g,w){const A=s.aj(45,65,g),[N,L]=Ms(v,w);let F=1-Math.min(1,Math.exp((d-N)/(L-N)*-6));return F*=F*F,F=Math.min(1,1.00747*F),F*A*v.alpha}function Ms(v,d){const g=.5/Math.tan(.5*d);return[v.range[0]+g,v.range[1]+g]}function ks(v,d,g,w,A){const N=s.ah([],[d,g,w],A.mercatorFogMatrix);return Pi(v,s.ai(N),A.pitch,A._fov)}function gs(v,d,g,w,A,N,L){const F=[[g,w,0],[A,w,0],[A,N,0],[g,N,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[Pi(v,$,L.pitch,L._fov),Pi(v,H,L.pitch,L._fov)]}const vi=s.a8.fog;class ss extends s.E{constructor(d,g,w,A){super();const N=new s.ab({range:new s.ac(vi.range),color:new s.ac(vi.color),"color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new s.ac(vi["high-color"]),"high-color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new s.ac(vi["space-color"]),"space-color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new s.ac(vi["horizon-blend"]),"star-intensity":new s.ac(vi["star-intensity"]),"vertical-range":new s.ac(vi["vertical-range"])});this._transitionable=new s.aa(N,w,new Map(A)),this.set(d,A),this._transitioning=this._transitionable.untransitioned(),this._transform=g,this.properties=new s.ak(N),this.scope=w}get state(){const d=this._transform,g=d.projection.name==="globe",w=s.al(d.zoom),A=this.properties.get("range"),N=[.5,3];return{range:g?[s.am(N[0],A[0],w),s.am(N[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(Oe,d,w))return;const A=Object.assign({},d);for(const N of Object.keys(vi))A[N]===void 0&&(A[N]=vi[N].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,N){const L=s.ag.fromLngLat(A),F=N.elevation?N.elevation.getAtPointOrZero(L):0;return ks(w,L.x,L.y,F,N)}(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,N){return this._transform.projection.supportsFog?gs(this.state,d,g,w,A,N,this._transform):[1,1]}getFovAdjustedRange(d){return this._transform.projection.supportsFog?Ms(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 N;if(A[2]>=0)N=A;else{const L=d.points[w-4];N=s.ao(L,A,L[2]/(L[2]-A[2]))}if(ks(this.state,N[0],N[1],0,this._transform)>=Ln)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)&&mr(this,d.call(au,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}}let ca,Ri,as,ys=class extends s.E{constructor(v,d,g,w){super();const A=ca||(ca=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),N=[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:N,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 N of Object.keys(A))w[N]===void 0&&(w[N]=A[N].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)&&mr(this,v.call(au,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}},Mn=class extends s.E{constructor(v,d,g,w){super();const A=Ri||(Ri=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),N=[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:N,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 N of Object.keys(A))w[N]===void 0&&(w[N]=A[N].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)&&mr(this,v.call(au,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}};class Ta 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 vo=()=>as||(as=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 co;const sc=()=>co||(co=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 ac{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 N=s.P.convert(d);w=[N],A=g.isPointAboveHorizon(N)}else{const N=s.P.convert(d[0]),L=s.P.convert(d[1]),F=N.add(L)._div(2);w=[N,L],A=s.as(N,L).every($=>g.isPointAboveHorizon($))&&g.isPointAboveHorizon(F)}return new ac(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),N=this.cameraPoint.clone(),L=+(N.x>g.x)+ +(N.x>w.x);switch(3*(+(N.y>g.y)+ +(N.y>w.y))+L){case 0:A[0]=N,A[4]=N.clone();break;case 1:A.splice(1,0,N);break;case 2:A[1]=N;break;case 3:A.splice(4,0,N);break;case 5:A.splice(2,0,N);break;case 6:A[3]=N;break;case 7:A.splice(3,0,N);break;case 8:A[2]=N}return A}containsTile(d,g,w,A=0){const N=Math.max(d.queryPadding,d.evaluateQueryRenderedFeaturePadding())/g._pixelsPerMercatorPixel+1,L=w?this._bufferedCameraMercator(N,g):this._bufferedScreenMercator(N,g);let F=d.tileID.wrap+(L.unwrapped?A:0);const $=L.polygon.map(ge=>s.au(d.tileTransform,ge,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(ge=>s.aw(d.tileTransform,ge,F)),Y=H.map(ge=>new s.P(ge[0],ge[1])),te=g.getFreeCameraOptions().position||new s.ag(0,0,0),ee=s.aw(d.tileTransform,te,F),ie=H.map(ge=>{const pe=s.ax(ge,ge,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=oc(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(N=>g.pointCoordinate3D(N)),unwrapped:!0},this._screenRaycastCache[w]=A,A}}_bufferedCameraMercator(d,g){const w=oc(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(N=>g.pointCoordinate3D(N)),unwrapped:!0},this._cameraRaycastCache[w]=A,A}}_projectAndResample(d,g){const w=function(N,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(N,te)&&$[3]1?wd(N.slice(0,ge),L):[],Le=genew s.P(xl(Ke.x),Ke.y)),Le=Le.map(Ke=>new s.P(xl(Ke.x),Ke.y));const xe=[...Ne];xe.length===0&&xe.push(Le[Le.length-1]);const Ze=s.am(xe[xe.length-1].y,(Le.length===0?Ne[0]:Le[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),Le.length===0?xe.push(Ne[0]):xe.push(...Le),{polygon:xe.map(Ke=>new s.ag(Ke.x,Ke.y)),unwrapped:!1}}(d,g);if(w)return w;const A=function(N,L){let F=!1,$=-1/0,H=0;for(let te=0;te$&&($=N[te].x,H=te);for(let te=0;te.5&&(ie.x{te.x-=1}),{polygon:N,unwrapped:F}}(wd(d,g).map(N=>new s.P(xl(N.x),N.y)),g);return{polygon:A.polygon.map(N=>new s.ag(N.x,N.y)),unwrapped:A.unwrapped}}}function wd(v,d){return s.aI(v,g=>{const w=d.pointCoordinate3D(g);g.x=w.x,g.y=w.y},1/256)}function xl(v){return v<0?1+v%1:v%1}function oc(v){return 100*v|0}function Sd(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 N of A.variants){if(N==null||typeof N!="object"||N.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(N.capabilities))throw new Error("capabilities must be an array");if(N.capabilities.length===1&&N.capabilities[0]==="meshopt")return Object.assign(A,N)}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 Tc(v,d,g,w,A){const N=function(F,$){if(F)return A(F);if($){v.url&&$.tiles&&v.tiles&&delete v.tiles;const H=Sd(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(()=>N(null,L)):v.url?s.m(d.transformRequest(d.normalizeSourceURL(v.url,null,g,w),s.R.Source),N):s.o.frame(()=>{const{data:F,...$}=v;N(null,$)})}function Td(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),N=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 N=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&&!N)return this._loaded=!0,this.fire(new s.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(d&&d());this._tileJSONRequest=N?this._loadWithProvider(N,A):Tc(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,N=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:N,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=Sd(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=ou.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),N=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:N,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 Rx 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=Tc(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(N=>N.id)),this.tileBounds=ou.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),(N,L,F)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(N)return d.state="errored",g(N);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 pT([v,d],g,w,{scaled:A=!0}={}){const{tileSize:N,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:ge=!0}={}){if(!oe)throw new Error("bandView is undefined");const{data:pe,tileSize:Ne,buffer:Le,offset:xe,scale:Ze,dimension:ze}=oe;if(ie<-Le||ie>Ne+Le||le<-Le||le>Ne+Le)throw new Error(`Point (${ie}, ${le}) out of bounds for tileSize=${Ne}, buffer=${Le}`);const Ke=(le+Le)*(Ne+2*Le)+(ie+Le);if(new Uint32Array(pe.buffer)[Ke]===4294967295)return null;let De=[];De=ge?[]:new oe.data.constructor(ze);for(let Be=0;Be{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",N,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,(N,L)=>{N?(d.state="errored",this.fire(new s.B(N))):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:N})=>N===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 N=null;g instanceof s.aS?N=g.paint.get("raster-array-band"):g instanceof s.aT&&(N=g.paint.get("raster-particle-array-band"));const L=N||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 N of g){const[L,F]=N.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(N,ie)}return w}queryRasterArrayValueByBandId(d,g,w){const A=g._mrt;return new Promise(N=>{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:pT([d.lng,d.lat],A,H.getBandView(ee)),F.delete(s.F($,ee)),F.size===0&&N(L)})},!1))}F.size===0&&N(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},(N,L,F)=>{if(N)return this._loadTilePending[d.uid].forEach($=>$(N,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,N)=>{this._loadTileForQuery(g,(L,F)=>{L?N(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,N,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 N={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&A&&A.resourceTiming&&A.resourceTiming[this.id]&&(N.resourceTiming=A.resourceTiming[this.id]),v&&(this._partialReload=!0),this.fire(new s.C("data",N)),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,N=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:N,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};v.request=this.actor.send(g,L,(F,$)=>N&&!$?(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=Tc(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 ou(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 N=Object.values(v.buckets);for(const L of N)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(N,L){return v.aborted?d(null):N&&N.status!==404?d(N):(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(N=>typeof N!="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 ou(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,N=new AbortController,L=Promise.resolve(this._implementation.loadTile({x:g,y:w,z:A},{signal:N.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=()=>N.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"}))}}},pv=function(v,d,g,w){const A=new mv[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 gT(v,d,g=""){return`${g}:${d.id||""}:${d.layer.id}:${function(w){if("layerId"in w)return`layer:${w.layerId}`;{const{featuresetId:A,importId:N}=w;return`featureset:${A}${N?`:import:${N}`:""}`}}(v.target)}`}function Ed(v,d,g,w=""){if(v.uniqueFeatureID){const A=gT(v,d,w);if(g.has(A))return!0;g.add(A)}return!1}function VC(v,d,g,w,A=!1,N=void 0){const L=d.sourceCache.transform,F=d.sourceCache.tilesIn(v,d.has3DLayers,A);F.sort(yv);const $=[];for(const H of F){const Y=H.tile.queryRenderedFeatures(d,H,g,w,L,A,N);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 ge in ie){const pe=ie[ge],Ne=oe[ge]=oe[ge]||{},Le=Y[ge]=Y[ge]||[];for(const xe of pe)Ne[xe.featureIndex]||(Ne[xe.featureIndex]=!0,Le.push(xe))}}return Y}($)}function gv(v,d,g,w,A,N){const L={},F=w.queryRenderedSymbols(v),$=[];for(const H of Object.keys(F).map(Number))$.push(A[H]);$.sort(yv);for(const H of $){const Y=H.featureIndex.lookupSymbolFeatures(F[H.bucketInstanceId],H.bucketIndex,H.sourceLayerIndex,d,g,N);for(const te in Y){const ee=L[te]=L[te]||[],ie=Y[te];ie.sort((le,oe)=>{const ge=H.featureSortOrder;if(ge){const pe=ge.indexOf(le.featureIndex);return ge.indexOf(oe.featureIndex)-pe}return oe.featureIndex-le.featureIndex});for(const le of ie)ee.push(le)}}return L}function yT(v,d){const g=v.getRenderableIds().map(N=>v.getTileByID(N)),w=[],A={};for(let N=0;N{if(N)g(N);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,N=>{if(N)return void A(N);this.updateTextureDescriptor(d,g,w);const L=this.textureDescriptorPerLayer.get(g);A(null,L?L.img:null)})}fetchBand(d,g,w,A,N=!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,ge)=>{$.complete(oe,ge),oe?A(oe):(Y.forEach(pe=>pe(null,ge)),this._taskQueue.delete(H))},ee=(oe,ge)=>{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:ge,task:$},te,void 0,!0);if(g!==null){const Ne=this._workQueuePerLayer.get(g)||[];Ne.push(()=>{pe&&pe.cancel(),$.cancel()}),this._workQueuePerLayer.has(g)||this._workQueuePerLayer.set(g,Ne)}};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}`}}),ge=s.b1(oe,ee);if(g!==null){const pe=this._fetchQueuePerLayer.get(g)||[];pe.push(()=>{ge.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:N,tileSize:L,buffer:F,offset:$,scale:H}=A.getBandView(w),Y=L+2*F,te=new s.q({width:Y,height:Y},N),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 rg{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 N={value:g,timeout:void 0};if(w!==void 0&&(N.timeout=setTimeout(()=>{this.remove(d,N)},w)),this.data[A].push(N),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),N=this.data[w][A];return this.data[w].splice(A,1),N.timeout&&clearTimeout(N.timeout),this.data[w].length===0&&delete this.data[w],this.onRemove(N.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 xT{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 N in this.state[d])N!==A&&(this.deletedStates[d][N]=null)}else if(this.deletedStates[d]&&this.deletedStates[d][A]===null){this.deletedStates[d][A]={};for(const N in this.state[d][A])w[N]||(this.deletedStates[d][A][N]=null)}else for(const N in w)this.deletedStates[d]&&this.deletedStates[d][A]&&this.deletedStates[d][A][N]===null&&delete this.deletedStates[d][A][N]}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]||{},N=this.deletedStates[d];if(N===null)return{};if(g!==void 0){const F=String(g),$=Object.assign({},w[F],A[F]);if(N){const H=N[g];if(H===null)return{};for(const Y in H)delete $[Y]}return $}const L=Object.assign({},w,A);if(N)for(const F in N)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 N={};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]),N[L]=this.state[A][L];w[A]=N}for(const A in this.deletedStates){this.state[A]=this.state[A]||{};const N={};if(this.deletedStates[A]===null)for(const L in this.state[A])N[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];N[L]=this.state[A][L]}w[A]=w[A]||{},Object.assign(w[A],N)}if(this.stateChanges={},this.deletedStates={},Object.keys(w).length!==0)for(const A in d)d[A].refreshFeatureState(g,w)}}class lu 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 rg(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 xT,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(_T).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,N)=>{const L=A.tileID,F=N.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(_T).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,N){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;N&&N.responseHeaders&&(L=N.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-=$)),N.dem&&A.dem&&(A.dem.backfillBorder(N.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 N in this._tiles){let L=this._tiles[N];if(A[N]||!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),N=this._getLoadedTile(A);if(N)return N}}_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,N=Math.floor(w*A*5),L=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,N):N,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 N=this._tiles[A];N.tileID=N.tileID.unwrapTo(N.tileID.wrap+g),w[N.tileID.key]=N}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,N){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 ge of oe)F.push(ge)}else if(N){const oe=this.transform.getFrustum(le),ge=d.extendTileCoverToNearPlane(F,oe,le);for(const pe of ge)F.push(pe);if(le>=18&&this._hasTunnelGeometry()){const pe=d.extendTileCoverForTunnels(F,oe,le,20);for(const Ne of pe)F.push(Ne)}}else if(this.castsShadows&&A){const oe=d.extendTileCover(F,le,A,16);for(const ge of oe)this._shadowCasterTiles[ge.key]=!0,F.push(ge)}}const te=this._updateRetainedTiles(F);if(this._supportsFading&&F.length!==0){const ie={},le={},oe=s.o.now(),ge=Object.keys(te);for(const Ne of ge){const Le=te[Ne],xe=this._tiles[Ne];if(!xe||xe.fadeEndTime!==void 0&&xe.fadeEndTime<=oe)continue;const Ze=this.findLoadedParent(Le,Math.max(Le.overscaledZ-lu.maxOverzooming,this._source.minzoom));Ze&&(this._addTile(Ze.tileID),ie[Ze.tileID.key]=Ze.tileID),le[Ne]=Le}const pe=F[F.length-1].overscaledZ;for(const Ne in this._tiles){const Le=this._tiles[Ne];if(te[Ne]||!Le.hasData())continue;let xe=Le.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[Ne]=Le.tileID;break}}}for(const Ne in ie)te[Ne]||(this._coveredTiles[Ne]=!0,te[Ne]=ie[Ne])}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),N=d[0].overscaledZ,L=Math.max(N-lu.maxOverzooming,this._source.minzoom),F=Math.max(N+lu.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 N=A.scaledTo(A.overscaledZ-1);if(w=this._getLoadedTile(N),w)break;A=N}for(const N of g)this._loadedParentTiles[N]=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,N=this._source.tileSize*d.overscaleFactor();g=this._source.type==="raster-array"?new km(d,N,this.transform.tileZoom,A,this._isRaster):new s.b0(d,N,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=[],N=this.transform;if(!N)return A;const L=N.projection.name==="globe",F=s.aH(N.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,...ng(te,-1))-F),Math.abs(s.aC(F,...ng(te,1))-F)];Y=[0,2*ee.indexOf(Math.min(...ee))-1]}else{const ee=[Math.abs(s.aC(F,...ng(te,-1))-F),Math.abs(s.aC(F,...ng(te,0))-F),Math.abs(s.aC(F,...ng(te,1))-F)];Y=[ee.indexOf(Math.min(...ee))-1]}}else Y=[0];for(const te of Y){const ee=d.containsTile(H,N,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(N=>this._tiles[N].tileID),A=this.transform.projection.name==="globe";for(const N of w)N.projMatrix=this.transform.calculateProjMatrix(N.toUnwrapped()),N.expandedProjMatrix=A?this.transform.calculateProjMatrix(N.toUnwrapped(),!1,!0):N.projMatrix;return w}sortCoordinatesByDistance(d){const g=d.slice(),w=this.transform._camera.position,A=this.transform._camera.forward(),N={};for(const L of g){const F=1/(1<N[L.key]-N[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],N=this.map.painter.terrain,L=this.usedForTerrain&&N?N.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 _T(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 ng(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 N=A.layer,L=this.style.getLayerSourceCache(N);let F=1;N.type==="fill-extrusion"?F=A.visible?N.paint.get("fill-extrusion-vertical-scale"):0:N.type==="building"&&(F=A.visible?N.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(N):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 bT(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[N].mult(1-$).add(this.points[g].mult($))}}class wT{constructor(d,g,w){const A=this.boxCells=[],N=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!N&&[];const F=[];if(d<=0&&g<=0&&this.width<=w&&this.height<=A){if(N)return!0;for(let $=0;$0:F}_queryCircle(d,g,w,A,N){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:{}}},N),A?Y.length>0:Y}query(d,g,w,A,N){return this._query(d,g,w,A,!1,N)}hitTest(d,g,w,A,N){return this._query(d,g,w,A,!0,N)}hitTestCircle(d,g,w,A){return this._queryCircle(d,g,w,!0,A)}_queryCell(d,g,w,A,N,L,F,$){const H=F.seenUids,Y=this.boxCells[N];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[N];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],ge=ee[le+1],pe=ee[le+2];L.push({key:this.circleKeys[ie],x1:oe-pe,y1:ge-pe,x2:oe+pe,y2:ge+pe})}}}}}_queryCellCircle(d,g,w,A,N,L,F,$){const H=F.circle,Y=F.seenUids,te=this.boxCells[N];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[N];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,N,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(N.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,N,L){const F=A-d,$=N-g,H=w+L;return H*H>F*F+$*$}_circleAndRectCollide(d,g,w,A,N,L,F){const $=(L-A)/2,H=Math.abs(d-(A+$));if(H>$+w)return!1;const Y=(F-N)/2,te=Math.abs(g-(N+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 QF=Math.tan(85*Math.PI/180);function mf(v,d,g,w,A,N,L){const F=s.bb();if(g)if(N.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 Ou(v,d,g,w,A,N,L){const F=mf(v,d,g,w,A,N,L);return N.name==="globe"&&g||(F[2]=F[6]=F[10]=F[14]=0),F}function og(v,d,g,w,A,N,L){if(g){if(N.name==="globe"){const F=mf(v,d,g,w,A,N,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 cu(v,d,g,w){const A=[v,d,g,1];g?s.aE(A,A,w):Xr(A,A,w);const N=A[3];return A[0]/=N,A[1]/=N,A[2]/=N,A}function vv(v,d){return Math.min(.5+v/d*.5,1.5)}function Mx(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 lc(v,d,g,w,A,N,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],ge=w?v.text.dynamicLayoutVertexArray:v.icon.dynamicLayoutVertexArray;ge.clear();let pe=null;le&&(pe=w?v.text.globeExtVertexArray:v.icon.globeExtVertexArray);const Ne=v.lineVertexArray,Le=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,N){return A===0||Math.abs(N/A)>QF}(g,w)?d===1?{needsFlipping:!0}:null:g<0?{needsFlipping:!0}:null}function TT(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne,Le){const xe=d/24,Ze=v.lineOffsetX*xe,ze=v.lineOffsetY*xe,{lineStartIndex:Ke,glyphStartIndex:De,numGlyphs:Be,segment:qe,writingMode:st,flipState:Qe}=v,xt=Ke+v.lineLength,ft=Rt=>{if(Y){const[gt,bt,St]=Rt.up,rr=H.length;s.bm(Y,rr+0,gt,bt,St),s.bm(Y,rr+1,gt,bt,St),s.bm(Y,rr+2,gt,bt,St),s.bm(Y,rr+3,gt,bt,St)}const[Ft,ot,et]=Rt.point;s.bn(H,Ft,ot,et,Rt.angle)};if(Be>1){const Rt=ST(xe,F,Ze,ze,g,te,ee,v,$,N,ie,oe,!1,ge,pe,Ne,Le);if(!Rt)return{notEnoughRoom:!0};if(w&&!g){let[Ft,ot,et]=Rt.first.point,[gt,bt,St]=Rt.last.point;[Ft,ot]=cu(Ft,ot,et,L),[gt,bt]=cu(gt,bt,St,L);const rr=bv(st,Qe,(gt-Ft)*le,bt-ot);if(v.flipState=rr&&rr.needsFlipping?1:2,rr)return rr}ft(Rt.first);for(let Ft=De+1;Ft0?gt:ET(ee,et,Ft,1,A,void 0,ge,pe.canonical),St=bv(st,Qe,(bt[0]-Ft[0])*le,bt[1]-Ft[1]);if(v.flipState=St&&St.needsFlipping?1:2,St)return St}const Rt=wv(xe*F.getoffsetX(De),Ze,ze,g,te,ee,qe,Ke,xt,$,N,ie,oe,!1,!1,ge,pe,Ne,Le);if(!Rt)return{notEnoughRoom:!0};ft(Rt)}return{}}function Zn(v,d,g,w,A){const{x:N,y:L,z:F}=w.projectTilePoint(v.x,v.y,d);if(!A)return cu(N,L,F,g);const[$,H,Y]=A.getElevation(v,A.elevation,A.elevationFeature);return cu(N+$,L+H,F+Y,g)}function ET(v,d,g,w,A,N,L,F){const $=Zn(v.sub(d)._unit()._add(v),F,A,L,N);return s.ax($,g,$),s.ay($,$),s.bg($,g,$,w)}function wv(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne){const Le=w?v-d:v+d;let xe=Le>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,Be=0,qe=0;const st=Math.abs(Le),Qe=[],xt=[];let ft=N,Rt=ft,Ft=s.be([]);const ot=()=>ET(Rt,ft,De,st-Be+1,Y,ee,oe,ge.canonical);for(;Be+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=Zn(ft,ge.canonical,Y,oe,ee);Ke=Lr[3]>0?te[ze]=Lr:ot()}Be+=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,Le),Ke=H*ze.perspectiveRatio,De=(w.x1*g+F.x-w.padding)*Ke+ze.point.x,Be=(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,Be,qe,st)||!$&&this.grid.hitTest(De,Be,qe,st,te)||Qe?{box:[],offscreen:!1,occluded:ze.occluded}:{box:[De,Be,qe,st],offscreen:this.isOffscreen(De,Be,qe,st),occluded:!1}}placeCollisionCircles(d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge){const pe=[],Ne=this.transform.elevation,Le=d.getProjection(),xe=d.elevationType==="road",Ze=!!Ne||xe,ze=s.bu.getAtTileOffsetFunc(ge,this.transform.center.lat,this.transform.worldSize,Le),Ke=new s.P(w.tileAnchorX,w.tileAnchorY),De=new s.P(w.tileAnchorX,w.tileAnchorY);let{x:Be,y:qe,z:st}=Le.projectTilePoint(De.x,De.y,ge.canonical),Qe=null;if(Ze){const Ar=xe?d.getElevationFeatureForText(A):null;Qe={getElevation:ze,elevation:Ne,elevationFeature:Ar};const[Lr,yr,Tr]=ze(Ke,Ne,Ar);Be+=Lr,qe+=yr,st+=Tr}const xt=Le.name==="globe",ft=this.projectAndGetPerspectiveRatio($,Be,qe,st,ge,xt||!!Ne||this.transform.pitch>0,Le),{perspectiveRatio:Rt}=ft,Ft=(ee?F/Rt:F*Rt)/s.by,ot=cu(Be,qe,st,H),et=w.lineOffsetX*Ft,gt=w.lineOffsetY*Ft,bt=s.ap(d.layers[0].layout.get("text-max-angle")),St=Math.cos(bt),rr=ft.signedDistanceFromCamera>0?ST(Ft,L,et,gt,xe&&w.flipState===1,ot,De,w,N,H,{},Ze&&!ee?Qe:null,ee&&Ze,Le,ge,ee,St):null;let Ht=!1,Wt=!1,Dt=!0;if(rr&&!ft.occluded){const Ar=.5*le*Rt+oe,Lr=new s.P(-100,-100),yr=new s.P(this.screenRightBoundary,this.screenBottomBoundary),Tr=new GC,{first:Hr,last:sn}=rr,en=Hr.path.length;let bn=[];for(let tn=en-1;tn>=1;tn--)bn.push(Hr.path[tn]);for(let tn=1;tn(Ze&&!xt&&(bi=ze(Zitn[3]<=0)&&(bn=[]));let wn=[];if(bn.length>0){let tn=1/0,qn=-1/0,bi=1/0,Zi=-1/0;for(const ki of bn)tn=Math.min(tn,ki[0]),bi=Math.min(bi,ki[1]),qn=Math.max(qn,ki[0]),Zi=Math.max(Zi,ki[1]);qn>=Lr.x&&tn<=yr.x&&Zi>=Lr.y&&bi<=yr.y&&(wn=[bn.map(ki=>new s.P(ki[0],ki[1]))],(tnyr.x||biyr.y)&&(wn=s.bv(wn,Lr.x,Lr.y,yr.x,yr.y)))}for(const tn of wn){Tr.reset(tn,.25*Ar);let qn=0;qn=Tr.length<=.5*Ar?1:Math.ceil(Tr.paddedLength/Ur)+1;for(let bi=0;bi0?(s.aE($,$,d),this.fogState&&N&&F.name!=="globe"&&(H=function(ee,ie,le,oe,ge,pe){const Ne=pe.calculateFogTileMatrix(ge),Le=[ie,le,oe];return s.ah(Le,Le,Ne),Pi(ee,s.ai(Le),pe.pitch,pe._fov)}(this.fogState,g,w,A,N.toUnwrapped(),this.transform)>.9)):Xr($,$,d);const Y=$[3];return{point:new s.P(($[0]/Y+1)/2*this.transform.width+Fu,(-$[1]/Y+1)/2*this.transform.height+Fu),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 _l(v,d,g,w,A){const{horizontalAlign:N,verticalAlign:L}=s.bF(v),F=-(N-.5)*d,$=-(L-.5)*g,H=s.bG(v,w);return new s.P(F+H[0]*A,$+H[1]*A)}function pf(v,d,g,w,A){const N=new s.P(v,d);return g&&N._rotate(w?A:-A),N}class pi{constructor(d,g,w,A,N,L){this.transform=d.clone(),this.projection=d.projection.name,this.collisionIndex=new Sv(this.transform,N),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 mi(w),this.collisionCircleArrays={},this.prevPlacement=A,A&&(A.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(d,g,w,A,N=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,ge=L.getProjection(),pe=this.transform,ge.name===this.projection?pe.calculateProjMatrix(oe.toUnwrapped()):_v(pe,ge,oe));var oe,ge,pe;const Ne=$.get("text-pitch-alignment")==="map",Le=$.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=Ou(le,w.tileID.canonical,Ne,Le,this.transform,L.getProjection(),Ke);let Be=null;const qe=L.getProjection().createInversionMatrix(this.transform,w.tileID.canonical);if(Ne){const gt=og(le,w.tileID.canonical,Ne,Le,this.transform,L.getProjection(),Ke);Be=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 di(L.bucketInstanceId,F,L.sourceLayerIndex,L.index,w.tileID);const[Qe,xt]=L.layers[0].layout.get("text-size-scale-range"),ft=s.aC(N,Qe,xt),[Rt,Ft]=$.get("icon-size-scale-range"),ot=s.aC(N,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:Be,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:bt,symbolInstanceStart:St,symbolInstanceEnd:rr}=gt;d.push({sortKey:bt,symbolInstanceStart:St,symbolInstanceEnd:rr,parameters:et})}else d.push({symbolInstanceStart:0,symbolInstanceEnd:L.symbolInstances.length,parameters:et})}attemptAnchorPlacement(d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne,Le,xe,Ze){const{textOffset0:ze,textOffset1:Ke,crossTileID:De}=oe,Be=[ze,Ke],qe=_l(d,L,F,Be,$),st=this.collisionIndex.placeCollisionBox(pe,$,g,w,A,N,pf(qe.x,qe.y,H,Y,this.transform.angle),le,te,ee,ie.predicate);if(Le){const Qe=pe.getSymbolInstanceIconSize(Ze,this.transform.zoom,oe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(pe,Qe,Le,w,A,N,pf(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:Be,width:L,height:F,anchor:d,textScale:$,prevAnchor:Qe},this.markUsedJustification(pe,d,oe,Ne),pe.allowVerticalPlacement&&(this.markUsedOrientation(pe,Ne,oe),this.placedOrientations[De]=Ne),{shift:qe,placedGlyphBoxes:st}}}placeLayerBucketPart(d,g,w,A,N=1){const{bucket:L,layout:F,paint:$,posMatrix:H,textLabelPlaneMatrix:Y,labelToScreenMatrix:te,clippingData:ee,textPixelRatio:ie,mercatorCenter:le,invMatrix:oe,holdingForFade:ge,collisionBoxArray:pe,partiallyEvaluatedTextSize:Ne,partiallyEvaluatedIconSize:Le,collisionGroup:xe,latestFeatureIndex:Ze}=d.parameters,ze=F.get("text-optional"),Ke=F.get("icon-optional"),De=F.get("text-allow-overlap"),Be=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"),bt=s.aC(N,Ft,ot),St=s.aC(N,et,gt),rr=F.get("text-variable-anchor"),Ht=qe&&Rt!=="point",Wt=st&&Rt!=="point",Dt=rr&&L.hasTextData(),Ar=L.hasIconTextFit()&&Dt&&L.hasIconData();this.transform.setProjection(L.projection);const Lr=Dt||Ht,yr=Wt||Ar;let Tr=De&&(Be||!L.hasIconData()||Ke),Hr=Be&&(De||!L.hasTextData()||ze);const sn=!xt.isConstant();!L.collisionArrays&&pe&&L.deserializeCollisionBoxes(pe),w&&A&&L.updateCollisionDebugBuffers(this.transform.zoom,pe,bt,St);const en=(Ur,wn,tn)=>{const{crossTileID:qn,numVerticalGlyphVertices:bi}=Ur;let Zi=null;if(ee&&ee.dynamicFilterNeedsFeature||sn){const Li=this.retainedQueryData[L.bucketInstanceId],$i=Ze.loadFeature({featureIndex:Ur.featureIndex,bucketIndex:Li.bucketIndex,sourceLayerIndex:Li.sourceLayerIndex,layoutVertexArrayOffset:0}),gi=$i.properties?$i.properties.worldview:null;if(L.localizable&&L.worldview&&typeof gi=="string")if(gi==="all")$i.properties.$localized=!0;else{if(!gi.split(",").includes(L.worldview))return;$i.properties.$localized=!0,$i.properties.worldview=L.worldview}Zi=ee&&ee.needGeometry?s.bD($i,!0):$i}if(ee&&!(0,ee.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:L.worldview},Zi,this.retainedQueryData[L.bucketInstanceId].tileID.canonical,new s.P(Ur.tileAnchorX,Ur.tileAnchorY),this.transform.calculateDistanceTileData(ee.unwrappedTileID)))return this.placements[qn]=new fh(!1,!1,!1,!0),void g.add(qn);const ki=xt.evaluate(Zi,{});if((Ur.zOffset||0)+(ki||0)>0&&this.frontCutoffStart>0){const Li=2*this.frontCutoffStart-1,$i=[Ur.tileAnchorX,Ur.tileAnchorY,0,1],gi=s.aE(s.bE(),$i,H);if(gi[1]/gi[3]{Li.tileID=this.retainedQueryData[L.bucketInstanceId].tileID;const $i=this.transform.elevation;Li.elevation=ft?ki:ki+s.bu.getAtTileOffset(Li.tileID,new s.P(Li.tileAnchorX,Li.tileAnchorY),$i,ha),Li.elevation+=Ur.zOffset},dc=tn.textBox;if(dc){qa(dc);const Li=gi=>{let Is=s.bk.horizontal;if(L.allowVerticalPlacement&&!gi&&this.prevPlacement){const Mo=this.prevPlacement.placedOrientations[qn];Mo&&(this.placedOrientations[qn]=Mo,Is=Mo,this.markUsedOrientation(L,Is,Ur))}return Is},$i=(gi,Is)=>{if(L.allowVerticalPlacement&&bi>0&&tn.verticalTextBox){for(const Mo of L.writingModes)if(Mo===s.bk.vertical?(on=Is(),Ki=on):on=gi(),on&&on.box&&on.box.length)break}else on=gi()};if(rr){let gi=rr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[qn]){const hs=this.prevPlacement.variableOffsets[qn];gi.indexOf(hs.anchor)>0&&(gi=gi.filter(hc=>hc!==hs.anchor),gi.unshift(hs.anchor))}const Is=(hs,hc,Tf)=>{const Km=L.getSymbolInstanceTextSize(Ne,Ur,this.transform.zoom,wn),Ym=(hs.x2-hs.x1)*Km+2*hs.padding,Cg=(hs.y2-hs.y1)*Km+2*hs.padding,wh=Ur.hasIconTextFit&&!Be?hc:null;wh&&qa(wh);let Pd={box:[],offscreen:!1,occluded:!1};const Ig=De?2*gi.length:gi.length;for(let Bl=0;Bl=gi.length,Ur,wn,L,Tf,wh,Ne,Le);if(Ef&&(Pd=Ef.placedGlyphBoxes,Pd&&Pd.box&&Pd.box.length)){Jn=!0,ei=Ef.shift;break}}return Pd};$i(()=>Is(dc,tn.iconBox,s.bk.horizontal),()=>{const hs=tn.verticalTextBox;return hs&&qa(hs),L.allowVerticalPlacement&&!(on&&on.box&&on.box.length)&&bi>0&&hs?Is(hs,tn.verticalIconBox,s.bk.vertical):{box:null,offscreen:null,occluded:null}}),on&&(Jn=on.box,yn=on.offscreen,Ci=on.occluded);const Mo=Li(!(!on||!on.box));if(!Jn&&this.prevPlacement){const hs=this.prevPlacement.variableOffsets[qn];hs&&(this.variableOffsets[qn]=hs,this.markUsedJustification(L,hs.anchor,Ur,Mo))}}else{const gi=(Is,Mo)=>{const hs=L.getSymbolInstanceTextSize(Ne,Ur,this.transform.zoom,wn),hc=this.collisionIndex.placeCollisionBox(L,hs,Is,le,oe,Lr,new s.P(0,0),De,ie,H,xe.predicate);return hc&&hc.box&&hc.box.length&&(this.markUsedOrientation(L,Mo,Ur),this.placedOrientations[qn]=Mo),hc};$i(()=>gi(dc,s.bk.horizontal),()=>{const Is=tn.verticalTextBox;return L.allowVerticalPlacement&&bi>0&&Is?(qa(Is),gi(Is,s.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Li(!!(on&&on.box&&on.box.length))}}if(wi=on,Jn=wi&&wi.box&&wi.box.length>0,yn=wi&&wi.offscreen,Ci=wi&&wi.occluded,Ur.useRuntimeCollisionCircles){const Li=Ur.centerJustifiedTextSymbolIndex>=0?Ur.centerJustifiedTextSymbolIndex:Ur.verticalPlacedTextSymbolIndex,$i=L.text.placedSymbolArray.get(Li),gi=s.bl(L.textSizeData,Ne,$i),Is=F.get("text-padding");Os=this.collisionIndex.placeCollisionCircles(L,De,$i,Li,L.lineVertexArray,L.glyphOffsetArray,gi,H,Y,te,w,Qe,xe.predicate,Ur.collisionCircleDiameter*gi/s.by,Is,this.retainedQueryData[L.bucketInstanceId].tileID),Jn=De||Os.circles.length>0&&!Os.collisionDetected,yn=yn&&Os.offscreen,Ci=Os.occluded}if(tn.iconFeatureIndex&&(wo=tn.iconFeatureIndex),tn.iconBox){const Li=$i=>{qa($i);const gi=Ur.hasIconTextFit&&ei?pf(ei.x,ei.y,qe,Qe,this.transform.angle):new s.P(0,0),Is=L.getSymbolInstanceIconSize(Le,this.transform.zoom,Ur.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(L,Is,$i,le,oe,yr,gi,Be,ie,H,xe.predicate)};Ki&&Ki.box&&Ki.box.length&&tn.verticalIconBox?(In=Li(tn.verticalIconBox),gn=In.box.length>0):(In=Li(tn.iconBox),gn=In.box.length>0),yn=yn&&In.offscreen,ns=In.occluded}const oi=ze||Ur.numHorizontalGlyphVertices===0&&bi===0,Ic=Ke||Ur.numIconVertices===0;if(oi||Ic?Ic?oi||(gn=gn&&Jn):Jn=gn&&Jn:gn=Jn=gn&&Jn,Jn&&wi&&wi.box&&this.collisionIndex.insertCollisionBox(wi.box,F.get("text-ignore-placement"),L.bucketInstanceId,Ki&&Ki.box&&Js?Js:Ai,xe.ID),gn&&In&&this.collisionIndex.insertCollisionBox(In.box,F.get("icon-ignore-placement"),L.bucketInstanceId,wo,xe.ID),Os&&(Jn&&this.collisionIndex.insertCollisionCircles(Os.circles,F.get("text-ignore-placement"),L.bucketInstanceId,Ai,xe.ID),w)){const Li=L.bucketInstanceId;let $i=this.collisionCircleArrays[Li];$i===void 0&&($i=this.collisionCircleArrays[Li]=new Dr);for(let gi=0;gi=0;--wn){const tn=Ur[wn];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 Ur=L.getSortedIndexesByZOffset();for(let wn=0;wn=0&&(d.text.placedSymbolArray.get(N).crossTileID=te>=0&&N!==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,N=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=N)}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,N=g?g.opacities:{},L=g?g.variableOffsets:{},F=g?g.placedOrientations:{};for(const $ in this.placements){const H=this.placements[$],Y=N[$];Y?(this.opacities[$]=new Im(Y,A,H.text,H.icon,null,H.clipped),w=w||H.text!==Y.text.placed||H.icon!==Y.icon.placed):(this.opacities[$]=new Im(null,A,H.text,H.icon,H.skipFade,H.clipped),w=w||H.text||H.icon)}for(const $ in N){const H=N[$];if(!this.opacities[$]){const Y=new Im(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 N=new Set;for(const L of g){const F=L.getBucket(d);F&&L.latestFeatureIndex&&d.fqid===F.layerIds[0]&&(this.updateBucketOpacities(F,N,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,N,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 Im(null,0,!1,!1,!0),ie=H.get("text-allow-overlap"),le=H.get("icon-allow-overlap"),oe=H.get("text-variable-anchor"),ge=H.get("text-rotation-alignment")==="map",pe=H.get("text-pitch-alignment")==="map",Ne=Y.get("symbol-z-offset"),Le=H.get("symbol-elevation-reference")==="sea",xe=!Ne.isConstant(),Ze=new Im(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,Be,qe)=>{for(let st=0;st0||st>0,rr=xt>0,Ht=this.placedOrientations[Qe],Wt=Ht===s.bk.vertical,Dt=Ht===s.bk.horizontal||Ht===s.bk.horizontalOnly;!St&&!rr||bt.isHidden()||Ke++;let Ar=!1;if((St||rr)&&L)for(const Lr of d.activeReplacements){if(s.bz(Lr,N,s.bA.Symbol,$)||Lr.min.x>ft||ft>Lr.max.x||Lr.min.y>Rt||Rt>Lr.max.y)continue;const yr=s.bB(ft,Rt,F.canonical,Lr.footprintTileId.canonical);if(Ar=s.bC(yr,Lr.footprint),Ar)break}if(Ar&&this.collisionIndex.markSymbolAsClipped(d.bucketInstanceId,Be.featureIndex),St){const Lr=Ar?mh:cg(bt.text);ze(d.text,qe,Wt?mh:Lr),ze(d.text,st,Dt?mh:Lr);const yr=bt.text.isHidden(),{leftJustifiedTextSymbolIndex:Tr,centerJustifiedTextSymbolIndex:Hr,rightJustifiedTextSymbolIndex:sn,verticalPlacedTextSymbolIndex:en}=Be,bn=d.text.placedSymbolArray,Ur=yr||Wt?1:0;Tr>=0&&(bn.get(Tr).hidden=Ur),Hr>=0&&(bn.get(Hr).hidden=Ur),sn>=0&&(bn.get(sn).hidden=Ur),en>=0&&(bn.get(en).hidden=yr||Dt?1:0);const wn=this.variableOffsets[Qe];wn&&this.markUsedJustification(d,wn.anchor,Be,Ht);const tn=this.placedOrientations[Qe];tn&&(this.markUsedJustification(d,"left",Be,tn),this.markUsedOrientation(d,tn,Be))}if(rr){const Lr=Ar?mh:cg(bt.icon),{placedIconSymbolIndex:yr,verticalPlacedIconSymbolIndex:Tr}=Be,Hr=d.icon.placedSymbolArray,sn=bt.icon.isHidden()?1:0;yr>=0&&(ze(d.icon,xt,Wt?mh:Lr),Hr.get(yr).hidden=sn),Tr>=0&&(ze(d.icon,Be.numVerticalIconVertices,Dt?mh:Lr),Hr.get(Tr).hidden=sn)}if(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData()){const Lr=d.collisionArrays[De];if(Lr){let yr=new s.P(0,0),Tr=!0;if(Lr.textBox||Lr.verticalTextBox){if(oe){const sn=this.variableOffsets[Qe];sn?(yr=_l(sn.anchor,sn.width,sn.height,sn.textOffset,sn.textScale),ge&&yr._rotate(pe?this.transform.angle:-this.transform.angle)):Tr=!1}te&&(Tr=!bt.clipped),Lr.textBox&&Nm(d.textCollisionBox.collisionVertexArray,bt.text.placed,!Tr||Wt,et,Le,yr.x,yr.y),Lr.verticalTextBox&&Nm(d.textCollisionBox.collisionVertexArray,bt.text.placed,!Tr||Dt,et,Le,yr.x,yr.y)}const Hr=Tr&&!!(!Dt&&Lr.verticalIconBox);Lr.iconBox&&Nm(d.iconCollisionBox.collisionVertexArray,bt.icon.placed,Hr,et,Le,Be.hasIconTextFit?yr.x:0,Be.hasIconTextFit?yr.y:0),Lr.verticalIconBox&&Nm(d.iconCollisionBox.collisionVertexArray,bt.icon.placed,!Hr,et,Le,Be.hasIconTextFit?yr.x:0,Be.hasIconTextFit?yr.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 Nm(v,d,g,w,A,N,L){v.emplaceBack(d?1:0,g?1:0,N||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,N||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,N||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,N||0,L||0,w,A?1:0)}const Ox=Math.pow(2,25),Fx=Math.pow(2,24),Xo=Math.pow(2,17),ua=Math.pow(2,16),JF=Math.pow(2,9),Bx=Math.pow(2,8),AT=Math.pow(2,1);function cg(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*Ox+d*Fx+g*Xo+d*ua+g*JF+d*Bx+g*AT+d}const mh=0;class jT{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,N,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"),ge=le&&oe,pe=this._inProgressLayer=this._inProgressLayer||new jT(Y),Ne=s.F($.source,$.scope);if(pe.continuePlacement(te||ge?A[Ne]:w[Ne],this.placement,this._showCollisionBoxes,$,F,N))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(d){return this.placement.commit(d),this.placement}}const Lo=512/s.an/2;class du{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,N=d.canonical.y*s.an;for(let L=0;Lge-pe);for(const ge of oe){const pe=this.crossTileIDs[ge];if(this.keys[ge]===Y&&!w.has(pe)){w.add(pe),H.crossTileID=pe;break}}}}}class Fl{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class HC{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],N={};for(const L in A){const F=A[L];F.tileID=F.tileID.unwrapTo(F.tileID.wrap+g),N[F.tileID.key]=F}this.indexes[w]=N}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 N=0;Nd.overscaledZ)for(const F in L){const $=L[F];$.tileID.isChildOf(d)&&$.findMatches(g.symbolInstances,d,A)}else{const F=L[d.scaledTo(Number(N)).key];F&&F.findMatches(g.symbolInstances,d,A)}}for(let N=0;N{g[w]=!0});for(const w in this.layerIndexes)g[w]||delete this.layerIndexes[w]}}const Cs=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,Cs,1,Cs],s.aq.transparent,[!0,!0,!0,!0]),Kr.alphaBlendedNonPremultiplied=new Kr([770,Cs,770,Cs],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,Cs],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 Qs=7680;class Qr{constructor(d,g,w,A,N,L){this.test=d,this.ref=g,this.mask=w,this.fail=A,this.depthFail=N,this.pass=L}}Qr.disabled=new Qr({func:519,mask:0},0,0,Qs,Qs,Qs);const Ec=1029,Pm=2305;class Gr{constructor(d,g,w){this.enable=d,this.mode=g,this.frontFace=w}}function $x(v,d){const g=s.bO(v,3);s.bR(v,d),s.bW(v,3,g)}function Tv(v,d){const g=s.bL([]);return s.bM(g,g,-d),s.bN(g,g,-v),g}function Ev(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 N=Math.atan2(-A[1],A[0]);return Tv(Math.atan2(Math.sqrt(v[0]*v[0]+v[1]*v[1]),-v[2]),N)}Gr.disabled=new Gr(!1,Ec,Pm),Gr.backCCW=new Gr(!0,Ec,Pm),Gr.backCW=new Gr(!0,Ec,2304),Gr.frontCW=new Gr(!0,1028,2304),Gr.frontCCW=new Gr(!0,1028,Pm);class Ux{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,N=w||(this._elevation?this._elevation.getAtPointOrZero(s.ag.fromLngLat(d)):0),L=s.ag.fromLngLat(d,N),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=Ev(F,g)}setPitchBearing(d,g){this.orientation=Tv(s.ap(d),s.ap(-g))}}class Vx{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&&$x(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=Tv(d,g),$x(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 N=new Float64Array(16);return s.bP(N,[w,w,w]),s.bx(N,N,A),N[10]*=g,N}getWorldToCamera(d,g){const w=new Float64Array(16),A=new Float64Array(4),N=this.position;return s.bQ(A,this._orientation),s.bJ(N,N,-d),s.bR(w,A),s.bx(w,w,N),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 N=new Float64Array(16);return s.bS(N,d,g,w,A),N}getCameraToClipOrthographic(d,g,w,A,N,L){const F=new Float64Array(16);return s.bT(F,d,g,w,A,N,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 Vx([...this.position],[...this.orientation])}}const e5=(v,d)=>({u_matrix:v,u_ground_shadow_factor:d});class Bu{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 Bu(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Rm=15;class qx{constructor(d,g,w,A,N,L,F){this.tileSize=512,this._renderWorldCopies=N===void 0||N,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 Bu,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Vx,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 qx(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,N=0;for(let L=0;L{const ge=s.ck(ee,te,ie,le,oe);$.has(ge)||(N.push(new s.aR(te,ee,ie,le,oe)),$.add(ge))};for(let te=0;teee.canonical.z)continue;const ie=ee.canonical,le=ee.overscaledZ,oe=ee.wrap,ge=1<0,Le=ie.y+10,Ze=ee.wrap-(Ne?0:1),ze=ee.wrap+(pe?0:1),Ke=Ne?ie.x-1:ge-1,De=pe?ie.x+1:0;if(L)w[0]<0?(H(le,ze,ie.z,De,ie.y),w[1]<0&&Le&&(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&&Le&&(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&&Le?H(le,oe,ie.z,ie.x,ie.y+1):xe&&H(le,oe,ie.z,ie.x,ie.y-1);else{const Be=ee.visibleQuadrants;1&Be&&(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&Be&&(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&Be&&(H(le,Ze,ie.z,Ke,ie.y),Le&&(H(le,oe,ie.z,ie.x,ie.y+1),H(le,Ze,ie.z,Ke,ie.y+1))),8&Be&&(H(le,ze,ie.z,De,ie.y),Le&&(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 N)N.some(ee=>te.isChildOf(ee))||Y.push(te);if(N=Y.filter(te=>!d.some(ee=>!!(te.overscaledZ{const pe=ge.canonical.x+.5-ie[0],Ne=ge.canonical.y+.5-ie[1];return pe*pe+Ne*Ne{const Ke=s.ck(Le,Ne,xe,Ze,ze);N.has(Ke)||(A.push(new s.aR(Ne,Le,xe,Ze,ze)),N.add(Ke))},F=d.reduce((Ne,Le)=>Math.max(Ne,Le.overscaledZ),w),$=1<{const xe=Math.floor(Ne[0]),Ze=Math.floor(Ne[1]),ze=(Ne[0]-xe)*s.an,Ke=(Ne[1]-Ze)*s.an,De=Math.floor(Le[0]),Be=Math.floor(Le[1]),qe=(Le[0]-De)*s.an,st=(Le[1]-Be)*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-Be)*s.an,s.cI(Y,te,H)&&L(F,0,w,xt,Rt)}}}},ie=g.points,le=ie[s.c9],oe=ie[s.ca],ge=this._projectToGround(le,ie[s.cb]),pe=this._projectToGround(oe,ie[s.cc]);return ee(le,ge),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 N=g.points,L=N[s.cg],F=N[s.ch],$=N[s.ci],H=N[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 N=[],L=new Set;for(const De of d)L.add(De.key);const F=d.reduce((De,Be)=>Math.max(De,Be.overscaledZ),g),$=1<{const qe=De.canonical.x+.5-ze,st=De.canonical.y+.5-Ke,Qe=Be.canonical.x+.5-ze,xt=Be.canonical.y+.5-Ke;return qe*qe+st*st-(Qe*Qe+xt*xt)||De.canonical.x-Be.canonical.x||De.canonical.y-Be.canonical.y}),N}coveringTiles(d){let g=this.coveringZoomLevel(d);const w=g,A=this.elevation&&this.elevation.exaggeration(),N=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 bt=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(),Ht=bt.toLngLat(),Wt=St.toLngLat(),Dt=this.locationCoordinate(rr),Ar=this.locationCoordinate(Ht),Lr=this.locationCoordinate(Wt),yr=Math.hypot(Ar.x-Dt.x,Ar.y-Dt.y),Tr=Math.hypot(Lr.x-Dt.x,Lr.y-Dt.y);return Math.sqrt(yr*Tr)*Ke/25e-6},Be=et=>{const gt=Ze,bt=ze;return{aabb:s.cp(this,H,0,0,0,et,bt,gt,this.projection),zoom:0,x:0,y:0,minZ:bt,maxZ:gt,wrap:et,fullyVisible:!1}},qe=[];let st=[];const Qe=g,xt=d.reparseOverscaled?w:g,ft=(ge-this._centerAltitude)*oe,Rt=et=>{if(!this._elevation||!et.tileID||!L)return;const gt=this._elevation.getMinMaxForTile(et.tileID),bt=et.aabb;gt?(bt.min[2]=gt.min,bt.max[2]=gt.max,bt.center[2]=(bt.min[2]+bt.max[2])/2):(et.shouldSplit=ot(et),et.shouldSplit||(bt.min[2]=bt.max[2]=bt.center[2]=this._centerAltitude))},Ft=(et,gt)=>{if(.707*gt{if(et.zoom=.9)return!0}else if(N&&(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+bt*bt+St*St);let Hr=(1<0;){const et=qe.pop(),gt=et.x,bt=et.y;let St=et.fullyVisible;const rr=()=>this.projection.name==="globe"&&(et.y===0||et.y===(1<Ht)continue;let Wt=0;if(!St){let yr=Ne?et.aabb.intersectsPrecise(ie):et.aabb.intersectsPreciseFlat(ie);if(yr===0&&rr()){const Tr=new s.cn(et.zoom,gt,bt);yr=s.co(this,H,Tr,!0).intersectsPrecise(ie)}if(yr===0)continue;if(d.calculateQuadrantVisibility)if(ie.containsPoint(et.aabb.center))Wt=15;else for(let Tr=0;Tr<4;Tr++)et.aabb.quadrant(Tr).intersects(ie)!==0&&(Wt|=1<>1),Ar={aabb:L?et.aabb.quadrant(Ht):s.cp(this,H,et.zoom+1,Wt,Dt,et.wrap,et.minZ,et.maxZ,this.projection),zoom:et.zoom+1,x:Wt,y:Dt,wrap:et.wrap,fullyVisible:St,tileID:void 0,shouldSplit:void 0,minZ:et.minZ,maxZ:et.maxZ};N&&!te&&(Ar.tileID=new s.aR(et.zoom+1===Qe?xt:et.zoom+1,et.wrap,et.zoom+1,Wt,Dt),Rt(Ar)),qe.push(Ar)}}if(this.fogCullDistSq){const et=this.fogCullDistSq,gt=this.horizonLineFromTop();st=st.filter(bt=>{const St=[0,0,0,1],rr=[s.an,s.an,0,1],Ht=this.calculateFogTileMatrix(bt.tileID.toUnwrapped());s.aE(St,St,Ht),s.aE(rr,rr,Ht);const Wt=s.cq([],St,rr),Dt=s.cr([],St,rr),Ar=s.cK(Wt,Dt);if(Ar===0)return!0;let Lr=!1;const yr=this._elevation;if(yr&&Ar>et&>!==0){const Tr=this.calculateProjMatrix(bt.tileID.toUnwrapped());let Hr;d.isTerrainDEM||(Hr=yr.getMinMaxForTile(bt.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 N=this.centerPoint;if(this.projection.name==="globe"){const F=this.worldSize;w=(g.x-N.x)/F,A=(g.y-N.y)/F}else{const F=this.pointCoordinate(g),$=this.pointCoordinate(N);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],N=[d.x,d.y,1,1];s.aE(A,A,this.pixelMatrixInverse),s.aE(N,N,this.pixelMatrixInverse);const L=N[3];s.cu(A,A,1/A[3]),s.cu(N,N,1/L);const F=A[2],$=N[2];return{p0:A,p1:N,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,N=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(N,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,N=this.horizonLineFromTop();if(d.y>N)return this.pointCoordinate(d,g);const L=.02*N,F=d.clone();for(let $=0;$<10&&N-A>L;$++){F.y=s.am(A,N,.66);const H=this.projection.pointCoordinate3D(this,F.x,F.y);H?(N=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,N=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(N.lng,L.lng,F.lng,$.lng),Y=Math.max(N.lng,L.lng,F.lng,$.lng),te=Math.min(N.lat,L.lat,F.lat,$.lat),ee=Math.max(N.lat,L.lat,F.lat,$.lat);const ie=Math.pow(2,-this.zoom)/16*270,le=this.projection.name==="globe"?1:4,oe=(ge,pe,Ne,Le,xe)=>{const Ze=(ge+Ne)/2,ze=(pe+Le)/2,Ke=new s.P(Ze,ze),{lng:De,lat:Be}=this.pointLocation3D(Ke),qe=Math.max(0,H-De,te-Be,De-Y,Be-ee);H=Math.min(H,De),Y=Math.max(Y,De),te=Math.min(te,Be),ee=Math.max(ee,Be),(xeie)&&(oe(ge,pe,Ze,ze,xe+1),oe(Ze,ze,Ne,Le,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[ge,pe]=s.cw(this);ge?(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,N=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,N),Y=new s.P(A,N);let te=this.pointCoordinate(F,d),ee=this.pointCoordinate($,d);const ie=this.pointCoordinate(H,g),le=this.pointCoordinate(Y,g),oe=(ge,pe)=>(pe.y-ge.y)/(pe.x-ge.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 N=A.dem.tree;w.min=Math.min(w.min,N.minimums[0]),w.max=Math.max(w.max,N.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>=Rm?1:this.pitch/Rm))}else F=$;const H=s.cz([],$,L);let Y=s.cz([],F,L);if(this.projection.isReprojectedInTileSpace){const Be=this.locationCoordinate(this.center),qe=s.b9([]);s.bx(qe,qe,[Be.x*this.worldSize,Be.y*this.worldSize,0]),s.aD(qe,qe,s.cA(this)),s.bx(qe,qe,[-Be.x*this.worldSize,-Be.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/N,1]),this.projMatrix=Y,this.invProjMatrix=s.b7(new Float64Array(16),this.projMatrix),g){const Be=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Be[8]=2*-d.x/this.width,Be[9]=2*d.y/this.height,this.expandedFarZProjMatrix=s.cz([],Be,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,ge=oe.x,pe=oe.y,Ne=this.width%2/2,Le=this.height%2/2,xe=Math.cos(this.angle),Ze=Math.sin(this.angle),ze=ge-Math.round(ge)+xe*Ne+Ze*Le,Ke=pe-Math.round(pe)+xe*Le+Ze*Ne,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 Be=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=s.ah(Be,Be,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,N=[d,d,g];s.bJ(N,N,A),s.bJ(w,w,-1),s.cG(w,w,N);const L=s.bb();s.bx(L,L,w),s.cC(L,L,N),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,N=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*g-d/this.worldSize*this._centerAltitude;return[A.x/this.worldSize-w[0]*N,A.y/this.worldSize-w[1]*N,d/this.worldSize*this._centerAltitude-w[2]*N]}_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 N=1;this.projection.wrap&&(this.center=this.center.wrap()),A>0&&(N=Math.min((g-w)/A,1)),this._camera.position=s.bg([],this._camera.position,d,N),this._updateStateFromCamera()}_updateStateFromCamera(){const d=this._camera.position,g=this._camera.forward(),{pitch:w,bearing:A}=this._camera.getPitchBearing(),N=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]-N)/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,N=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],N){const L=[g,w,A,1];s.aE(L,L,N);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),N=d.pixelSpaceConversion(this.center.lat,w,A);let L=.5/Math.tan(.5*this._fov)*this.height*N;return this.isOrthographic&&(L=s.am(1,L,s.cL(this.pitch>=Rm?1:this.pitch/Rm))),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 Da=(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)/N,(Y-ee-g._nearZ)/N]}}},gf=2048;class Av{constructor(d,g){this.aabb=d,this.lastCascade=g}}class WC{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 Av(g,null)}clear(){this.receivers={}}get(d){return this.receivers[d.key]}computeRequiredCascades(d,g,w){const A=s.cU.fromPoints(d.points);let N=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,N=Math.max(N,H),Y)break}}return N+1}}class Gx{constructor(d){this.painter=d,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new WC,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"),N=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 Ne=w.style._mergedLayers[pe];Ne.hasShadowPass()&&!Ne.isHidden(d.zoom)&&(L=F),!N||N!==pe&&N!==Ne.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=gf,Y=gf;if(this._cascades.length===0||gf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let pe=0;pe<2;++pe){const Ne=$.gl,Le=$.createFramebuffer(H,Y,0,"texture"),xe=new s.T($,{width:H,height:Y,data:null},Ne.DEPTH_COMPONENT16);Le.depthAttachment.set(xe.texture),this._cascades.push({framebuffer:Le,texture:xe,matrix:[],far:0,boundingSphereRadius:0,frustum:new s.cl,scale:0})}}this.shadowDirection=KC(g);let te=0;if(d.elevation){const pe=d.elevation,Ne=[1e4,-1e4];pe.visibleDemTiles.filter(Le=>Le.dem).forEach(Le=>{const xe=Le.dem.tree;Ne[0]=Math.min(Ne[0],xe.minimums[0]),Ne[1]=Math.max(Ne[1],xe.maximums[0])}),Ne[0]!==1e4&&(te=(Ne[1]-Ne[0])*pe.exaggeration())}const ee=1.5*d.cameraToCenterDistance,ie=3*ee,le=new Float64Array(16);for(let pe=0;pe=0)return{};const N=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(N[0],N[0],[A[0]*L,0,0]),s.cT(N[3],N[3],[A[0]*L,0,0])):A[0]>0&&(s.cT(N[1],N[1],[A[0]*L,0,0]),s.cT(N[2],N[2],[A[0]*L,0,0])),A[1]<0?(s.cT(N[0],N[0],[0,A[1]*L,0]),s.cT(N[1],N[1],[0,A[1]*L,0])):A[1]>0&&(s.cT(N[2],N[2],[0,A[1]*L,0]),s.cT(N[3],N[3],[0,A[1]*L,0]));const F={};return F.vertices=N,F.planes=[jv(N[1],N[0],N[4]),jv(N[2],N[1],N[5]),jv(N[3],N[2],N[6]),jv(N[0],N[3],N[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 jv(v,d,g){const w=s.ax([],g,d),A=s.ax([],v,d),N=s.bh([],w,A),L=s.ai(N);return L===0?[0,0,1,0]:(s.bJ(N,N,1/L),[N[0],N[1],N[2],-s.bi(N,d)])}function KC(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 zu(v,d,g){const w=d.properties.get("color-use-theme")==="none",A=d.properties.get("color"),N=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*N),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 Hx(v,d,g,w,A,N){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,ge;ee>ie/le?(oe=w,ge=w*te):(oe=.5*le*(1+ee),ge=.5*Math.sqrt(ie*ie+2*(w*w+g*g)*ee+le*le*ee*ee));const pe=v.projection.pixelsPerMeter(v.center.lat,$),Ne=v._camera.getCameraToWorldMercator(),Le=[0,0,-oe*H];s.ah(Le,Le,Ne);let xe=ge*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 Ht=new Float64Array(16);s.cz(Ht,rr,St);const Wt=new Float64Array(16);s.b7(Wt,Ht);const Dt=s.cl.fromInvProjectionMatrix(Wt,$,L,!0);for(const Ar of Dt.points){const Lr=Ze(Ar);xe=Math.max(xe,s.bK(s.cV([],Le,Lr)))}}xe*=A/(A-1);const Ke=Math.acos(d[2]),De=Math.atan2(-d[0],-d[1]),Be=new Vx;Be.position=Le,Be.setPitchBearing(Ke,De);const qe=Be.getWorldToCamera($,pe),st=xe*$,Qe=Math.min(v._mercatorZfromZoom(17)*$*-2,-2*st),xt=Be.getCameraToClipOrthographic(-st,st,-st,st,Qe,(st+N*pe)/d[2]),ft=new Float64Array(16);s.aD(ft,xt,qe);const Rt=s.cQ(Math.floor(1e6*Le[0])/1e6*$,Math.floor(1e6*Le[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 bt=new Float64Array(16);return s.b9(bt),s.bx(bt,bt,gt),s.aD(ft,bt,ft),[ft,st]}class t5 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),N=new s.cZ(d,g,void 0,void 0,A);return N.computeBoundsAndApplyParent(),N}).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),N=[],L=[];for(const F of A){const $=d[F];this.hasURLBeenRequested($)&&!w.forceReload||(this.modelByURL[$]={modelId:F,scope:g},N.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(N).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:N,modelId:L}=this.modelByURL[A];this.models[N][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 N=this.modelUris[g][d];w||delete this.modelUris[g][d],delete this.modelByURL[N];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 kT=s.a8.colorTheme,dg=new s.ab({data:new s.ac(kT.data)});function YC(v){if(!v.metadata||!v.metadata.content_area)return;const d=s.o.devicePixelRatio,{left:g,top:w,width:A,height:N}=v.metadata.content_area,L=g*d,F=w*d;return[L,F,L+A*d,F+N*d]}function Wx(v){if(v)return v.map(([d,g])=>[d*s.o.devicePixelRatio,g*s.o.devicePixelRatio])}class CT{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 jm))return d;const A=g.map(L=>this.sourceCache.getTile(L)),N=w.getImages(A,Array.from(this.pendingRequests));for(const[L,F]of N)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 yf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(d,g,w,A,N){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 N=d.floors[A];if(!N.geometry)continue;const L=N.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 r5 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 yf,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 N of A.floorIds)this._buildings[w].floorIds.add(N),this._buildings[w].floors[N]?this._mergeFloors(this._buildings[w].floors[N],A.floors[N]):(this._buildings[w].floors[N]=A.floors[N],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 N=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:N}}_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 Lm=(v,d)=>mr(v,d&&d.filter(g=>g.identifier!=="source.canvas")),n5=s.aJ(Qn,["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"]),ZC=s.aJ(Qn,["setCenter","setZoom","setBearing","setPitch"]),IT=new Set(["background","sky","slot","custom"]),kv={version:8,layers:[],sources:{}},NT={duration:300,delay:0};class hu 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({},NT),this._buildingIndex=new Lx(this),this.crossTileSymbolIndex=new ug,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 _n,this._hasDataDrivenEmissive=!1,this.indoorManager=new r5(this),this.dispatcher=g.dispatcher?g.dispatcher:new hr(Rn(),this),this.map.painter&&this.map.painter.context){const A=this.map.painter.context.maxUniformBufferBindings,N=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:A,maxUniformBlockSizeDwords:N,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}g.imageManager?this.imageManager=g.imageManager:(this.imageManager=new ci(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 t5(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=hu.registerForPluginStateChange(A=>{w.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:A.pluginStatus,pluginURL:A.pluginURL},(N,L)=>{if(s.d6(N),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 N=this.getOwnSource(A.sourceId);if(N&&N.vectorLayerIds)for(const L in this._layers){const F=this._layers[L];F.source===N.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=(N,L)=>{try{L(null,this.setState(N,w))}catch(F){L(F,!1)}};if(typeof d=="string"){const N=this.map._requestManager.normalizeStyleURL(d),L=this.map._requestManager.transformRequest(N,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 N=this.map._requestManager.transformRequest(d,s.R.Style);this._request=s.m(N,(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(kv,!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 N of d){const L=this._createFragmentStyle(N),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(N.url)){L.loadEmpty();continue}const $=N.data||this.importsCache.get(N.url);$?(N.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)):N.url?L.loadURL(N.url,{validate:g}):L.loadEmpty();const H={style:L,id:N.id,config:N.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 N=new hu(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 N.setEventedParent(this.map,{style:N}),N}_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 N=Object.assign({},kv,{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(N,g)}if(this.updateConfig(this._config,d.schema),g&&Lm(this,au(d)))return;this._loaded=!0;for(const N in d.sources)this.addSource(N,d.sources[N],{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 N=bT(this.stylesheet.layers);if(this._order=N.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 N){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 N=this._evaluateColorThemeData(A);this._loadColorTheme(N).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,N,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&&(N=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=N,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({},NT,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(N=>{for(const L in N._sourceCaches){const F=s.F(L,N.scope);d[F]=N._sourceCaches[L]}for(const L in N._otherSourceCaches){const F=s.F(L,N.scope);g[F]=N._otherSourceCaches[L]}for(const L in N._symbolSourceCaches){const F=s.F(L,N.scope);w[F]=N._symbolSourceCaches[L]}for(const L in N._fillExtrusionSourceCaches){const F=s.F(L,N.scope);A[F]=N._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 N=(L=[])=>{for(const F of L)if(F.type==="slot"){const $=s.da(F.id);d[$]&&N(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(N(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 N=Object.assign({},w);for(const F of Object.keys(kT))N[F]===void 0&&(N[F]=kT[F].default);const L=new s.aa(dg,g,new Map(A));return L.setTransitionOrValue(N,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 N="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(N)||(L=N+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 N,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,N=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(N&&L){const ee=s.o.getImageData(L),ie={};for(const le in N){const{width:oe,height:ge,x:pe,y:Ne,sdf:Le,pixelRatio:xe,stretchX:Ze,stretchY:ze,content:Ke}=N[le],De=new s.q({width:oe,height:ge});s.q.copy(ee,De,{x:pe,y:Ne},{x:0,y:0},{width:oe,height:ge},null),ie[le]={data:De,pixelRatio:xe!==void 0?xe:1,sdf:Le!==void 0&&Le,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 N in w)A.set(s.I.from(N),w[N]);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 N=new CT(d,this.scope,w);this.imageManager.addImageProvider(N,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=(N,L)=>{if(this._spriteRequest=null,N)g?this._loadSprite(d):this.fire(new s.B(N));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),(N,L)=>{if(N)return void A(N);const F={},$=s.c$(new s.a$(L));for(const H of $.icons){const Y={version:1,pixelRatio:s.o.devicePixelRatio,content:YC(H),stretchX:H.metadata?Wx(H.metadata.stretch_x_areas):void 0,stretchY:H.metadata?Wx(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 N=d.getProgramIds();if(N)for(const L of N){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 N={};for(const $ in this._mergedSourceCaches){const H=this._mergedSourceCaches[$];N[$]=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 N){const H=this._mergedSourceCaches[$];N[$]!==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(),Lm(this,au(d)))return!1;(d=s.d9(d)).layers=bT(d.layers);const w=function(L,F){if(!L)return[{command:Qn.setStyle,args:[F]}];let $=[];try{if(!s.b6(L.version,F.version))return[{command:Qn.setStyle,args:[F]}];if(s.b6(L.center,F.center)||$.push({command:Qn.setCenter,args:[F.center]}),s.b6(L.zoom,F.zoom)||$.push({command:Qn.setZoom,args:[F.zoom]}),s.b6(L.bearing,F.bearing)||$.push({command:Qn.setBearing,args:[F.bearing]}),s.b6(L.pitch,F.pitch)||$.push({command:Qn.setPitch,args:[F.pitch]}),s.b6(L.sprite,F.sprite)||$.push({command:Qn.setSprite,args:[F.sprite]}),s.b6(L.glyphs,F.glyphs)||$.push({command:Qn.setGlyphs,args:[F.glyphs]}),s.b6(L.imports,F.imports)||function(ie=[],le=[],oe){le=le||[];const ge=(ie=ie||[]).map(ag),pe=le.map(ag),Ne=ie.reduce(Dx,{}),Le=le.reduce(Dx,{}),xe=ge.slice();let Ze,ze,Ke,De;for(Ze=0,ze=0;Ze{ie.source&&H[ie.source]?$.push({command:Qn.removeLayer,args:[ie.id]}):te.push(ie)});let ee=L.terrain;ee&&H[ee.source]&&($.push({command:Qn.setTerrain,args:[void 0]}),ee=void 0),$=$.concat(Y),s.b6(ee,F.terrain)||$.push({command:Qn.setTerrain,args:[F.terrain]}),function(ie,le,oe){le=le||[];const ge=(ie=ie||[]).map(ag),pe=le.map(ag),Ne=ie.reduce(Dx,{}),Le=le.reduce(Dx,{}),xe=ge.slice(),Ze=Object.create(null);let ze,Ke,De,Be,qe,st,Qe;for(ze=0,Ke=0;ze!(L.command in ZC));if(w.length===0)return!1;const A=w.filter(L=>!(L.command in n5));if(A.length>0)throw new Error(`Unimplemented: ${A.map(L=>L.command).join(", ")}.`);const N=[];return w.forEach(L=>{N.push(this[L.command](...L.args))}),g&&Promise.all(N).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($t,`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(Px,`sources.${d}`,g,null,w))return;this.map&&this.map._collectResourceTiming&&(g.collectResourceTiming=!0);const A=pv(d,g,this.dispatcher,this);A.scope=this.scope,A.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(A.id),source:A.serialize(),sourceId:A.id}));const N=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 lu($,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)};N(s.b4.Other),g.type!=="vector"&&g.type!=="geojson"||(N(s.b4.Symbol),g.type==="vector"&&N(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(([N,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 N=s.da(A.id);delete this._sourceCaches[N],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 N=w[A];if(N.state!=="loaded"&&N.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 N of d){if(this._validate(de,"lights",N))return;switch(N.type){case"ambient":if(this.ambientLight){const L=this.ambientLight;L.set(N),L.updateTransitions(g)}else this.ambientLight=new Ta(N,vo(),this.scope,this.options);break;case"directional":if(this.directionalLight){const L=this.directionalLight;L.set(N),L.updateTransitions(g)}else this.directionalLight=new Ta(N,sc(),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(),N=d.properties.get("intensity"),L=d.properties.get("direction"),F=1-s.cP(L.x,L.y,L.z)[2]/90,$=w(A)*N*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:N})=>N===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={},N=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)}N.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 N=[];for(const L of A[d].selectors){const F=w.getOwnLayer(L.layer);F&&N.push(F)}return N}getConfigProperty(d,g){const w=this.getFragmentStyle(d);if(!w)return null;const A=s.F(g,w.scope),N=w.options.get(A),L=N?N.value||N.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 N=A.stylesheet.schema;if(!N||!N[g])return;const L=s.X(w);if(L.result!=="success")return void Lm(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}=N[g],ge=s.X(N[g].default);ge.result==="success"&&(Y=ge.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 N in w){const L=s.F(N,g.scope),F=g.options.get(L),$=F?F.value||F.default:null;A[N]=$?$.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,N;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"&&(N=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:N,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 N;if(d.type==="custom"){if(Lm(this,s.dd(d)))return;N=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;N=s.de(d,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(N),N.setEventedParent(this,{layer:{id:A}})}const L=s.F(N.source,N.scope);N.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(L),N.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.`)));N.slot&&N.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]=N;const $=this.getOwnLayerSourceCache(N),H=!!this.directionalLight&&this.directionalLight.shadowsEnabled();$&&N.canCastShadows()&&H&&($.castsShadows=!0);const Y=this._changes.getRemovedLayer(N);if(Y&&N.source&&$&&N.type!=="custom"){this._changes.discardLayerRemoval(N);const te=s.F(N.source,N.scope);Y.type!==N.type?this._changes.updateSourceCache(te,"clear"):(this._changes.updateSourceCache(te,"reload"),$.pause())}this._updateLayer(N),N.onAdd&&N.onAdd(this.map),N.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 N=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.`):N=L}this._order.splice(N,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 N=!1;for(const L in this._layers)if(this._layers[L].source===g.source&&this._layers[L].canCastShadows()){N=!0;break}A.castsShadows=N}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 N=this._checkLayer(d);if(N&&!s.b6(N.getLayoutProperty(g),w)){if(w!=null&&(!A||A.validate!==!1)&&Lm(N,ht.call(au,{key:`layers.${d}.layout.${g}`,layerType:N.type,objectKey:g,value:w,styleSpec:s.a8,style:{glyphs:!0,sprite:!0}})))return;N.setLayoutProperty(g,w),N.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(N.fqid),N.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(N.fqid),this._updateLayer(N)}}setLayerProperty(d,g,w,A={}){this._checkLoaded();const N=this._checkLayer(d);N&&(g==="appearances"?(N.setAppearances(w),this._updateLayer(N)):N.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 N=this._checkLayer(d);if(!N||s.b6(N.getPaintProperty(g),w)||w!=null&&(!A||A.validate!==!1)&&Lm(N,it.call(au,{key:`layers.${d}.paint.${g}`,layerType:N.type,objectKey:g,value:w,styleSpec:s.a8})))return;const L=N.setPaintProperty(g,w);N.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(N.fqid),N.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(N.fqid),L&&this._updateLayer(N),this._changes.updatePaintProperties(N)}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,N=this._checkSource(w);if(!N)return;const L=N.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 N=A.type,L=N==="vector"?d.sourceLayer:void 0;if(N==="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 N;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&&!N)N=ee;else if(!s.b6(N,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);N=this.getFeatureState({id:d.id,source:F.source,sourceLayer:F.sourceLayer})}return N}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={},N=[];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)N.push(te)}}}N.sort((F,$)=>$.intersectionZ-F.intersectionZ);const L=[];for(let F=w.length-1;F>=0;F--){const $=w[F];if(g($))for(let H=N.length-1;H>=0;H--){const Y=N[H].feature;if(Y.layer&&A[Y.layer.id]{if(IT.has(Y.type))return;const te=this.getOwnLayerSourceCache(Y),ee=N[te.id]=N[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,N,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 N="mock",L=[];if(g&&g.target)L.push(Object.assign({},g,{targetId:N,filter:A}));else{const Y=this.getFeaturesetDescriptors();for(const te of Y)L.push({targetId:N,filter:A,target:te});for(const{style:te}of this.fragments){const ee=te.getFeaturesetDescriptors();for(const ie of ee)L.push({targetId:N,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[N])Ed(te,Y,H)||$.push(new s.di(Y,te));return $}queryRenderedTargets(d,g,w){const A={},N=(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&&!IT.has(ie.type)&&N(ie,Y.getOwnLayerSourceCache(ie),F,ee)}}else if("layerId"in F.target){const{layerId:$}=F.target,H=this.getLayer($);if(!H||IT.has(H.type))continue;N(H,this.getLayerSourceCache(H),F)}const L=this._queryRenderedFeatures(d,A,w);return this._flattenAndSortRenderedFeatures(L)}_queryRenderedFeatures(d,g,w){const A=[],N=!!this.map._showQueryGeometry,L=ac.createFromScreenPoints(d,w);for(const F in g){const $=VC(L,g[F],this._availableImages,w,N,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 $=gv(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 N=this.getOwnSourceCaches(d);for(const L of N)A=A.concat(yT(L,g));return A}addSourceType(d,g,w){return hu.getSourceType(d)?w(new Error(`A source type called "${d}" already exists.`)):(hu.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 N=!1;for(const F in d)if(!s.b6(d[F],A[F])){N=!0;break}if(!N)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 N=Object.assign({},w),L={};if(this.terrain&&A){N.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",N,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 N=this.terrain,L=N.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])){N.set(d,this.options),this.stylesheet.terrain=d;const $=this._getTransitionParameters({duration:0});N.updateTransitions($),this.fire(new s.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(d){const g=this.fog=new ss(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 Mn(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,N={}){if(N&&N.validate===!1)return!1;const L=Object.assign({},this.serialize());return Lm(this,d.call(au,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=KC(this.directionalLight));const w=new Set,A=new Set,N=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"&&N.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=N.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 zx),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(d,g,w,A,N){this.pauseablePlacement||(this.pauseablePlacement=new zx);let L=!1,F=!1;const $={},H={};for(const oe of this._mergedOrder){const ge=this._mergedLayers[oe];if(ge.type!=="symbol")continue;const pe=s.F(ge.source,ge.scope);let Ne=$[pe];if(!Ne){const xe=this.getLayerSourceCache(ge);if(!xe)continue;const Ze=xe.getRenderableIds(!0).map(ze=>xe.getTileByID(ze));H[pe]=Ze.slice(),Ne=$[pe]=Ze.sort((ze,Ke)=>Ke.tileID.overscaledZ-ze.tileID.overscaledZ||(ze.tileID.isLessThan(Ke.tileID)?-1:1))}const Le=this.crossTileSymbolIndex.addLayer(ge,Ne,d.center.lng,d.projection);L=L||Le}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Y=!!(this.placement&&!d.equals(this.placement.transform)),te=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!N||this.placement.lastReplacementSourceUpdateTime!==N.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 ge=180*d.pitch/Math.PI;if(ge>=15){const pe=Math.min(1,Math.max(0,(ge-15)/5)),Ne=pe*pe*(3-2*pe);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Ne)+oe*Ne}}}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;oeN===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:N})=>N===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 N=this.getImportIndex(g);if(N===-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,N).concat(L).concat(w.slice(N)),this.fragments=this.fragments.slice(0,N).concat(F).concat(this.fragments.slice(N)),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 N=this.fragments[A];return N.style=this._createFragmentStyle(w[A]),N.style.on("style.import.load",()=>this.mergeAll()),N.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),N=this.stylesheet.imports||[];if(A===-1)return this;g?N[A].config=g:delete N[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)}},N=s.F(g.source,g.scope);A(this._mergedOtherSourceCaches[N]),A(this._mergedSymbolSourceCaches[N]),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)}}hu.getSourceType=function(v){return mv[v]},hu.setSourceType=function(v,d){mv[v]=d},hu.registerForPluginStateChange=s.dk;var PT=` #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`,RT=` #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;}`,xf=` #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`,Kx="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;}",LT=` #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`,DT=`#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`,hg=`#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`,fg=`#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`,MT=`#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;}`,Cv=`#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`,Ac=`#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 Yx=/#include\s+"([^"]+)"/g,ar=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,XC=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,QC=new Set(["ifdef","ifndef","elif","if","defined"]),Dm=new Set;ph(PT,Dm),ph(xf,Dm),ph(RT,Dm);const $u={"_prelude_fog.vertex.glsl":DT,"_prelude_terrain.vertex.glsl":LT,"_prelude_shadow.vertex.glsl":Cv,"_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":hg,"_prelude_shadow.fragment.glsl":Ac,"_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":fg,"_prelude_raster_particle.glsl":MT},mg={};zn("",LT),zn(hg,DT),zn(Ac,Cv),zn(fg,""),zn(MT,"");const _f=zn(RT,xf),Zx=PT,pg=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Zx,_f.fragmentSource].join(` `),i5=["precision highp float;",Zx,_f.vertexSource].join(` `);var JC={background:zn(`#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:zn(`#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:zn(`#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:zn(`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:zn("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:zn(`#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:zn("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:zn(`#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:zn(`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:zn("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:zn("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:zn("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:zn("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:zn(`#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:zn(`#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:zn(`#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:zn(`#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:zn(`#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:zn(`#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:zn(`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:zn(`#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:zn("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:zn(`#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:zn(`#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:zn(`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:zn(`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:zn(`#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:zn(`#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:zn(`#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:zn(`#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:zn(`#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:zn("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:zn("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:zn(`#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:zn(`#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:zn(`#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:zn("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:zn(`#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 }`,Kx),skyboxGradient:zn(`#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 }`,Kx),skyboxCapture:zn(` 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:zn(`#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:zn(`#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:zn(`#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:zn("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:zn(`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:zn("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:zn("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:zn("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:zn("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 ph(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(XC);if(A)for(const N of A)QC.has(N)||d.add(N)}}function eI(v){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(v)}function zn(v,d){const g=new Set,w=[],A=[];v=v.replace(Yx,(L,F)=>(A.push(F),"")),d=d.replace(Yx,(L,F)=>(w.push(F),""));let N=new Set(Dm);ph(v,N),ph(d,N);for(const L of[...w,...A])mg[L]||(mg[L]=new Set,ph($u[L],mg[L])),N=new Set([...N,...mg[L]]);return{fragmentSource:v=v.replace(ar,(L,F,$,H,Y)=>(g.add(Y),F==="define"?` #ifndef HAS_UNIFORM_u_${Y} ${eI(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 ${eI(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:N,vertexIncludes:w,fragmentIncludes:A}}class tI{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,N,L,F,$){this.context=d;let H=this.boundPaintVertexBuffers.length!==A.length;for(let te=0;!H&&te{const Ze=Le.paint.get("hillshade-shadow-color"),ze=Le.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ke=Le.paint.get("hillshade-highlight-color"),De=Le.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Be=Le.paint.get("hillshade-accent-color"),qe=Le.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",st=Le.paint.get("hillshade-emissive-strength");let Qe=s.ap(Le.paint.get("hillshade-illumination-direction"));if(Le.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(Ne.tileID.toUnwrapped(),xt),u_image:0,u_latrange:OT(0,Ne.tileID),u_light:[Le.paint.get("hillshade-exaggeration"),Qe],u_shadow:Ze.toPremultipliedRenderColor(ze?null:Le.lut),u_highlight:Ke.toPremultipliedRenderColor(De?null:Le.lut),u_emissive_strength:st,u_accent:Be.toPremultipliedRenderColor(qe?null:Le.lut)}})(v,g,w,v.terrain?d.projMatrix:null);v.uploadCommonUniforms(F,ee,d.toUnwrapped());const{tileBoundsBuffer:le,tileBoundsIndexBuffer:oe,tileBoundsSegments:ge}=v.getTileBoundsBuffers(g);ee.draw(v,$.TRIANGLES,A,N,L,Gr.disabled,ie,w.id,le,oe,ge)}function rI(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 N=g.getPixels();d.demTexture?d.demTexture.update(N,{premultiply:!1}):d.demTexture=new s.T(w,N,A.R32F,{premultiply:!1}),d.needsDEMTextureUpload=!1}function a5(v,d,g){const w=v.context,A=w.gl;if(!d.dem)return;const N=d.dem;if(w.activeTexture.set(A.TEXTURE1),rI(v,d,N),!d.demTexture)return;d.demTexture.bind(A.NEAREST,A.CLAMP_TO_EDGE);const L=N.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,N),g.id,$,H,Y),d.needsHillshadePrepare=!1}class os{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 nI extends os{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 o5 extends os{getDefault(){return 1}set(d){(d!==this.current||this.dirty)&&(this.gl.clearDepth(d),this.current=d,this.dirty=!1)}}class Iv extends os{getDefault(){return 0}set(d){(d!==this.current||this.dirty)&&(this.gl.clearStencil(d),this.current=d,this.dirty=!1)}}class l5 extends os{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 iI extends os{getDefault(){return!0}set(d){(d!==this.current||this.dirty)&&(this.gl.depthMask(d),this.current=d,this.dirty=!1)}}class FT extends os{getDefault(){return 255}set(d){(d!==this.current||this.dirty)&&(this.gl.stencilMask(d),this.current=d,this.dirty=!1)}}class Nv extends os{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 BT extends os{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 Mm extends os{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 Om extends os{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 gg extends os{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 Ad extends os{getDefault(){return this.gl.LESS}set(d){(d!==this.current||this.dirty)&&(this.gl.depthFunc(d),this.current=d,this.dirty=!1)}}class sI extends os{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 zT extends os{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 aI extends os{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 yg extends os{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 os{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 Rv extends os{getDefault(){return this.gl.BACK}set(d){(d!==this.current||this.dirty)&&(this.gl.cullFace(d),this.current=d,this.dirty=!1)}}class $T extends os{getDefault(){return this.gl.CCW}set(d){(d!==this.current||this.dirty)&&(this.gl.frontFace(d),this.current=d,this.dirty=!1)}}let Lv=class extends os{getDefault(){return null}set(v){(v!==this.current||this.dirty)&&(this.gl.useProgram(v),this.current=v,this.dirty=!1)}};class Xx extends os{getDefault(){return this.gl.TEXTURE0}set(d){(d!==this.current||this.dirty)&&(this.gl.activeTexture(d),this.current=d,this.dirty=!1)}}class oI extends os{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 lI extends os{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 cI extends os{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 xg extends os{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 uI extends os{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 c5 extends os{getDefault(){return null}set(d){const g=this.gl;g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,d),this.current=d,this.dirty=!1}}class u5 extends os{getDefault(){return null}set(d){this.gl&&(d!==this.current||this.dirty)&&(this.gl.bindVertexArray(d),this.current=d,this.dirty=!1)}}class d5 extends os{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 UT extends os{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 os{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 Qx extends os{constructor(d,g){super(d),this.context=d,this.parent=g}getDefault(){return null}}class _g extends Qx{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 qT extends Qx{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 dI extends Qx{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 h5 extends qT{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Jx=(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}),vg=(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge)=>({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:N,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:ge?Float32Array.from(ge):new Float32Array(9),u_skirt_height:ie,u_far_z_cutoff:le,u_emissive_texture_available:oe});function GT(v,d){return v!=null&&d!=null&&!(!v.hasData()||!d.hasData())&&v.demTexture!=null&&d.demTexture!=null&&v.tileID.key!==d.tileID.key}const Do=new class{constructor(){this.operations={}}newMorphing(v,d,g,w,A){if(v in this.operations){const N=this.operations[v];N.to.tileID.key!==g.tileID.key&&(N.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()}},Dv={0:null,1:"TERRAIN_VERTEX_MORPHING"};function e0(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 Mv(v,d){const g=1<({u_matrix:v});function n0(v,d,g,w,A){if(A>0){const N=s.o.now(),L=(N-v.timeAdded)/A,F=d?(N-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 Ov extends lu{constructor(d){const g={type:"raster-dem",maxzoom:Math.ceil(d.transform.maxZoom)},w=pv("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 HT extends lu{constructor(d){const g=pv("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((N,L)=>{if(N[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 N},{});for(const N in this._tiles)N in A||(this.freeFBO(N),this._tiles[N].unloadVectorData(),delete this._tiles[N])}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 Fv 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 i0 extends s.bu{constructor(d,g){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=d,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[w,A,N]=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,Ne=s.aC(Math.round(ge),0,s.an),Le=s.aC(Math.round(oe),0,s.an);$.emplaceBack(Ne+pe,Le)}const le=(oe,ge)=>{const pe=ge*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 ge=1;ge<129;ge++)le(ge,oe);return[0,129].forEach(oe=>{for(let ge=0;ge<130;ge++)le(ge,oe),le(oe,ge)}),[$,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,N),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new HT(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 Ov(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,N=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=N?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 N=d.zoom,L=this._style.terrain;if(!this._previousUpdateTimestamp)return L.getExaggeration(N);let F=N-this._previousZoom;const $=this._previousUpdateTimestamp;let H=N;this._evaluationZoom!=null&&(H=this._evaluationZoom,Math.abs(N-H)>.5&&(F=.5*(N-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[$],N),H.usedForTerrain))continue;const Y=d[$];(H.getSource().reparseOverscaled||H._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Y)}this.proxiedCoords[g.id]=A.map($=>new Fv($,$.key,this.orthoMatrix)),this._assignTerrainTiles(A),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(N),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],N=A.dem;!N||A.demTexture&&!A.needsDEMTextureUpload||(d.activeTexture.set(g.TEXTURE1),rI(this.painter,A,N))}}_prepareDemTileUniforms(d,g,w,A){if(!g||g.demTexture==null)return!1;const N=d.tileID.canonical,L=Math.pow(2,g.tileID.canonical.z-N.z),F=A||"";return w[`u_dem_tl${F}`]=[N.x*L%1,N.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 N=A.dem.tree.minimums[0];return N>0&&d++,w+N},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 N=this._emptyDEMTexture;return N?N.update(A,{premultiply:!1}):N=this._emptyDEMTexture=new s.T(d,A,g.R32F,{premultiply:!1}),N}setupElevationDraw(d,g,w){const A=this.painter.context,N=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()?N.LINEAR:N.NEAREST;let te=null;var ee;if(this.enabled?$&&F?(te=F.demTexture,A.activeTexture.set(N.TEXTURE4),$.demTexture.bind(Y($),N.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(N.TEXTURE2),te&&(L.u_dem_size=(ee=te).size[0]===1?1:ee.size[0]-2,te.bind(Y(F),N.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(w&&w.useDepthForOcclusion,g,L),w&&w.useMeterToDem&&F){const ie=(1<{if(pe===ft)return;const Rt=[Dv[ft],"PROJECTION_GLOBE_VIEW"];Le&&Rt.push("CUSTOM_ANTIALIASING");const Ft=H.isTileAffectedByFog(xt);ge=H.getOrCreateProgram("globeRaster",{defines:Rt,overrideFog:Ft}),pe=ft},Ze=H.colorModeForRenderPass(),ze=new Ir(oe.LEQUAL,Ir.ReadWrite,H.depthRangeFor3D);Do.update(ie);const Ke=s.dq(Ne),De=[s.aH(Ne.center.lng),s.aL(Ne.center.lat)],Be=H.globeSharedBuffers,qe=[Ne.width*s.o.devicePixelRatio,Ne.height*s.o.devicePixelRatio],st=Float32Array.from(Ne.globeMatrix),Qe={useDenormalizedUpVectorScale:!0};{const xt=H.transform,ft=e0(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],bt=Y.terrainTileForTile[Ft.key];GT(gt,bt)&&Do.newMorphing(Ft.key,gt,bt,ie,250),t0(H,ot.emissiveTexture),le.activeTexture.set(oe.TEXTURE0),ot.texture&&ot.texture.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const St=Do.getMorphValuesForProxy(Ft.key),rr=St?1:0;St&&Object.assign(Qe,{morphing:{srcDemTile:St.from,dstDemTile:St.to,phase:s.dn(St.phase)}});const Ht=s.dr(Ft.canonical),Wt=s.ds(Ht.getCenter().lat),Dt=s.dt(Ft.canonical,Ht,Wt,xt.worldSize/xt._pixelsPerMercatorPixel),Ar=s.du(s.dv(Ft.canonical)),Lr=H.emissiveMode==="mrt-fallback"?1:0,yr=vg(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),ge&&(Y.setupElevationDraw(ot,ge,Qe),H.uploadCommonUniforms(le,ge,Ft.toUnwrapped()),Be)){const[Tr,Hr,sn]=Be.getGridBuffers(Wt,ft!==0);ge.draw(H,Rt,ze,et,Ze,Gr.backCCW,yr,"globe_raster",Tr,Hr,sn)}}}if(Be&&(H.renderDefaultNorthPole||H.renderDefaultSouthPole)){const xt=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Le&&xt.push("CUSTOM_ANTIALIASING"),ge=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,vg(Ne.expandedFarZProjMatrix,Dt,Dt,Ar,0,De,Ne.frustumCorners.TL,Ne.frustumCorners.TR,Ne.frustumCorners.BR,Ne.frustumCorners.BL,Ne.globeCenterInViewSpace,Ne.globeRadius,qe,0,Ne._farZ,Lr),"globe_pole_raster",Hr,rr,Ht);Y.setupElevationDraw(Wt,ge,Qe),H.uploadCommonUniforms(le,ge,ft.toUnwrapped()),et&&H.renderDefaultNorthPole&&yr(ge,bt),gt&&H.renderDefaultSouthPole&&(Dt=s.cC(s.bb(),Dt,[1,-1,1]),yr(ge,St))}}}})(A,N,L,F,$);else{const H=A.context,Y=H.gl;let te,ee;const ie=A.shadowRenderer,le=Da(A,A.longestCutoffRange),oe=Ze=>{if(ee===Ze)return;const ze=[];ze.push(Dv[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},ge=A.colorModeForRenderPass(),pe=new Ir(Y.LEQUAL,Ir.ReadWrite,A.depthRangeFor3D);Do.update($);const Ne=A.transform,Le=e0(Ne.zoom,N.exaggeration(),N.sourceCache._source.tileSize);let xe=[0,0,0];if(ie){const Ze=A.style.directionalLight,ze=A.style.ambientLight;Ze&&ze&&(xe=zu(A.style,Ze,ze))}{ee=-1;const Ze=Y.TRIANGLES,[ze,Ke]=[N.gridIndexBuffer,N.gridSegments];for(const De of F){const Be=L.getTile(De),qe=Qr.disabled,st=N.prevTerrainTileForTile[De.key],Qe=N.terrainTileForTile[De.key];GT(st,Qe)&&Do.newMorphing(De.key,st,Qe,$,250),t0(A,Be.emissiveTexture),H.activeTexture.set(Y.TEXTURE0),Be.texture&&Be.texture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE);const xt=Do.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=Jx(De.projMatrix,Mv(De.canonical,Ne.renderWorldCopies)?Le/10:Le,xe,Ft);if(oe(ft),!te)continue;N.setupElevationDraw(Be,te,Rt);const et=De.toUnwrapped();ie&&ie.setupShadows(et,te),A.uploadCommonUniforms(H,te,et,null,le),te.draw(A,Ze,pe,qe,ge,Gr.backCCW,ot,"terrain_raster",N.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,N=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 N){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 ge;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 Ne=g.style._mergedLayers[F[pe]];if(Ne.isHidden(g.transform.zoom))continue;const Le=g.style.getLayerSourceCache(Ne),xe=Le?this.proxyToSource[Y.key][Le.id]:[Y];if(!xe)continue;const Ze=xe;w.viewport.set([0,0,ie.fb.width,ie.fb.height]),ge!==(Le?Le.id:null)&&(this._setupStencil(ie,xe,Ne,Le),ge=Le?Le.id:null),g.renderLayer(g,Le,Ne,Ze)}if(oe.drawBuffers([oe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const pe of this._pendingGroundEffectLayers){const Ne=g.style._mergedLayers[F[pe]];if(Ne.isHidden(g.transform.zoom))continue;const Le=g.style.getLayerSourceCache(Ne),xe=Le?this.proxyToSource[Y.key][Le.id]:[Y];if(!xe)continue;const Ze=xe;w.viewport.set([0,0,ie.fb.width,ie.fb.height]),ge!==(Le?Le.id:null)&&(this._setupStencil(ie,xe,Ne,Le),ge=Le?Le.id:null),g.renderLayer(g,Le,Ne,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 N=0;Nw}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(N=>N.dem).map(N=>{const L=N.tileID,F=1<(N.t!==null?N.t:Number.MAX_VALUE)-(L.t!==null?L.t:Number.MAX_VALUE));for(const N of A){if(N.t==null)return null;const L=N.tile.dem.tree.raycast(N.minx,N.miny,N.maxx,N.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 N=d.createFramebuffer(w[0],w[1],1,null);let L;return N.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),N.createColorAttachment(d,1),N.colorAttachment1.set(L.texture)),N.depthAttachment=new h5(d,N.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=d.createRenderbuffer(d.gl.DEPTH_STENCIL,w[0],w[1]),this._stencilRef=0,N.depthAttachment.set(this._sharedDepthStencil),d.clear({stencil:0})):N.depthAttachment.set(this._sharedDepthStencil),d.extTextureFilterAnisotropic&&g.texParameterf(g.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax),{fb:N,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,N=A.gl,L=this.drapeBufferSize;if(g){const F=new s.T(A,{width:L[0],height:L[1],data:null},N.R8);F.bind(N.LINEAR,N.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 Ol){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 N=[...this._drapedRenderBatches];N.sort((L,F)=>F.end-F.start-(L.end-L.start));for(const L of N)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 N=this.painter.context,L=N.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&&(N.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,N=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,N.TRIANGLES,Ir.disabled,new Qr({func:N.ALWAYS,mask:0},$,255,N.KEEP,N.KEEP,N.REPLACE),Kr.disabled,Gr.disabled,r0(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,N=s.bU(1,g.center.lat),L=[A[0],A[1],A[2]/N,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]*=N,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]=[],N=this.proxyCoords;for(let $=0;$Y.overscaledZ-H.overscaledZ)}_setupProxiedCoordsForImageSource(d,g,w){if(!d.getSource().loaded())return;const A=this.proxiedCoords[d.id]=[],N=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<ge+H.max.x||le+oepe+H.max.y};for(let te=0;teL.key===g.tileID.key);if(N)return N}if(g.tileID.key!==d.key){const N=d.canonical.z-g.tileID.canonical.z;let L,F,$;A=s.bb();const H=g.tileID.wrap-d.wrap<0?(L=s.an>>N,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 WT(v,d,g){const w=function(F,$,H){const Y=s.bi($,F),te=s.bi(H,[.2126,.7152,.0722]),ee=(le,oe,ge)=>(1-ge)*le+ge*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 N=[0,0,0];s.bJ(N,d.slice(0,3),v[2]);const L=[0,0,0];return s.cT(L,A,N),s.cW(L)}const hI=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],fI=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Fm{static cacheKey(d,g,w,A){const N=[g];A&&N.push(A.cacheKey);for(const L of w)(typeof L=="string"&&L.includes(" ")||d.usedDefines.has(L))&&N.push(L);return N.join("/")}constructor(d,g,w,A,N,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=[$,pg];for(const oe of w.fragmentIncludes)H.push($u[oe]);H.push(w.fragmentSource);const Y=H.join(` `),te=[$,i5];for(const oe of w.vertexIncludes)te.push($u[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=N(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,N,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||!hI.includes(this.name))||!(!te.layers3D||!fI.includes(this.name))))return;const ie=ee.gl,le=d.wireframeDebugCache.getLinesFromTrianglesBuffer(d.frameCounter,N,ee);if(!le)return;const oe=[...this.fixedDefines,"DEBUG_WIREFRAME"],ge=d.getOrCreateProgram(this.name,{config:this.configuration,defines:oe});ee.program.set(ge.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(ge.program,ee,ge.binderUniforms,F,{zoom:$}),pe("fixedUniforms",this,ge),pe("terrainUniforms",this,ge),pe("globeUniforms",this,ge),pe("fogUniforms",this,ge),pe("lightsUniforms",this,ge),pe("shadowUniforms",this,ge),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 Ne=3*L.primitiveLength*2,Le=3*L.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const xe=Y||1;for(let Ze=0;Ze1?ie.drawElementsInstanced(ie.LINES,Ne,ie.UNSIGNED_SHORT,Le,Y):ie.drawElements(ie.LINES,Ne,ie.UNSIGNED_SHORT,Le);N.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,N,L,F,$,H,Y,te,ee,ie,le,oe,ge){const pe=d.context,Ne=pe.gl;if(this.failedToCreate)return;pe.program.set(this.program),pe.setDepthMode(w),pe.setStencilMode(A),pe.setColorMode(N),pe.setCullFace(L);for(const[De,Be]of this.fixedUniformsEntries)Be.set(this.program,De,F[De]);le&&le.setUniforms(this.program,pe,this.binderUniforms,ee,{zoom:ie});const Le={[Ne.POINTS]:1,[Ne.LINES]:2,[Ne.TRIANGLES]:3,[Ne.LINE_STRIP]:1}[g];this.checkUniforms($,"RENDER_SHADOWS",this.shadowUniforms);const xe=oe||[],Ze=le?le.getPaintVertexBuffers():[],ze=g===Ne.TRIANGLES&&Y,Ke=ge&&ge>0?1:void 0;for(const De of te.get()){const Be=De.vaos||(De.vaos={});if((Be[$]||(Be[$]=new tI)).bind(pe,this,H,Ze,Y,De.vertexOffset,xe,Ke),this.forceManualRenderingForInstanceIDShaders){const qe=ge||1;for(let st=0;st1?Ne.drawElementsInstanced(g,De.primitiveLength*Le,Ne.UNSIGNED_SHORT,De.primitiveOffset*Le*2,ge):Y?Ne.drawElements(g,De.primitiveLength*Le,Ne.UNSIGNED_SHORT,De.primitiveOffset*Le*2):Ne.drawArrays(g,De.vertexOffset,De.vertexLength);ze&&this._drawDebugWireframe(d,w,A,N,Y,De,ee,ie,le,ge)}}}function mI(v,d,g=0){const w=Math.pow(2,d.tileID.overscaledZ),A=d.tileSize*Math.pow(2,v.transform.tileZoom)/w,N=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:[N>>16,L>>16],u_pixel_coord_lower:[65535&N,65535&L],u_pattern_transition:g}}const Bv={terrain:0,flat:1},f5=s.bb(),pI=(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne=[0,0,1])=>{const Le=d.style.light,xe=Le.properties.get("position"),Ze=[xe.x,xe.y,xe.z],ze=s.dE();Le.properties.get("anchor")==="viewport"&&(s.dF(ze,-d.transform.angle),s.dG(Ze,Ze,ze));const Ke=Le.properties.get("color").toPremultipliedRenderColor(null),De=d.transform,Be={u_matrix:v,u_lightpos:Ze,u_lightintensity:Le.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:f5,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:N,u_width_scale:L,u_flood_light_color:le,u_vertical_scale:oe,u_flood_light_intensity:ge,u_ground_shadow_factor:pe,u_front_cutoff_params:Ne};return De.projection.name==="globe"&&(Be.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[N]}),p5=(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe)=>{const Ne=pI(v,d,g,w,A,N,L,F,H,Y,te,ee,ie,le,oe,ge,1,[0,0,0]),Le={u_height_factor:-Math.pow(2,F.overscaledZ)/$.tileSize/8};return Object.assign(Ne,mI(d,$,pe),Le)},zv=(v,d,g)=>({u_matrix:v,u_emissive_strength:d,u_ground_shadow_factor:g}),$v=(v,d,g,w,A,N=0)=>Object.assign(zv(v,d,A),mI(g,w,N)),gI=(v,d,g,w)=>({u_matrix:v,u_world:g,u_emissive_strength:d,u_ground_shadow_factor:w}),bg=(v,d,g,w,A,N,L=0)=>Object.assign($v(v,d,g,w,N,L),{u_world:A}),yI=(v,d)=>({u_matrix:v,u_depth_bias:d}),xI=(v,d)=>({u_matrix:v,u_ground_shadow_factor:d}),s0=(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}),Uv=(v,d,g)=>({u_image:v,u_opacity:d,u_blend_mode:g}),vf=(v,d,g,w,A,N,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:N,u_facade_emissive_chance:L,u_flood_light_color:F,u_flood_light_intensity:$,u_front_cutoff_params:H}),Vv=v=>({u_matrix:v}),qv=v=>({u_matrix:v}),_I=(v,d,g,w,A,N,L,F)=>{const $=s.an/N.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}},bf=(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]}),a0=(v,d,g=1)=>({u_matrix:v,u_color:d,u_overlay:0,u_overlay_scale:g}),Gv=s.bb(),vI=(v,d,g,w,A,N,L)=>{const F=v.transform,$=F.projection.name==="globe",H=$?s.dH(F.zoom,d.canonical)*F._pixelsPerMercatorPixel:s.aA(g,1,N),Y={u_matrix:d.projMatrix,u_extrude_scale:H,u_intensity:L,u_inv_rot_matrix:Gv,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:N,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:wI(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:KT(s.dK,ge,Ne),u_colorization_offset:Hv(s.dK,pe,Ne),u_color_ramp:oe,u_texture_offset:[xe/(Le+2*xe),Le/(Le+2*xe)],u_texture_res:[Le+2*xe,Le+2*xe],u_emissive_strength:Ze,u_zbias_factor:YT(v)});function wI(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 jd=.05,g5=(v,d,g,w,A,N,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:N,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:$}),y5=(v,d,g,w,A,N,L,F,$,H)=>({u_particle_texture:v,u_particle_texture_side_len:d,u_tile_offset:g,u_velocity:w,u_color_ramp:N,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:[jd,jd]}),SI=(v,d,g,w,A,N,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:N,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:[jd,jd]}),TI=s.bb(),Wv=(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne,Le,xe,Ze,ze,Ke)=>{const De=A.transform,Be={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(Ne),u_rotate_symbol:+g,u_aspect_ratio:De.width/De.height,u_fade_change:A.options.fadeDuration?A.symbolFadeChange:1,u_matrix:N,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:TI,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:TI,u_up_vector:[0,-1,0],u_color_adj_mat:Ze,u_icon_transition:ze||0,u_gamma_scale:w?A.transform.getCameraToCenterDistance(Ne)*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:Le,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 Ne.name==="globe"&&(Be.u_tile_id=[ie.canonical.x,ie.canonical.y,1<({u_matrix:v,u_emissive_strength:d,u_opacity:g,u_color:w}),wf=(v,d,g,w,A,N,L,F,$)=>Object.assign(function(H,Y,te,ee,ie,le){const{width:oe,height:ge}=ee.imageManager.getPixelSize(Y),pe=Math.pow(2,le.tileID.overscaledZ),Ne=le.tileSize*Math.pow(2,ee.transform.tileZoom)/pe,Le=Ne*(le.tileID.canonical.x+le.tileID.wrap*pe),xe=Ne*le.tileID.canonical.y;return{u_image:0,u_pattern_tl:te.tl,u_pattern_br:te.br,u_texsize:[oe,ge],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:[Le>>16,xe>>16],u_pixel_coord_lower:[65535&Le,65535&xe]}}(0,N,L,w,F,$),{u_matrix:v,u_emissive_strength:d,u_opacity:g}),wg=new Float32Array(s.b9([])),Bm=(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie=[0,0,0],le,oe,ge)=>{const pe=A.style.light,Ne=pe.properties.get("position"),Le=[-Ne.x,-Ne.y,Ne.z],xe=s.dE();pe.properties.get("anchor")==="viewport"&&(s.dF(xe,-A.transform.angle),s.dG(Le,Le,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),ge&&(De.r=ge[0],De.g=ge[1],De.b=ge[2],De.a=ge[3]),oe&&(De.r=oe.color.r,De.g=oe.color.g,De.b=oe.color.b,De.a=oe.colorMix,te=oe.emissionStrength,N*=oe.opacity),{u_matrix:v,u_lighting_matrix:d,u_normal_matrix:g,u_node_matrix:w||wg,u_lightpos:Le,u_lightintensity:pe.properties.get("intensity"),u_lightcolor:[ze.r,ze.g,ze.b],u_camera_pos:ie,u_opacity:N,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]}},ZT=(v,d=wg,g=wg)=>({u_matrix:v,u_instance:d,u_node_matrix:g}),Kv={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 Uu{constructor(d,g,w,A){this.id=Uu.uniqueIdxCounter,Uu.uniqueIdxCounter++,this.context=d;const N=d.gl;this.buffer=N.createBuffer(),this.dynamicDraw=!!w,this.context.unbindVAO(),d.bindElementBuffer.set(this.buffer),N.bufferData(N.ELEMENT_ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?N.DYNAMIC_DRAW:N.STATIC_DRAW),this.dynamicDraw||A||g.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(d){this.id=Uu.uniqueIdxCounter,Uu.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)}}Uu.uniqueIdxCounter=0;const XT={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class EI{constructor(d,g,w,A,N,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||N||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 N=g.getAttributeLocation(d,A.name);if(N!==-1){const L=A.offset+this.itemSize*(w||0);A.type==="Float32"?d.vertexAttribPointer(N,A.components,d.FLOAT,!1,this.itemSize,L):d.vertexAttribIPointer(N,A.components,d[XT[A.type]],this.itemSize,L)}}}setVertexAttribDivisor(d,g,w){for(let A=0;A0&&d.vertexAttribDivisor(N,w)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class l0{constructor(d,g,w,A,N){this.context=d,this.width=g,this.height=w;const L=this.framebuffer=d.gl.createFramebuffer();A>0&&(this.colorAttachment0=new _g(d,L,0)),A>1&&(this.colorAttachment1=new _g(d,L,1)),N&&(this.depthAttachmentType=N,this.depthAttachment=N==="renderbuffer"?new qT(d,L):new dI(d,L))}static createWithTexture(d,g,w,A,N){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),N){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 _g(d,this.framebuffer,0):g===1&&(this.colorAttachment1=new _g(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 Sg{constructor(d,g){this.gl=d,this.clearColor=new nI(this),this.clearDepth=new o5(this),this.clearStencil=new Iv(this),this.colorMask=new l5(this),this.depthMask=new iI(this),this.stencilMask=new FT(this),this.stencilFunc=new Nv(this),this.stencilOp=new BT(this),this.stencilTest=new Mm(this),this.depthRange=new Om(this),this.depthTest=new gg(this),this.depthFunc=new Ad(this),this.blend=new sI(this),this.blendFunc=new zT(this),this.blendColor=new aI(this),this.blendEquation=new yg(this),this.cullFace=new Pv(this),this.cullFaceSide=new Rv(this),this.frontFace=new $T(this),this.program=new Lv(this),this.activeTexture=new Xx(this),this.viewport=new oI(this),this.bindFramebuffer=new lI(this),this.bindRenderbuffer=new cI(this),this.bindTexture=new xg(this),this.bindVertexBuffer=new uI(this),this.bindElementBuffer=new c5(this),this.bindVertexArrayOES=new u5(this),this.pixelStoreUnpack=new d5(this),this.pixelStoreUnpackPremultiplyAlpha=new UT(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 Uu(this,d,g,w)}createVertexBuffer(d,g,w,A,N){return new EI(this,d,g,w,A,N)}createRenderbuffer(d,g,w){const A=this.gl,N=A.createRenderbuffer();return this.bindRenderbuffer.set(N),A.renderbufferStorage(A.RENDERBUFFER,d,g,w),this.bindRenderbuffer.set(null),N}createFramebuffer(d,g,w,A){return new l0(this,d,g,w,A)}clear({color:d,depth:g,stencil:w,colorMask:A}){const N=this.gl;let L=0;d&&(L|=N.COLOR_BUFFER_BIT,this.clearColor.set(d.toNonPremultipliedRenderColor(null)),this.colorMask.set(A||[!0,!0,!0,!0])),g!==void 0&&(L|=N.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(g),this.depthMask.set(!0)),w!==void 0&&(L|=N.STENCIL_BUFFER_BIT,this.clearStencil.set(w),this.stencilMask.set(255)),N.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 zm;function br(v,d,g,w,A,N,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",ge=[];let pe=0,Ne=0;for(let De=0;De0){const Lr=s.bb(),yr=Ht;s.cz(Lr,st.placementInvProjMatrix,H.glCoordMatrix),s.cz(Lr,Lr,st.placementViewportMatrix),ge.push({circleArray:Dt,circleOffset:Ne,transform:yr,invTransform:Lr,projection:st.getProjection()}),pe+=Dt.length/4,Ne=pe}if(!Wt)continue;v.terrain&&v.terrain.setupElevationDraw(qe,rr);const Ar=bt?[Be.canonical.x,Be.canonical.y,1<=0&&(ie[Le.associatedIconIndex]={x:Qe,y:xt,z:ft,angle:gt})}else lg(ze,te)}if(H){ee.clear();const Ne=v.icon.placedSymbolArray;for(let Le=0;Le{let on=[0,0,0];if(ei){const Ki=v.style.directionalLight,wi=v.style.ambientLight;Ki&&wi&&(on=zu(v.style,Ki,wi))}return on},wn=ei=>{if(v.context.disableSymbolUBO)return;ei.push("USE_PAINT_PROPERTIES_UBO");const on=Math.floor(v.context.maxUniformBlockSize/4),Ki=Math.floor(on/4);ei.push(`MAX_UBO_SIZE_VEC4 ${Ki}u`)},tn=ei=>{Be.depthOcclusionForSymbolsAndCircles&&(g.hasOcclusionOpacityProperties||v.terrain)&&(ei.push("DEPTH_D24"),ei.push("DEPTH_OCCLUSION"))},qn=ei=>{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),ei.push("APPLY_LUT_ON_GPU"))},bi=()=>{const ei=qe&&g.layout.get("symbol-placement")!=="point",on=[];tn(on),qn(on);const Ki=ei||sn,wi=Dt.elevationType==="road",Os=v.shadowRenderer,In=wi&&Qe&&!!Os&&Os.enabled,Ai=Ur(In),Js=wi&&Qe&&!v.terrain?ot:Ft,wo=g.paint.get("icon-image-cross-fade");v.terrainRenderModeElevated()&&Qe&&on.push("PITCH_WITH_MAP_TERRAIN"),Ar&&(on.push("PROJECTION_GLOBE_VIEW"),Ki&&on.push("PROJECTED_POS_ON_VIEWPORT")),wo>0&&Dt.hasAnySecondaryIcon&&on.push("ICON_TRANSITION"),!Dt.icon.zOffsetVertexBuffer||wi&&v.terrain||on.push("Z_OFFSET"),pe===0&&Ne===0&&Le===0&&xe===1||on.push("COLOR_ADJUSTMENT"),Dt.sdfIcons&&on.push("RENDER_SDF"),In&&on.push("RENDER_SHADOWS","NORMAL_OFFSET"),wi&&Qe&&!v.terrain&&Dt.icon.orientationVertexBuffer&&on.push("ELEVATED_ROADS"),wn(on);const ha=Ke.disableSymbolUBO?Dt.icon.programConfigurations.get(g.id):null,qa=v.getOrCreateProgram("symbol",{config:ha,defines:on}),dc=Wt.imageAtlasTexture?Wt.imageAtlasTexture.size:[0,0],oi=Dt.iconSizeData,Ic=s.bj(oi,Be.zoom),Nc=Qe||!Be.isOrthographic,Li=mf(yr,Wt.tileID.canonical,Qe,qe,Be,Dt.getProjection(),Tr),$i=og(yr,Wt.tileID.canonical,Qe,qe,Be,Dt.getProjection(),Tr),gi=Dt.icon.uboBinder&&Dt.icon.uboBinder.cachedHeader&&256&Dt.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:F,Is=v.translatePosMatrix($i,Wt,gi,H,!0),Mo=v.translatePosMatrix(yr,Wt,gi,H),hs=Ki?c0:Li,hc=qe&&!Qe&&!ei;let Tf=rr;!bt&&!Be.mercatorFromTransition||qe||(Tf=gh(Be));const Km=Ar?Tf:rr,Ym=g.getColorAdjustmentMatrix(pe,Ne,Le,xe),Cg=Wv(oi.kind,Ic,hc,Qe,v,Mo,hs,Is,Ze,!1,dc,[0,0],0,Ht,Lr,et,en,Km,Dt.getProjection(),Ai,bn,Ym,wo,null),wh=Wt.imageAtlasTexture?Wt.imageAtlasTexture:null,Pd=g.layout.get("icon-size").constantOr(0)!==1||Dt.iconsNeedLinear,Ig=Dt.sdfIcons||v.options.rotating||v.options.zooming||Pd||Nc?De.LINEAR:De.NEAREST,Bl=Dt.sdfIcons&&g.paint.get("icon-halo-width").constantOr(1)!==0,Ef=v.terrain&&Qe&&ei?s.b7(s.bb(),Li):c0;if(ei&&Dt.icon){const Af=s.bu.getAtTileOffsetFunc(Ht,Be.center.lat,Be.worldSize,Dt.getProjection()),jf=Ou(yr,Wt.tileID.canonical,Qe,qe,Be,Dt.getProjection(),Tr),xb=g.layout.get("icon-size-scale-range"),Ng=s.aC(v.scaleFactor,xb[0],xb[1]);lc(Dt,yr,v,!1,jf,$i,Qe,oe,Af,Ht,Ng)}return{program:qa,buffers:Dt.icon,uniformValues:Cg,atlasTexture:wh,atlasTextureIcon:null,atlasInterpolation:Ig,atlasInterpolationIcon:null,isSDF:Dt.sdfIcons,hasHalo:Bl,depthMode:Js,tile:Wt,renderWithShadows:In,labelPlaneMatrixInv:Ef}},Zi=()=>{const ei=st&&g.layout.get("symbol-placement")!=="point",on=[],Ki=ei||gt||sn,wi=Dt.elevationType==="road",Os=v.shadowRenderer,In=wi&&xt&&!!Os&&Os.enabled,Ai=Ur(In),Js=wi&&xt&&!v.terrain?ot:Ft;v.terrainRenderModeElevated()&&xt&&on.push("PITCH_WITH_MAP_TERRAIN"),Ar&&(on.push("PROJECTION_GLOBE_VIEW"),Ki&&on.push("PROJECTED_POS_ON_VIEWPORT")),!Dt.text.zOffsetVertexBuffer||wi&&v.terrain||on.push("Z_OFFSET"),Dt.iconsInText&&on.push("RENDER_TEXT_AND_SYMBOL"),on.push("RENDER_SDF"),In&&on.push("RENDER_SHADOWS","NORMAL_OFFSET"),wi&&xt&&!v.terrain&&Dt.text.orientationVertexBuffer&&on.push("ELEVATED_ROADS"),tn(on),wn(on);const wo=Ke.disableSymbolUBO?Dt.text.programConfigurations.get(g.id):null,ha=v.getOrCreateProgram("symbol",{config:wo,defines:on});let qa,dc=[0,0],oi=null;const Ic=Dt.textSizeData;Dt.iconsInText&&(dc=Wt.imageAtlasTexture?Wt.imageAtlasTexture.size:[0,0],oi=Wt.imageAtlasTexture?Wt.imageAtlasTexture:null,qa=xt||!Be.isOrthographic||v.options.rotating||v.options.zooming||Ic.kind==="composite"||Ic.kind==="camera"?De.LINEAR:De.NEAREST);const Nc=Wt.glyphAtlasTexture?Wt.glyphAtlasTexture.size:[0,0],Li=g.layout.get("text-size-scale-range"),$i=s.aC(v.scaleFactor,Li[0],Li[1]),gi=s.bj(Ic,Be.zoom,$i),Is=mf(yr,Wt.tileID.canonical,xt,st,Be,Dt.getProjection(),Tr),Mo=og(yr,Wt.tileID.canonical,xt,st,Be,Dt.getProjection(),Tr),hs=Dt.text.uboBinder&&Dt.text.uboBinder.cachedHeader&&256&Dt.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:$,hc=v.translatePosMatrix(Mo,Wt,hs,Y,!0),Tf=v.translatePosMatrix(yr,Wt,hs,Y),Km=Ki?c0:Is,Ym=st&&!xt&&!ei;let Cg=rr;!bt&&!Be.mercatorFromTransition||st||(Cg=gh(Be));const wh=Wv(Ic.kind,gi,Ym,xt,v,Tf,Km,hc,Ze,!0,Nc,dc,0,Ht,Lr,et,en,Ar?Cg:rr,Dt.getProjection(),Ai,bn,null,null,$i),Pd=Wt.glyphAtlasTexture?Wt.glyphAtlasTexture:null,Ig=De.LINEAR,Bl=g.paint.get("text-halo-width").constantOr(1)!==0,Ef=v.terrain&&xt&&ei?s.b7(s.bb(),Is):c0;if(ei&&Dt.text){const Af=s.bu.getAtTileOffsetFunc(Ht,Be.center.lat,Be.worldSize,Dt.getProjection()),jf=Ou(yr,Wt.tileID.canonical,xt,st,Be,Dt.getProjection(),Tr);lc(Dt,yr,v,!0,jf,Mo,xt,ge,Af,Ht,$i)}return{program:ha,buffers:Dt.text,uniformValues:wh,atlasTexture:Pd,atlasTextureIcon:oi,atlasInterpolation:Ig,atlasInterpolationIcon:qa,isSDF:!0,hasHalo:Bl,depthMode:Js,tile:Wt,renderWithShadows:In,labelPlaneMatrixInv:Ef}},ki=Dt.icon.segments.get().length,Jn=Dt.text.segments.get().length,gn=ki&&!L.onlyText?bi():null,yn=Jn&&!L.onlyIcons?Zi():null,Ci=g.paint.get("icon-opacity").constantOr(1),ns=g.paint.get("text-opacity").constantOr(1);if(ft&&Dt.canOverlap){Rt=!0;const ei=Ci&&!L.onlyText?Dt.icon.segments.get():[],on=ns&&!L.onlyIcons?Dt.text.segments.get():[];for(const Ki of ei)St.push({segments:new s.dy([Ki]),sortKey:Ki.sortKey,state:gn});for(const Ki of on)St.push({segments:new s.dy([Ki]),sortKey:Ki.sortKey,state:yn})}else L.onlyText||St.push({segments:Ci?Dt.icon.segments:new s.dy([]),sortKey:0,state:gn}),L.onlyIcons||St.push({segments:ns?Dt.text.segments:new s.dy([]),sortKey:0,state:yn})}Rt&&St.sort((Ht,Wt)=>Ht.sortKey-Wt.sortKey);for(const Ht of St){const Wt=Ht.state;if(Wt)if(v.terrain?v.terrain.setupElevationDraw(Wt.tile,Wt.program,{useDepthForOcclusion:Be.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Wt.labelPlaneMatrixInv}):v.setupDepthForOcclusion(Be.depthOcclusionForSymbolsAndCircles,Wt.program),Ke.activeTexture.set(De.TEXTURE0),Wt.atlasTexture&&Wt.atlasTexture.bind(Wt.atlasInterpolation,De.CLAMP_TO_EDGE,!0),Wt.atlasTextureIcon&&(Ke.activeTexture.set(De.TEXTURE1),Wt.atlasTextureIcon&&Wt.atlasTextureIcon.bind(Wt.atlasInterpolationIcon,De.CLAMP_TO_EDGE,!0)),Wt.renderWithShadows&&v.shadowRenderer.setupShadows(Wt.tile.tileID.toUnwrapped(),Wt.program,"vector-tile"),v.uploadCommonLightUniforms(v.context,Wt.program),Wt.hasHalo){const Dt=Wt.uniformValues;Dt.u_is_halo=1,Zv(Wt.buffers,Ht.segments,g,v,Wt.program,Wt.depthMode,A,N,Dt,2),Dt.u_is_halo=0}else{if(Wt.isSDF){const Dt=Wt.uniformValues;Wt.hasHalo&&(Dt.u_is_halo=1,Zv(Wt.buffers,Ht.segments,g,v,Wt.program,Wt.depthMode,A,N,Dt,1)),Dt.u_is_halo=0}Zv(Wt.buffers,Ht.segments,g,v,Wt.program,Wt.depthMode,A,N,Wt.uniformValues,1)}}}function Zv(v,d,g,w,A,N,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 ge=w.transform.zoom,pe=w.style.getBrightness?w.style.getBrightness():null,Ne=v.uboBinder.getConstantUniformValues(ge,pe);$.u_spp_fill_np_color=Ne.fill_np_color,$.u_spp_halo_np_color=Ne.halo_np_color,$.u_spp_opacity=Ne.opacity,$.u_spp_halo_width=Ne.halo_width,$.u_spp_halo_blur=Ne.halo_blur,$.u_spp_emissive_strength=Ne.emissive_strength,$.u_spp_occlusion_opacity=Ne.occlusion_opacity,$.u_spp_z_offset=Ne.z_offset;const Le=g.paint.get(v.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),xe=v.uboBinder.cachedHeader&&256&v.uboBinder.cachedHeader.dataDrivenMask&&Le==="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 ge of le){const pe=oe.get(ge);v.uboBinder&&v.uboBinder.bind(Y,A.program,ge),A.draw(w,te.TRIANGLES,N,L,F,Gr.disabled,$,g.id,v.layoutVertexBuffer,v.indexBuffer,pe,g.paint,w.transform.zoom,ie,ee,H)}}function Xv(v,d,g,w,A,N){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 ge=g.layout.get("line-cross-slope"),pe=ge!==void 0,Ne=ge<1,Le=A||v.colorModeForDrapableLayerRenderPass(F?$:null),xe=v.terrain&&v.terrain.renderingToTexture||N,Ze=xe?1:s.o.devicePixelRatio,ze=g.paint.get("line-dasharray"),Ke=ze.constantOr(1),De=g.layout.get("line-cap"),Be=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 bt;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"?bt=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,yr,Tr,Hr)=>{for(const sn of Dt){const en=d.getTile(sn);if(Qe&&!en.patternsLoaded())continue;const bn=en.getBucket(g);if(!bn||bn.elevationType!=="none"&&!Tr||bn.elevationType==="none"&&Tr)continue;v.prepareDrawTile();const Ur=[...Ar],wn=v.shadowRenderer,tn=bn.elevationType==="road"&&!!wn&&wn.enabled;let qn=[0,0,0];if(tn){const In=v.style.directionalLight,Ai=v.style.ambientLight;In&&Ai&&(qn=zu(v.style,In,Ai)),Ur.push("RENDER_SHADOWS","NORMAL_OFFSET")}const bi=bn.programConfigurations.get(g.id);let Zi=!1;if(ft&&en.imageAtlas){const In=s.dV.from(ft),Ai=In.getPrimary().scaleSelf(Ze).toString(),Js=en.imageAtlas.patternPositions.get(Ai),wo=In.getSecondary(),ha=wo?en.imageAtlas.patternPositions.get(wo.scaleSelf(Ze).toString()):null;Zi=!!Js&&!!ha,Js&&bi.setConstantPatternPositions(Js,ha)}xt>0&&(Zi||bi.getPatternTransitionVertexBuffer("line-pattern"))&&Ur.push("LINE_PATTERN_TRANSITION"),bn.elevationGroundScaleVertexBuffer&&Ur.push("ELEVATION_GROUND_SCALE");const ki=v.isTileAffectedByFog(sn),Jn=v.getOrCreateProgram(et,{config:bi,defines:Ur,overrideFog:ki});if(!Qe&&Be&&qe&&en.lineAtlas){const In=en.lineAtlas.getDash(Be,qe);In&&bi.setConstantPatternPositions(In)}tn&&wn.setupShadows(en.tileID.toUnwrapped(),Jn,"vector-tile");let[gn,yn]=g.paint.get("line-trim-offset");(qe==="round"||qe==="square")&&gn!==yn&&(gn===0&&(gn-=1),yn===1&&(yn+=1));const Ci=xe?sn.projMatrix:null,ns=te?1/bn.tileToMeter/s.aA(en,1,v.transform.zoom):1,ei=te?1/bn.tileToMeter/s.aA(en,1,Math.floor(v.transform.zoom)):1,on=Ke?g.paint._values["line-floorwidth"]:null;let Ki;if(on&&on.value.kind==="constant"){const In=bn.zoom;In in St||(St[In]=Math.max(.01,g.widthExpression().evaluate({zoom:In}))),Ki=on.value.value;const Ai=Math.floor(v.transform.zoom);on.value.value=St[In]*Math.pow(2,Ai-en.tileID.overscaledZ)}const wi=Qe?s.dW(v,en,g,Ci,Ze,ns,ei,[gn,yn],qn,xt):s.dX(v,en,g,Ci,bn.lineClipsArray.length,Ze,ns,ei,[gn,yn],qn);if(ot){const In=bn.gradients[g.id];let Ai=In.texture;if(g.gradientVersion!==In.version){let Js=256;if(g.stepInterpolant){const wo=d.getSource().maxzoom,ha=sn.canonical.z===wo?Math.ceil(1<{bt!=null&&(bt.value=Rt*H),Jn.draw(v,oe.TRIANGLES,Lr,In,Le,Gr.disabled,wi,g.id,bn.layoutVertexBuffer,bn.indexBuffer,bn.segments,g.paint,v.transform.zoom,bi,[bn.layoutVertexBuffer2,bn.patternVertexBuffer,bn.zOffsetVertexBuffer,bn.elevationGroundScaleVertexBuffer]),bt!=null&&(bt.value=Rt)};if(Ft&&!Tr){const In=v.stencilModeForClipping(sn).ref;In===0&&xe&&le.clear({stencil:0});const Ai={func:oe.EQUAL,mask:255};wi.u_alpha_discard_threshold=.8,Os(new Qr(Ai,In,255,oe.KEEP,oe.KEEP,oe.INVERT)),wi.u_alpha_discard_threshold=0,Os(new Qr(Ai,In,255,oe.KEEP,oe.KEEP,oe.KEEP))}else wi.u_alpha_discard_threshold=Ft&&Tr&&Hr?.8:0,Os(Tr?yr:v.stencilModeForClipping(sn));Ki!==void 0&&(on.value.value=Ki)}};let Ht=v.depthModeForSublayer(0,Ir.ReadOnly);const Wt=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,Ht,Qr.disabled,!1,!0)}if(g.hasElevatedBuckets){Y==="hd-road-markup"?ie||(Ht=Wt,gt.push("ELEVATED_ROADS")):(gt.push("ELEVATED"),Ht=Wt,pe&>.push(Ne?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),ee&>.push("ELEVATION_REFERENCE_SEA"));const Dt=Ft?v.stencilModeFor3D():Qr.disabled;v.forceTerrainMode=!0,rr(w,gt,Ht,Dt,!0,!0),Ft&&rr(w,gt,Ht,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 yh={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 QT(v,d){const g=1<=Rm?1:ie.pitch/Rm))),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 ge=oe.elevatedStructures;if(!ge)continue;const pe=oe.elevationBufferData.heightRange,Ne=QT(ie.toUnwrapped(),H),Le=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||ge.depthSegments.segments[0].primitiveLength===0)continue;xe=s0(Le,Ne,$,1,0),Ze=L,ze=ge.depthSegments,Ke=te}else if(A==="reset"){if(!pe||pe.min>=0||ge.maskSegments.segments[0].primitiveLength===0)continue;xe=s0(Le,Ne,0,0,1),Ze=F,ze=ge.maskSegments,Ke=te}else if(A==="geometry"){if(ge.depthSegments.segments[0].primitiveLength===0)continue;xe=s0(Le,Ne,$,1,0),Ze=L,ze=ge.depthSegments,Ke=ee}Ke.draw(v,N.TRIANGLES,Ze,Qr.disabled,Kr.disabled,Gr.disabled,xe,g.id,ge.vertexBuffer,ge.indexBuffer,ze,g.paint,v.transform.zoom)}}function d0(v,d,g,w){const{painter:A,sourceCache:N,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 ge=H;H!=="road"||d&&!Y||(ge="none");const pe=ge==="road",Ne=v.painter.shadowRenderer,Le=pe&&!!Ne&&Ne.enabled,xe=new Ir(A.context.gl.LEQUAL,Ir.ReadOnly,A.depthRangeFor3D);let Ze=[0,0,0];if(Le){const Be=A.style.directionalLight,qe=A.style.ambientLight;Be&&qe&&(Ze=zu(A.style,Be,qe))}const ze=ie&&ie.constantOr(1),Ke=A.terrain&&A.terrain.renderingToTexture,De=(Be,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=N.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 bt=gt.programConfigurations.get(L.id),St=A.isTileAffectedByFog(Ft),rr=[],Ht=[];pe&&(rr.push("ELEVATED_ROADS"),Ht.push(gt.elevatedLayoutVertexBuffer)),Le&&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),bt.updatePaintBuffers());let Wt=!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(),bn=Tr.patternPositions.get(sn),Ur=en?Tr.patternPositions.get(en.scaleSelf(s.o.devicePixelRatio).toString()):null;Wt=!!bn&&!!Ur,bn&&bt.setConstantPatternPositions(bn,Ur)}le>0&&(Wt||bt.getPatternTransitionVertexBuffer("fill-pattern"))&&rr.push("FILL_PATTERN_TRANSITION");const Dt=A.getOrCreateProgram(st,{config:bt,overrideFog:St,defines:rr}),Ar=A.translatePosMatrix(Ft.projMatrix,ot,L.paint.get("fill-translate"),L.paint.get("fill-translate-anchor"));Le&&Ne.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?bg(Ar,Lr,A,ot,Tr,Ze,le):gI(Ar,Lr,Tr,Ze)}else ft=gt.indexBuffer,Rt=gt.triangleSegments,Qe=ze?$v(Ar,Lr,A,ot,Ze,le):zv(Ar,Lr,Ze);A.uploadCommonUniforms(A.context,Dt,Ft.toUnwrapped());let yr=Be;(H==="road"&&!Y||H==="offset")&&(yr=xe),Dt.draw(A,xt,yr,w||A.stencilModeForClipping(Ft),$,Gr.disabled,Qe,L.id,gt.layoutVertexBuffer,ft,Rt,L.paint,A.transform.zoom,bt,Ht)}};A.renderPass===te&&De(A.depthModeForSublayer(1,A.renderPass==="opaque"?Ir.ReadWrite:Ir.ReadOnly),!1),ge==="none"&&A.renderPass==="translucent"&&L.paint.get("fill-antialias")&&De(A.depthModeForSublayer(L.getPaintProperty("fill-outline-color")?2:0,Ir.ReadOnly),!0)}function $m(v,d,g,w,A,N,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"),ge=v.style.enable3dLights(),pe=g.paint.get(ge&&!le?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Ne=[g.paint.get("fill-extrusion-ambient-occlusion-intensity"),pe],Le=g.layout.get("fill-extrusion-edge-radius"),xe=Le>0&&!g.paint.get("fill-extrusion-rounded-roof"),Ze=xe?0:Le,ze=Y.projection.name==="globe"?s.e1():0,Ke=Y.projection.name==="globe",De=Ke?s.al(Y.zoom):0,Be=[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=Da(v,g.paint.get("fill-extrusion-cutoff-fade-range")),et=g.paint.get("fill-extrusion-front-cutoff"),gt=Qv(Y.pitch,et,!!v.terrain),bt=gt[2]<1;bt&&(v.maxFrontCutoffRawStart=Math.max(v.maxFrontCutoffRawStart,et[0]));const St=[];let rr;Ke&&St.push("PROJECTION_GLOBE_VIEW"),Ne[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"),bt&&St.push("RENDER_FRONT_CUTOFF"),ft&&St.push("RENDER_WALL_MODE");const Ht=v.renderPass==="shadow",Wt=v.shadowRenderer,Dt=Ht&&!!Wt,Ar=Ht?Gr.disabled:Gr.backCCW;v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!0);let Lr=[0,0,0];if(Wt){const Hr=v.style.directionalLight,sn=v.style.ambientLight;Hr&&sn&&(Lr=zu(v.style,Hr,sn)),Ht||(St.push("RENDER_SHADOWS"),Wt.useNormalOffset&&St.push("NORMAL_OFFSET")),rr=St.concat(["SHADOWS_SINGLE_CASCADE"])}const yr=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 bn=!1;Wt&&(bn=Wt.getMaxCascadeForTile(Hr.toUnwrapped())===0);const Ur=v.isTileAffectedByFog(Hr),wn=en.programConfigurations.get(g.id);let tn=!1;if(ie&&sn.imageAtlas){const yn=sn.imageAtlas,Ci=s.dV.from(ie),ns=Ci.getPrimary().scaleSelf(s.o.devicePixelRatio).toString(),ei=Ci.getSecondary(),on=yn.patternPositions.get(ns),Ki=ei?yn.patternPositions.get(ei.scaleSelf(s.o.devicePixelRatio).toString()):null;tn=!!on&&!!Ki,on&&wn.setConstantPatternPositions(on,Ki)}ee>0&&(tn||wn.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&St.push("FILL_EXTRUSION_PATTERN_TRANSITION");const qn=v.getOrCreateProgram(yr,{config:wn,defines:bn?rr:St,overrideFog:Ur});if(v.terrain&&v.terrain.setupElevationDraw(sn,qn,{useMeterToDem:!0}),!en.centroidVertexBuffer){const yn=qn.getAttributeLocation(H,"a_centroid_pos");yn!==-1&&H.vertexAttribI4ui(yn,0,0,0,0)}!Ht&&Wt&&Wt.setupShadows(sn.tileID.toUnwrapped(),qn,"vector-tile"),le&&(v.context.activeTexture.set(H.TEXTURE0),sn.imageAtlasTexture&&sn.imageAtlasTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),wn.updatePaintBuffers());const bi=g.paint.get("fill-extrusion-vertical-gradient"),Zi=1/en.tileToMeter;let ki;if(Ht&&Wt){if(Jv(sn.tileID,en.maxHeight,v))continue;const yn=Wt.calculateShadowPassMatrixFromTile(sn.tileID.toUnwrapped());ki=m5(yn,Ze,Zi,xt,Rt,Ft)}else{const yn=v.translatePosMatrix(Hr.expandedProjMatrix,sn,g.paint.get("fill-extrusion-translate"),g.paint.get("fill-extrusion-translate-anchor")),Ci=Y.projection.createInversionMatrix(Y,Hr.canonical);ki=le?p5(yn,v,bi,oe,Ne,Ze,Zi,Hr,sn,ze,Rt,Ft,De,Be,Ci,st,xt,ee):pI(yn,v,bi,oe,Ne,Ze,Zi,Hr,ze,Rt,Ft,De,Be,Ci,st,xt,Qe,Lr,gt)}v.uploadCommonUniforms($,qn,Hr.toUnwrapped(),null,ot);let Jn=en.segments;if(Y.projection.name==="mercator"&&!Ht&&(Jn=en.getVisibleSegments(sn.tileID,v.terrain,v.transform.getFrustum(0)),!Jn.get().length))continue;if(Tr)if(Ht)for(const yn of Jn.get())Tr.numRenderedVerticesInShadowPass+=yn.primitiveLength;else for(const yn of Jn.get())Tr.numRenderedVerticesInTransparentPass+=yn.primitiveLength;const gn=[];(v.terrain||F)&&gn.push(en.centroidVertexBuffer),Ke&&gn.push(en.layoutVertexExtBuffer),ft&&gn.push(en.wallVertexBuffer),qn.draw(v,$.gl.TRIANGLES,A,N,L,Ar,ki,g.id,en.layoutVertexBuffer,en.indexBuffer,Jn,g.paint,v.transform.zoom,wn,gn)}v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!1)}class JT{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Qv(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)),N=A*A*(3-2*A);return[-.5*(1-N)+d[0]*N,d[1],d[2]]}function kd(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie,le,oe,ge,pe,Ne,Le,xe){const Ze=d.context,ze=Ze.gl,Ke=d.transform,De=d.transform.zoom,Be=[],qe=v.translate,st=v.translateAnchor,Qe=v.edgeRadius,xt=Da(d,v.cutoffFadeRange);Y==="clear"?(Be.push("CLEAR_SUBPASS"),Le&&(Be.push("CLEAR_FROM_TEXTURE"),Ze.activeTexture.set(ze.TEXTURE0),Le.bind(ze.LINEAR,ze.CLAMP_TO_EDGE))):Y==="sdf"?Be.push("SDF_SUBPASS"):Y==="emissive"&&(Be.push("USE_MRT1"),Ze.activeTexture.set(ze.TEXTURE0),Le.bind(ze.LINEAR,ze.CLAMP_TO_EDGE)),pe&&Be.push("HAS_CENTROID"),xt.shouldRenderCutoff&&Be.push("RENDER_CUTOFF");const ft=(Rt,Ft,ot,et,gt)=>{let bt=Be;Ft.groundRadiusBuffer!=null&&(bt=Be.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const St=Ft.programConfigurations.get(w.id),rr=d.isTileAffectedByFog(Rt),Ht=d.getOrCreateProgram("fillExtrusionGroundEffect",{config:St,defines:bt,overrideFog:rr}),Wt=((Ar,Lr,yr,Tr,Hr,sn,en,bn,Ur,wn,tn)=>({u_matrix:Lr,u_opacity:yr,u_ao_pass:Tr?1:0,u_meter_to_tile:Hr,u_ao:sn,u_flood_light_intensity:en,u_flood_light_color:bn,u_attenuation:Ur,u_edge_radius:wn,u_fb:0,u_fb_size:tn,u_dynamic_offset:1}))(0,et,te,H,gt,[ee,ie*gt],le,oe,ge,De>=17?0:Qe*gt,Le?Le.size[0]:0),Dt=[];pe&&Dt.push(Ft.hiddenByLandmarkVertexBuffer),Ft.groundRadiusBuffer!=null&&Dt.push(Ft.groundRadiusBuffer),d.uploadCommonUniforms(Ze,Ht,Rt.toUnwrapped(),null,xt),Ht.draw(d,Ze.gl.TRIANGLES,N,L,F,$,Wt,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 bt=d.translatePosMatrix(Rt.projMatrix,Ft,qe,st),St=et.getDefaultSegment();ft(Rt,et,St,bt,gt)}if(Ne)for(let bt=0;bt<4;bt++){const St=s.d$[bt](Rt),rr=g.getTile(St);if(!rr)continue;const Ht=rr.getBucket(w);if(!Ht||Ht.projection.name!==Ke.projection.name||!Ht.groundEffect||Ht.groundEffect&&!Ht.groundEffect.hasData())continue;const Wt=Ht.groundEffect;let Dt,Ar;bt===0?(Dt=[-s.an,0,0],Ar=1):bt===1?(Dt=[s.an,0,0],Ar=0):bt===2?(Dt=[0,-s.an,0],Ar=3):(Dt=[0,s.an,0],Ar=2);const Lr=Wt.regionSegments[Ar];if(!Lr)continue;const yr=new Float32Array(16);s.bx(yr,Rt.projMatrix,Dt),ft(Rt,Wt,Lr,d.translatePosMatrix(yr,Ft,qe,st),gt)}}}function jI(v,d,g,w,A,N,L){w.centroidVertexArray.length===0&&w.createCentroidsBuffer();const F=N?N.findDEMTileFor(g):null;if(!(F&&F.dem||L))return;N&&F&&F.dem&&w.selfDEMTileTimestamp!==F.dem._timestamp&&(w.borderDoneWithNeighborZ=[-1,-1,-1,-1],w.selfDEMTileTimestamp=F.dem._timestamp);const $=(pe,Ne)=>{(pe.flags|Ne.flags)&s.e3?(pe.flags|=s.e3,Ne.flags|=s.e3):(pe.flags&=~s.e3,Ne.flags&=~s.e3)},H=pe=>new s.P(Math.ceil((pe+s.e4)*s.e5),0),Y=(pe,Ne,Le)=>{const xe=Math.ceil((pe+s.e4)*s.e5),Ze=Math.floor(Math.max(0,Math.min(s.an-1,Le))/4);return new s.P(xe,Ze<<5|(3&Ne)<<3|7)},te=pe=>{const Ne=d.getSource().minzoom,Le=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,Ne.min.y),ee[1]=Math.max(pe.max.y,Ne.max.y),ee[2]=s.an-Ne.min.x>pe.max.x?Ne.min.x-s.an:pe.max.x,ee),le=(pe,Ne)=>(ee[0]=Math.min(pe.min.x,Ne.min.x),ee[1]=Math.max(pe.max.x,Ne.max.x),ee[2]=s.an-Ne.min.y>pe.max.y?Ne.min.y-s.an:pe.max.y,ee),oe=[(pe,Ne)=>ie(pe,Ne),(pe,Ne)=>ie(Ne,pe),(pe,Ne)=>le(pe,Ne),(pe,Ne)=>le(Ne,pe)],ge=(pe,Ne,Le,xe,Ze,ze,Ke)=>{if(!N)return 0;const De=[[ze?Le:pe,ze?pe:Le,0],[ze?Le:Ne,ze?Ne:Le,0]],Be=Ke<0?s.an+Ke:Ke,qe=[ze?Be:(pe+Ne)/2,ze?(pe+Ne)/2:Be,0];return Le===0&&Ke<0||Le!==0&&Ke>0?N.getForTilePoints(Ze,[qe],!0,xe):De.push(qe),N.getForTilePoints(g,De,!0,F),Math.max(De[0][2],De[1][2],qe[2])/N.exaggeration()};for(let pe=0;pe<4;pe++){const Ne=w.borderFeatureIndices[pe];if(Ne.length===0)continue;const Le=s.d$[pe](g),xe=te(Le);if(!(xe&&xe instanceof s.e0))continue;const Ze=N?N.findDEMTileFor(Le):null;if(!(Ze&&Ze.dem||L)||(N&&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 Be=0;if(w.canonical.z!==xe.canonical.z){for(const xt of Ne)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 Ht=0;if(Ze&&Ze.dem&&!rr){const Wt=oe[pe](Rt,et),Dt=pe%2?s.an-1:0;Ht=ge(Wt[0],Math.min(s.an-1,Wt[1]),Dt,Ze,Le,pe<2,Wt[2])}Rt.centroidXY=Y(Ht,pe,St),et.centroidXY=Y(Ht,ze,St)}if(w.writeCentroidToBuffer(Rt),xe.writeCentroidToBuffer(et),ft.buildingId!==void 0){for(const Ht of w.centroidData)Ht.buildingId===ft.buildingId&&Ht!==Rt&&(Ht.centroidXY=Rt.centroidXY,w.writeCentroidToBuffer(Ht));for(const Ht of xe.centroidData)Ht.buildingId===ft.buildingId&&Ht!==et&&(Ht.centroidXY=et.centroidXY,xe.writeCentroidToBuffer(Ht))}}for(const xt of Ne){if(st.has(xt))continue;const ft=w.featuresOnBorder[xt],Rt=w.centroidData[ft.centroidDataIndex],Ft=ft.borders[pe];let ot;for(;BeFt[0]+3||et[0]>Ft[0]-3)break;xe.showCentroid(ot),Be++}if(ot&&BeFt[1]-3||(gt++,++Be===De.length))break;ot=xe.featuresOnBorder[De[Be]]}for(;et=De.length){w.showCentroid(ft);continue}ot=xe.featuresOnBorder[De[et]];let bt=!1;if(gt>=1){const Ht=ot.borders[ze];Math.abs(Ft[0]-Ht[0])<3&&Math.abs(Ft[1]-Ht[1])<3&&(gt=1,bt=!0,Be=et+1)}else if(gt===0){w.showCentroid(ft);continue}const St=xe.centroidData[ot.centroidDataIndex];L&&bt&&$(Rt,St);const rr=ft.intersectsCount()>1||ot.intersectsCount()>1;if(gt>1)Be=et,Rt.centroidXY=St.centroidXY=new s.P(0,0);else if(Ze&&Ze.dem&&!rr){const Ht=oe[pe](Rt,St),Wt=pe%2?s.an-1:0,Dt=ge(Ht[0],Math.min(s.an-1,Ht[1]),Wt,Ze,Le,pe<2,Ht[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 kI=[1,0,0],CI=[0,1,0],eE=[0,0,1];function Jv(v,d,g){const w=g.transform,A=g.shadowRenderer;if(!A)return!0;const N=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(N,F,L,H);if(!Y)return!1;const te=[kI,CI,eE,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 h0(v){const{painter:d,source:g,layer:w,coords:A}=v;let N=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=Da(d,w.paint.get("building-cutoff-fade-range"));te.shouldRenderCutoff&&(N=N.concat("RENDER_CUTOFF"));const ee=w.paint.get("building-front-cutoff"),ie=ee[2]<1&&!d.terrain,le=Qv(d.transform.pitch,ee,!!d.terrain);ie&&(N=N.concat("RENDER_FRONT_CUTOFF"),d.maxFrontCutoffRawStart=Math.max(d.maxFrontCutoffRawStart,ee[0])),v.floodLightIntensity>0&&(N=N.concat("FLOOD_LIGHT"));for(const oe of A){const ge=g.getTile(oe),pe=ge.getBucket(w);if(!pe)continue;H&&H.getMaxCascadeForTile(oe.toUnwrapped())===0&&(N=N.concat("SHADOWS_SINGLE_CASCADE"));const Ne=pe.programConfigurations.get(w.id);let Le,xe,Ze,ze=d.translatePosMatrix(oe.expandedProjMatrix,ge,[0,0],"map");if(ze=s.cC(s.bb(),ze,[1,1,v.verticalScale]),F&&H){if(Jv(ge.tileID,pe.maxHeight*Y,d))continue;let De=H.calculateShadowPassMatrixFromTile(ge.tileID.toUnwrapped());De=s.cC(s.bb(),De,[1,1,v.verticalScale]),Ze=qv(De),Le=xe=d.getOrCreateProgram("buildingDepth",{config:Ne,defines:N,overrideFog:!1})}else if($)Le=xe=d.getOrCreateProgram("buildingBloom",{config:Ne,defines:N,overrideFog:!1}),Ze=Vv(ze);else{const De=d.transform.calculatePosMatrix(oe.toUnwrapped(),d.transform.worldSize);s.cC(De,De,[1,1,v.verticalScale]);const Be=s.bb();s.cC(Be,De,[1,-1,1/Y]),s.b7(Be,Be),s.e6(Be,Be);const qe=d.transform.getFreeCameraOptions().position,st=1<{if($){const qe=De.entranceBloom;Be.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,Ne,[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])),Be.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,Ne,st)}};d.uploadCommonUniforms(L,xe,oe.toUnwrapped(),null,te),pe.buildingWithoutFacade&&Ke(pe.buildingWithoutFacade,xe),pe.buildingWithFacade&&(Le!==xe&&d.uploadCommonUniforms(L,Le,oe.toUnwrapped(),null,te),Ke(pe.buildingWithFacade,Le))}}function tE(v,d,g,w,A,N,L,F,$,H,Y,te,ee,ie){const le=v.context.gl,oe=v.depthModeForSublayer(1,Ir.ReadOnly,le.LEQUAL,!0),ge=.1*(1-(pe=Y))+3*pe;var pe;const Ne=v._showOverdrawInspector,Le=te,xe=new JT;Ne||kd(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",N,L,F,$,H,ge,Le,!1,void 0);{const Ze=Ne?Qr.disabled:new Qr({func:le.EQUAL,mask:255},255,255,le.KEEP,le.DECR,le.DECR),ze=Ne?v.colorModeForRenderPass():new Kr([le.ONE_MINUS_DST_ALPHA,le.DST_ALPHA,le.ONE,le.ONE],s.aq.transparent,[!0,!0,!0,!0]);kd(xe,v,d,g,w,oe,Ze,ze,Gr.disabled,A,"color",N,L,F,$,H,ge,Le,!1,void 0)}}function rE(v){return[v[0]*s.e7,v[1]*s.e7,v[2]*s.e7,0]}function eb(v,d,g,w,A,N,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,ge=A.paint.get("raster-resampling")==="nearest"?oe.NEAREST:oe.LINEAR,pe=g.colorModeForDrapableLayerRenderPass(N),Ne=L.defines;Ne.push("GLOBE_POLES");const Le=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(ge,oe.CLAMP_TO_EDGE),le.activeTexture.set(oe.TEXTURE1),ee.bind(ge,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,Be]=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=rE(L.mix),xt=((Rt,Ft,ot,et,gt,bt,St,rr,Ht,Wt,Dt,Ar,Lr,yr)=>bI(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],Ht,2,Dt,Ar,Lr,1,0,yr))(g,xe,Ze,ie,s.al(g.transform.zoom),0,A,0,qe,0,Qe,L.offset,L.range,N),ft=g.getOrCreateProgram("raster",{defines:Ne});g.uploadCommonUniforms(le,ft,null),ft.draw(g,oe.TRIANGLES,Le,$,pe,F,xt,A.id,st,De,Be)}function nE(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,N=d+A;return[d,g,(N-A-d)/w,(N-d)/w]}function II(v,d,g,w){if(v)return d instanceof jm&&v instanceof km?d.getTextureDescriptor(v,g,!0):{texture:v.texture,mix:rE(w.mix),offset:w.offset,buffer:0,tileSize:1}}var iE=s.e8([{name:"a_index",type:"Int16",components:1}]);class NI{constructor(d,g,w,A){const N={width:w[0],height:w[1],data:null},L=d.gl;this.targetColorTexture=new s.T(d,N,L.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new s.T(d,N,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 N=new s.e9;N.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*N/(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 ge=Ir.disabled,pe=Qr.disabled,Ne=v.colorModeForRenderPass(),Le="$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,ge,pe,Ne,Gr.disabled,a0(ee,w.toPremultipliedRenderColor(null)),Le,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,Be=oe._tileDebugTextBuffer||v.debugBuffer,qe=oe._tileDebugTextIndexBuffer||v.quadTriangleIndexBuffer,st=oe._tileDebugTextSegments||v.debugSegments;le.draw(v,H.TRIANGLES,ge,pe,Kr.alphaBlended,Gr.disabled,a0(ee,s.aq.transparent.toPremultipliedRenderColor(null),De),Le,Be,qe,st,null,null,null,[oe._globeTileDebugTextBuffer])}function RI(v,d,g,w){tb(v,0,d+g/2,v.transform.width,g,w)}function cE(v,d,g,w){tb(v,d-g/2,0,g,v.transform.height,w)}function tb(v,d,g,w,A,N){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:N}),F.disable(F.SCISSOR_TEST)}const b5=s.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:cc}=b5;function Cd(v,d,g,w){v.emplaceBack(d,g,w)}class Qo{constructor(d){this.vertexArray=new s.ee,this.indices=new s.dC,Cd(this.vertexArray,-1,-1,1),Cd(this.vertexArray,1,-1,1),Cd(this.vertexArray,-1,1,1),Cd(this.vertexArray,1,1,1),Cd(this.vertexArray,-1,-1,-1),Cd(this.vertexArray,1,-1,-1),Cd(this.vertexArray,-1,1,-1),Cd(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,cc),this.indexBuffer=d.createIndexBuffer(this.indices),this.segment=s.dy.simpleSegment(0,0,36,12)}}function jc(v,d,g,w,A,N){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+N,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 LI=s.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class uE{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,LI.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 dE=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 hE{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class DI{constructor(d){this.colorModeAlphaBlendedWriteRGB=new Kr([1,Cs,1,Cs],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 hE,this.updateNeeded=!0}update(d){const g=d.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new uE(g);const w=this.params.sizeRange,A=this.params.intensityRange,N=function(Y){const te=s.em(30),ee=[];for(let ie=0;ie{const De=N.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ke&&De.push("ALPHA_PASS");const Be=d.getOrCreateProgram("globeAtmosphere",{defines:De}),qe=((Qe,xt,ft,Rt,Ft,ot,et,gt,bt,St,rr,Ht)=>({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:bt.toArray01(),u_space_color:St.toArray01(),u_temporal_offset:rr,u_horizon_angle:Ht}))(N.frustumCorners.TL,N.frustumCorners.TR,N.frustumCorners.BR,N.frustumCorners.BL,N.frustumCorners.horizon,F,ge,Y,ee,le,Ne,Ze);d.uploadCommonUniforms(w,Be);const st=this.atmosphereBuffer;st&&Be.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,N=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=(ge=ie,pe=le,Ne=w,{u_matrix:Float32Array.from(Y),u_up:ge,u_right:pe,u_intensity_multiplier:Ne});var ge,pe,Ne;d.uploadCommonUniforms(A,F),this.starsVx&&this.starsIdx&&F.draw(d,N.TRIANGLES,Ir.disabled,Qr.disabled,this.colorModeAlphaBlendedWriteRGB,Gr.disabled,oe,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class xh{constructor(){this.visibleTiles=[]}updateBorders(d,g){const w=[],A=[],N=d._getRenderableCoordinates(!1,!0);for(const $ of N){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 MI(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 ri(v,d,g,w,A){const N=g.material,L=w.context,{baseColorTexture:F,metallicRoughnessTexture:$}=N.pbrMetallicRoughness,{normalTexture:H,occlusionTexture:Y,emissionTexture:te}=N;function ee(le,oe,ge){if(le&&(v.push(oe),L.activeTexture.set(L.gl.TEXTURE0+ge),le.gfxTexture)){const{minFilter:pe,magFilter:Ne,wrapS:Le,wrapT:xe}=le.sampler;le.gfxTexture.bindExtraParam(pe,Ne,Le,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)),N.alphaMode!=="OPAQUE"&&N.alphaMode!=="MASK"||v.push("UNPREMULT_TEXTURE_IN_SHADER"),N.defined||v.push("DIFFUSE_SHADED");const ie=w.shadowRenderer;ie&&(v.push("RENDER_SHADOWS"),ie.useNormalOffset&&v.push("NORMAL_OFFSET"))}function Tg(v,d,g,w,A,N){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 ge=g.paint.get("model-color-use-theme").constantOr("default")==="none",pe=g.paint.get("model-emissive-strength").constantOr(0),Ne=Bm(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),Le={defines:[]},xe=[],Ze=d.shadowRenderer;Ze&&(Ze.useNormalOffset=!1),ri(Le.defines,xe,Y,d,ge?null:g.lut);let ze=null;if(ie){const Be=MI(v.nodeModelMatrix,d.transform);if(ze=new Float32Array(Be),H.projection.name!=="globe"){const qe=Y.aabb.min,st=Y.aabb.max,[Qe,xt]=ie.getOpacityForBounds(Be,qe[0],qe[1],st[0],st[1]);Le.overrideFog=Qe>=Ln||xt>=Ln}}const Ke=Da(d,g.paint.get("model-cutoff-fade-range"));Ke.shouldRenderCutoff&&Le.defines.push("RENDER_CUTOFF");const De=d.getOrCreateProgram("model",Le);d.uploadCommonUniforms(F,De,null,ze,Ke),d.renderPass!=="shadow"&&Ze&&Ze.setupShadowsFromMatrix(v.nodeModelMatrix,De),De.draw(d,F.gl.TRIANGLES,$,A,N,Y.material.doubleSided?Gr.disabled:Gr.backCCW,Ne,g.id,Y.vertexBuffer,Y.indexBuffer,Y.segments,g.paint,d.transform.zoom,void 0,xe)}function rb(v,d){return v.style._importedAsBasemap?"basemap":d.scope}function nb(v,d,g,w,A,N,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 ge=s.ah([],le.centroid,ie);!Y.isOrthographic&&ge[2]<=0||N.push({mesh:le,depth:ge[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)nb(v,le,g,w,A,N,L,F,$,H)}function Eg(v,d,g,w){const A=g.shadowRenderer;if(!A)return;const N=A.getShadowPassDepthMode(),L=A.calculateShadowPassMatrixFromMatrix(d),F=ZT(L);g.getOrCreateProgram("modelDepth").draw(g,g.context.gl.TRIANGLES,N,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 fE(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 ge=new s.dC;ge.reserve(le.length);for(let qe=0;qe0){const ee=N.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,N,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 rs(v,d,g,w,A,N,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(N),ee=v.transform.projection.name==="globe";if(g.meshes)for(const ie of g.meshes){const le=ee?[]:["MODEL_POSITION_ON_GPU"],oe=[];let ge,pe,Ne;const Le=!ee&&w.instancedDataArray.length>20;Le&&le.push("INSTANCED_ARRAYS");const xe=Da(v,d.paint.get("model-cutoff-fade-range"));if(xe.shouldRenderCutoff&&le.push("RENDER_CUTOFF"),$&&H)ge=v.getOrCreateProgram("modelDepth",{defines:le}),pe=ZT(L.shadowTileMatrix,L.shadowTileMatrix,Float32Array.from(g.globalMatrix)),Ne=Kr.disabled;else{ri(le,oe,ie,v,d.paint.get("model-color-use-theme").constantOr("default")==="none"?null:d.lut),ge=v.getOrCreateProgram("model",{defines:le,overrideFog:te});const ze=ie.material,Ke=ze.pbrMetallicRoughness,De=d.paint.get("model-opacity").constantOr(1),Be=d.paint.get("model-emissive-strength").constantOr(0);pe=Bm(N.expandedProjMatrix,Float32Array.from(g.globalMatrix),new Float32Array(16),null,v,De,Ke.baseColorFactor,ze.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,ze,Be,d,A),H&&(L.shadowUniformsInitialized?ge.setShadowUniformValues(F,H.getShadowUniformValues()):(H.setupShadows(N.toUnwrapped(),ge,"model-tile"),L.shadowUniformsInitialized=!0)),Ne=xe.shouldRenderCutoff||De<1||ze.alphaMode!=="OPAQUE"?Kr.alphaBlended:Kr.unblended}v.uploadCommonUniforms(F,ge,N.toUnwrapped(),null,xe);const Ze=ie.material.doubleSided?Gr.disabled:Gr.backCCW;if(Le)oe.push(w.instancedDataBuffer),ge.draw(v,F.gl.TRIANGLES,Y,Qr.disabled,Ne,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:$,N[0]=g.max[0],L=s.aE(s.bE(),N,A),F=L[1]$[1]?L:$,N[1]=g.min[1],L=s.aE(s.bE(),N,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,ge=(Ne,Le,xe)=>(1-xe)*Ne+xe*Le,pe=s.aC(ge(1,te,oe),te,1);return ge(1,pe,s.aC((d.pitch-20)/20,0,1))}class sb{}class FI{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,N=A.getBufferParameter(A.ELEMENT_ARRAY_BUFFER,A.BUFFER_SIZE),L=new ArrayBuffer(N),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 BI{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const jg=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 zI{constructor(d){this.revealStart=11,this.revealRange=2}}const w5=s.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class $I{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,w5.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:(N={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:N.vignetteColor};w.draw(d,d.context.gl.TRIANGLES,Ir.disabled,Qr.disabled,Kr.alphaBlended,Gr.disabled,L,"vignette",this.vignetteVx,this.vignetteIdx,A)}var N}}class ab{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(d,g){const w=d.getFreeCameraOptions().position,A=w.toAltitude(),N=w.toLngLat(),L=s.ap(N.lng),F=s.ap(N.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 ob(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 gE(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=gE(this.particlesCount),A=new s.eE,N=new s.dC;let L=0;const F=s.em(1323123451230);for(let $=0;$w)return;const A=vh(0,1,g.revealStart,g.revealStart+g.revealRange,w);if(!this.particlesVx||!this.particlesIdx)return;const N=structuredClone(this._params);let L=[-N.direction.x,N.direction.y,-100];s.ay(L,L);const F=structuredClone(this._vignetteParams);F.strength*=A,N.overrideStyleParameters||(N.intensity=d.style.rain.state.density,N.timeFactor=d.style.rain.state.intensity,N.color=structuredClone(d.style.rain.state.color),L=structuredClone(d.style.rain.state.direction),N.screenThinning.intensity=d.style.rain.state.centerThinning,N.dropletSizeX=d.style.rain.state.dropletSize[0],N.dropletSizeYScale=d.style.rain.state.dropletSize[1]/d.style.rain.state.dropletSize[0],N.distortionStrength=100*d.style.rain.state.distortionStrength,F.strength=1,F.color=structuredClone(d.style.rain.state.vignetteColor));const $=this.updateOnRender(d,N.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)),N.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=[N.color.r,N.color.g,N.color.b,N.color.a],le=(oe,ge)=>{const pe=ob(this._movement.getPosition(),oe),Ne=N.dropletSizeX,Le=N.dropletSizeX*N.dropletSizeYScale,xe=d.width/2,Ze=d.height/2,ze=vh(0,N.screenThinning.start,0,1,N.screenThinning.intensity),Ke=vh(.001,N.screenThinning.range,0,1,N.screenThinning.intensity),De=vh(0,N.screenThinning.particleOffset,0,1,N.screenThinning.intensity),Be=(qe={modelview:$.modelviewMatrix,projection:$.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:pe,velocityConeAperture:N.velocityConeAperture,velocity:N.velocity,boxSize:oe,rainDropletSize:[Ne,Le],distortionStrength:N.distortionStrength,rainDirection:L,color:ie,screenSize:[te.width,te.height],thinningCenterPos:[xe,Ze],thinningShape:[ze,Ke,Math.pow(10,N.screenThinning.fadePower)],thinningAffectedRatio:N.screenThinning.affectedRatio,thinningParticleOffset:De,shapeDirectionalPower:N.shapeDirPower,shapeNormalPower:N.shapeNormalPower,mode:ge?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(N.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,Be,"rain_particles",this.particlesVx,this.particlesIdx,Qe)};N.distortionStrength>0&&le(N.boxSize,!0),le(N.boxSize,!1),this._vignette.draw(d,F)}}const qm=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 UI extends f0{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 zI("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=gE(this.particlesCount),A=new s.eF,N=new s.dC;let L=0;const F=s.em(1323123451230);for(let $=0;$L)return;const F=vh(0,1,N.revealStart,N.revealStart+N.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 ge=ob(this._movement.getPosition(),ie),pe=te.width/2,Ne=te.height/2,Le=vh(0,oe.screenThinning.start,0,1,oe.screenThinning.intensity),xe=vh(.001,oe.screenThinning.range,0,1,oe.screenThinning.intensity),Ze=vh(0,oe.screenThinning.particleOffset,0,1,oe.screenThinning.intensity),ze=(Ke={modelview:$.modelviewMatrix,projection:$.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ge,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,Ne],thinningShape:[Le,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),Be=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,Be)})(g.boxSize,0,g),this._vignette.draw(d,A)}}const VI={symbol:function(v,d,g,w,A){if(v.renderPass!=="translucent")return;const N=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,ge,pe,Ne,Le){const xe=ie.transform,Ze=ge==="map",ze=pe==="map";for(const Ke of ee){const De=oe.getTile(Ke),Be=De.getBucket(le);if(!Be||!Be.text||!Be.text.segments.get().length)continue;const qe=s.bj(Be.textSizeData,xe.zoom,Le),st=Cm(Ke,Be.getProjection(),xe),Qe=xe.calculatePixelsToTileUnitsMatrix(De),xt=mf(st,De.tileID.canonical,ze,Ze,xe,Be.getProjection(),Qe),ft=Be.hasIconTextFit()&&Be.hasIconData();qe&&AI(Be,Ze,ze,Ne,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)?Yv(v,d,g,w,N,L):(Y&&Yv(v,d,g,w,N,L,{onlyIcons:!0}),te&&Yv(v,d,g,w,N,L,{onlyText:!0})),d.map.showCollisionBoxes&&(br(v,d,g,w,g.paint.get("text-translate"),g.paint.get("text-translate-anchor"),!0),br(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"),N=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&&(N.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),ge=ie==="none"||ee?le:oe,pe=Qr.disabled,Ne=v.colorModeForDrapableLayerRenderPass($),Le=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:Be,layoutVertexBuffer:qe,dynamicBuffers:st,indexBuffer:Qe,uniformValues:xt,tile:ft}=Ke.state,Rt=Ke.segments;v.terrain&&v.terrain.setupElevationDraw(ft,Be,ze),v.uploadCommonUniforms(H,Be,ft.tileID.toUnwrapped()),Be.draw(v,Y.TRIANGLES,ge,pe,Ne,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,N=A.gl,L=Qr.disabled,F=new Kr([N.ONE,N.ONE,N.ONE,N.ONE],s.aq.transparent,[!0,!0,!0,!0]),$=v.transform.projection.name==="globe"?.5:.25;g.heatmapFbo=l0.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,N),N.id,A.viewportBuffer,A.quadTriangleIndexBuffer,A.viewportSegments,N.paint,A.transform.zoom)}(v,g))},line:function(v,d,g,w){const A=g.paint.get("line-opacity"),N=g.paint.get("line-width");if(A.constantOr(1)===0||N.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,ge=F.emissiveMode==="mrt-fallback";H.lineBlendDrapeFbo=l0.createWithTexture(ee,H.lineBlendDrapeFbo,le.drapeBufferSize[0],le.drapeBufferSize[1],!0),H.lineBlendDrapeStencil=H.lineBlendDrapeFbo._stencilRbo,ge&&ie.drawBuffers([ie.COLOR_ATTACHMENT0]),ee.clear({color:yh[te].clearColor,depth:1,stencil:0});const pe=F.currentStencilSource,Ne=F._tileClippingMaskIDs,Le=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1;const xe=F._terrain;F._terrain=null,F._renderTileClippingMasks(H,$,Y),Xv(F,$,H,Y,yh[te].colorMode,!0),F._terrain=xe,F.currentStencilSource=pe,F._tileClippingMaskIDs=Ne,F.nextStencilID=Le,ee.bindFramebuffer.set(oe),ge&&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),Be=te==="additive"?F.colorModeForDrapableLayerRenderPass(De):yh[te].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,ie.TRIANGLES,Ir.disabled,Qr.disabled,Be,Gr.disabled,Uv(0,Ke,yh[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=l0.createWithTexture(ee,H.lineBlendFbo,ie,le,!0),H.lineBlendStencil=H.lineBlendFbo._stencilRbo,ee.clear({color:yh[te].clearColor,depth:1,stencil:0});const oe=F.currentStencilSource,ge=F._tileClippingMaskIDs,pe=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1,F._renderTileClippingMasks(H,$,Y);const Ne=F.renderPass;F.renderPass="translucent",Xv(F,$,H,Y,yh[te].colorMode),F.renderPass=Ne,F.currentStencilSource=oe,F._tileClippingMaskIDs=ge,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)):yh[H].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,te.TRIANGLES,Ir.disabled,Qr.disabled,le,Gr.disabled,Uv(0,ie,yh[H].compositeUniformValue),$.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,$.paint,F.transform.zoom)}(v,g,L):void 0;v.renderPass==="translucent"&&Xv(v,d,g,w)},fill:function(v,d,g,w){const A=g.paint.get("fill-color"),N=g.paint.get("fill-opacity");if(N.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&&N.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:ge,layer:pe,coords:Ne}=le,Le=oe.context.gl,xe=le.painter.shadowRenderer;for(const Ze of Ne){const ze=ge.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 Be=Ke.bufferData.programConfigurations.get(pe.id),qe=oe.isTileAffectedByFog(Ze),st=oe.getOrCreateProgram("elevatedStructuresDepth",{config:Be,overrideFog:qe}),Qe=xe.calculateShadowPassMatrixFromTile(ze.tileID.toUnwrapped());oe.uploadCommonUniforms(oe.context,st,Ze.toUnwrapped());const xt=yI(Qe,0);st.draw(oe,Le.TRIANGLES,xe.getShadowPassDepthMode(),Qr.disabled,Kr.disabled,Gr.disabled,xt,pe.id,De.vertexBuffer,De.indexBuffer,De.shadowCasterSegments,pe.paint,oe.transform.zoom,Be)}}(ee));const ie=v.emissiveMode==="mrt-fallback";if(Y!=="offset"){if(d0(ee,!1,ie),Y==="road"){const le=!te&&v.renderPass==="translucent";le&&u0(v,d,g,w,"geometry"),d0(ee,!0,ie,Qr.disabled),le&&function(oe){const{painter:ge,sourceCache:pe,layer:Ne,coords:Le,colorMode:xe}=oe,Ze=ge.context.gl,ze=oe.painter.shadowRenderer,Ke=!!ze&&ze.enabled,De=new Ir(ge.context.gl.LEQUAL,Ir.ReadOnly,ge.depthRangeFor3D);let Be=[0,0,0];if(Ke){const st=ge.style.directionalLight,Qe=ge.style.ambientLight;st&&Qe&&(Be=zu(ge.style,st,Qe))}const qe=st=>{for(const Qe of Le){const xt=pe.getTile(Qe),ft=xt.getBucket(Ne);if(!ft)continue;const Rt=ft.elevatedStructures;if(!Rt)continue;let Ft,ot;if(st?(Ft=Rt.renderableBridgeSegments,ot=Rt.bridgeProgramConfigurations.get(Ne.id)):(Ft=Rt.renderableTunnelSegments,ot=Rt.tunnelProgramConfigurations.get(Ne.id)),!Ft||Ft.segments[0].primitiveLength===0)continue;ot.updatePaintBuffers(),ge.prepareDrawTile();const et=ge.isTileAffectedByFog(Qe),gt=[];Ke&>.push("RENDER_SHADOWS","NORMAL_OFFSET");const bt=ge.getOrCreateProgram("elevatedStructures",{config:ot,overrideFog:et,defines:gt}),St=ge.translatePosMatrix(Qe.projMatrix,xt,Ne.paint.get("fill-translate"),Ne.paint.get("fill-translate-anchor"));Ke&&ze.setupShadows(xt.tileID.toUnwrapped(),bt,"vector-tile");const rr=xI(St,Be);ge.uploadCommonUniforms(ge.context,bt,Qe.toUnwrapped()),bt.draw(ge,Ze.TRIANGLES,De,Qr.disabled,xe,Gr.backCCW,rr,Ne.id,Rt.vertexBuffer,Rt.indexBuffer,Ft,Ne.paint,ge.transform.zoom,ot,[Rt.vertexBufferNormal])}};qe(!0),qe(!1)}(ee)}}else d0(ee,!1,ie,v.stencilModeFor3D())},"fill-extrusion":function(v,d,g,w){const A=g.paint.get("fill-extrusion-opacity"),N=v.context,L=N.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,ge){for(const pe of oe){const Ne=ie.getTile(pe).getBucket(le);Ne&&(Ne.updateReplacement(pe,ee.replacementSource,ge),Ne.uploadCentroid(ee.context))}}(v,d,g,w,te),F||Y)for(const ee of w){const ie=d.getTile(ee).getBucket(g);ie&&jI(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();$m(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?$m(v,d,g,w,le,Qr.disabled,Kr.unblended,Y):($m(v,d,g,w,le,Qr.disabled,Kr.disabled,Y),$m(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"),ge=g.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),pe=g.paint.get("fill-extrusion-flood-light-intensity"),Ne=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Le=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ne?null:g.lut).toArray01().slice(0,3),xe=oe>0&&ge>0,Ze=pe>0,ze=(Be,qe,st)=>(1-st)*Be+st*qe,Ke=new JT;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=Be=>{const qe=v.depthModeForSublayer(1,Ir.ReadOnly,L.LEQUAL,!0),st=g.paint.get(Be?"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);kd(Ke,v,d,g,w,qe,ft,Rt,Gr.disabled,Be,"sdf",le,oe,ge,pe,Le,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]);kd(Ke,v,d,g,w,qe,ft,Rt,Gr.disabled,Be,"color",le,oe,ge,pe,Le,Qe,Y,!1)}};if($){const Be=()=>{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(N,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]);kd(Ke,v,d,g,w,ft,Qr.disabled,ot,Gr.disabled,st,"clear",le,oe,ge,pe,Le,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);kd(Ke,v,d,g,w,ft,ot,et,Gr.disabled,st,"sdf",le,oe,ge,pe,Le,Ft,Y,Qe)}H&&!st&&(xt=Be());{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]);kd(Ke,v,d,g,w,ft,et,gt,Gr.disabled,st,"color",le,oe,ge,pe,Le,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);kd(Ke,v,d,g,w,ft,Qr.disabled,ot,Gr.disabled,st,"clear",le,oe,ge,pe,Le,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);kd(Ke,v,d,g,w,ft,ot,et,Gr.disabled,st,"emissive",le,oe,ge,pe,Le,Ft,Y,Qe,xt),L.drawBuffers([L.COLOR_ATTACHMENT0])}};if(xe||Ze){let st;v.prepareDrawTile(),H&&!xe||(st=Be()),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&&N>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,ge,pe,Ne){for(const Le of Ne){const xe=le.getTile(Le).getBucket(oe);xe&&(pe&&xe.updateReplacement(Le,ie.replacementSource,ge),xe.uploadUpdatedIndexBuffer(ie.context))}}(v,d,g,ee,te,w),function(ie,le,oe,ge){for(const pe of ge){const Ne=le.getTile(pe).getBucket(oe);Ne&&Ne.needsEvaluation()&&Ne.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();h0({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"),ge=g.paint.get("building-flood-light-intensity"),pe=g.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Ne=g.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(pe?null:g.lut).toArray01().slice(0,3),Le=g.paint.get("building-flood-light-ground-attenuation"),xe=ge>0,Ze=new Ir(v.context.gl.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D);F<1&&h0({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:Kr.disabled,depthMode:Ze,opacity:F,verticalScale:Y,facadeEmissiveChance:le,facadeAOIntensity:oe,floodLightIntensity:ge,floodLightColor:Ne,depthOnly:!0});const ze=v.colorModeForRenderPass();h0({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:ze,depthMode:Ze,opacity:F,verticalScale:Y,facadeEmissiveChance:le,facadeAOIntensity:oe,floodLightIntensity:ge,floodLightColor:Ne});const Ke=g.paint.get("building-front-cutoff");Qv(v.transform.pitch,Ke,!!v.terrain),$&&tE(v,d,g,w,!0,F,A,N,ge,Ne,L,te),xe&&tE(v,d,g,w,!1,F,A,N,ge,Ne,Le,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);h0({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,N=v.terrain&&v.terrain.renderingToTexture,[L,F]=v.renderPass!=="translucent"||N?[{},w]:v.stencilConfigForOverlap(w);for(const $ of F){const H=d.getTile($);if(H.needsHillshadePrepare&&v.renderPass==="offscreen")a5(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=N&&v.terrain?v.terrain.stencilModeForRTTOverlap($):L[$.overscaledZ];s5(v,$,H,g,Y,ie,ee)}}A.viewport.set([0,0,v.width,v.height]),v.resetStencilClippingMasks()},raster:function(v,d,g,w,A,N){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(Be,qe,st,Qe,xt){const ft=qe.paint.get("raster-color"),Rt=Be.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 bt=[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&&Be.rasterLayers)){const Ht=Be.rasterLayers.find(({id:Wt})=>Wt===qe.sourceLayer);Ht&&Ht.fields&&Ht.fields.range&&(gt=Ht.fields.range)}if(gt=gt||[0,1],ft){Ft.push("RASTER_COLOR"),st.activeTexture.set(Qe.TEXTURE2),qe.updateColorRamp(gt);let Ht=qe.colorRampTexture;Ht||(Ht=qe.colorRampTexture=new s.T(st,qe.colorRamp,Qe.RGBA8)),Ht.bind(rr,Qe.CLAMP_TO_EDGE)}return xt&&Ft.push("USE_MRT1"),{mix:bt,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 ge=g.paint.get("raster-emissive-strength"),pe=v.colorModeForDrapableLayerRenderPass(ge),Ne=v.terrain&&v.terrain.renderingToTexture,Le=!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 Be=$?v.stencilModeFor3D():Qr.disabled;return void eb(!!le.onNorthPole,null,v,d,g,ge,oe,Gr.disabled,Be)}if(!w.length)return;const[Ze,ze]=le instanceof s.aV||Ne?[{},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=(Be,qe,st)=>{for(const Qe of Be){const xt=Qe.toUnwrapped(),ft=d.getTile(Qe);if(Ne&&(!ft||!ft.hasData()))continue;ee.activeTexture.set(ie.TEXTURE0);const Rt=II(ft,le,g,oe);if(!Rt||!Rt.texture)continue;const{texture:Ft,mix:ot,offset:et,tileSize:gt,buffer:bt}=Rt;let St,rr;Ne?(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,Le)):(St=v.depthModeForSublayer(Qe.overscaledZ-Ke,L===1?Ir.ReadWrite:Ir.ReadOnly,ie.LESS),rr=v.transform.calculateProjMatrix(xt,Le));const Ht=v.terrain&&Ne?v.terrain.stencilModeForRTTOverlap(Qe):Ze[Qe.overscaledZ],Wt=N?0:g.paint.get("raster-fade-duration");ft.registerFadeDuration(Wt);const Dt=d.findLoadedParent(Qe,0),Ar=n0(ft,Dt,d,v.transform,Wt);let Lr,yr;!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),yr=[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=$?nE(Tr):[0,0,0,0];let en,bn,Ur,wn,tn,qn=0;if(H&&le instanceof s.aV&&le.coordinates.length>3)en=Float32Array.from(s.du(s.dv(new s.cn(0,0,0)))),bn=Float32Array.from(Tr.globeMatrix),Ur=Float32Array.from(s.dq(Tr)),wn=[s.aH(Tr.center.lng),s.aL(Tr.center.lat)],Hr=le.elevatedGlobePerspectiveTransform,tn=le.elevatedGlobeGridMatrix||new Float32Array(9);else if(H){const Jn=s.dr(Qe.canonical);qn=s.ds(Jn.getCenter().lat),en=Float32Array.from(s.du(s.dv(Qe.canonical))),bn=Float32Array.from(Tr.globeMatrix),Ur=Float32Array.from(s.dq(Tr)),wn=[s.aH(Tr.center.lng),s.aL(Tr.center.lat)],Hr=[0,0],tn=Float32Array.from(s.dt(Qe.canonical,Jn,qn,Tr.worldSize/Tr._pixelsPerMercatorPixel))}else Hr=le instanceof s.aV?le.perspectiveTransform:[0,0],en=new Float32Array(16),bn=new Float32Array(9),Ur=new Float32Array(16),wn=[0,0],tn=new Float32Array(9);const bi=bI(v,rr,en,bn,Ur,tn,yr||[0,0],s.al(v.transform.zoom),wn,sn,Lr||1,Ar,g,Hr,$?g.paint.get("raster-elevation"):0,2,ot,et,oe.range,gt,bt,ge),Zi=v.isTileAffectedByFog(Qe),ki=v.getOrCreateProgram("raster",{defines:oe.defines,overrideFog:Zi});if(v.uploadCommonUniforms(ee,ki,xt),le instanceof s.aV){const Jn=le.elevatedGlobeVertexBuffer,gn=le.elevatedGlobeIndexBuffer;if(Ne||!F)le.boundsBuffer&&le.boundsSegments&&ki.draw(v,ie.TRIANGLES,St,Qr.disabled,pe,Gr.disabled,bi,g.id,le.boundsBuffer,v.quadTriangleIndexBuffer,le.boundsSegments);else if(Jn&&gn){const yn=Tr.zoom<=s.cJ?le.elevatedGlobeSegments:le.getSegmentsForLongitude(Tr.center.lng);yn&&ki.draw(v,ie.TRIANGLES,St,Qr.disabled,pe,qe,bi,g.id,Jn,gn,yn)}}else if(H){St=new Ir(ie.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D);const Jn=v.globeSharedBuffers;if(Jn){Y&&(v.terrain.setupElevationDraw(ft,ki),v.uploadCommonUniforms(ee,ki,ft.tileID.toUnwrapped()));const[gn,yn,Ci]=Jn.getGridBuffers(qn,!1),ns=ki.getAttributeLocation(ie,"a_texture_pos");ns!==-1&&ie.vertexAttribI4ui(ns,0,0,0,0),ki.draw(v,ie.TRIANGLES,St,st||Ht,v.colorModeForRenderPass(),qe,bi,g.id,gn,yn,Ci)}}else if(te)St=new Ir(ie.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D),v.terrain.setupElevationDraw(ft,ki),v.uploadCommonUniforms(ee,ki,ft.tileID.toUnwrapped()),Tr.pitch>20&&ki.draw(v,ie.TRIANGLES,St,Qr.disabled,Kr.disabled,Gr.frontCCW,bi,g.id,v.terrain.gridBuffer,v.terrain.gridIndexBuffer,v.terrain.gridSegments),ki.draw(v,ie.TRIANGLES,St,Ht,pe,Gr.backCCW,bi,g.id,v.terrain.gridBuffer,v.terrain.gridIndexBuffer,v.terrain.gridSegments);else{const{tileBoundsBuffer:Jn,tileBoundsIndexBuffer:gn,tileBoundsSegments:yn}=v.getTileBoundsBuffers(ft);ki.draw(v,ie.TRIANGLES,St,Ht,pe,Gr.disabled,bi,g.id,Jn,gn,yn)}}if(!(le instanceof s.aV)&&H)for(const Qe of Be){const xt=Qe.canonical.y===(1<s.d$[bt](xt));ot.push(xt);const et=xt.canonical.x,gt=xt.canonical.y;for(const bt of ot){const St=xe.getTile(qe?bt.wrapped():bt);if(!St)continue;const rr=St.rasterParticleState;if(!rr)continue;const Ht=bt.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(Le,{overrideFog:!1,overrideRtt:!0,defines:ze}),De=new Float32Array(s.b9([])),Be=new s.aR(0,0,0,0,0),qe=ie?wf(De,F,L,v,0,g.scope,le,$,{tileID:Be,tileSize:ee}):o0(De,F,L,A.toPremultipliedRenderColor(N?null:g.lut));return void Ke.draw(v,Y.TRIANGLES,pe,ge,Ne,Gr.disabled,qe,g.id,v.viewportBuffer,v.quadTriangleIndexBuffer,v.viewportSegments)}for(const Ke of Ze){const De=v.isTileAffectedByFog(Ke),Be=v.getOrCreateProgram(Le,{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?wf(st,F,L,v,0,g.scope,le,$,{tileID:Ke,tileSize:ee}):o0(st,F,L,A.toPremultipliedRenderColor(N?null:g.lut));v.uploadCommonUniforms(H,Be,qe);const{tileBoundsBuffer:ft,tileBoundsIndexBuffer:Rt,tileBoundsSegments:Ft}=v.getTileBoundsBuffers(Qe);Be.draw(v,Y.TRIANGLES,pe,ge,Ne,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 N=v.context,L=g.paint.get("sky-type"),F=new Ir(N.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 Qo(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"),ge=new Float64Array(16);s.b9(ge),s.ef(ge,ge,.5*-Math.PI),jc(H,Y,oe,ge,le,0),s.b9(ge),s.ef(ge,ge,.5*Math.PI),jc(H,Y,oe,ge,le,1),s.b9(ge),s.cE(ge,ge,.5*-Math.PI),jc(H,Y,oe,ge,le,2),s.b9(ge),s.cE(ge,ge,.5*Math.PI),jc(H,Y,oe,ge,le,3),s.b9(ge),jc(H,Y,oe,ge,le,4),s.b9(ge),s.ef(ge,ge,Math.PI),jc(H,Y,oe,ge,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,ge=H.transform,pe=H.getOrCreateProgram("skybox");le.activeTexture.set(oe.TEXTURE0),oe.bindTexture(oe.TEXTURE_CUBE_MAP,Y.skyboxTexture);const Ne=((Le,xe,Ze,ze,Ke)=>({u_matrix:Le,u_sun_direction:xe,u_cubemap:0,u_opacity:ze,u_temporal_offset:Ke}))(ge.skyboxMatrix,Y.getCenter(H,!1),0,ee,ie);H.uploadCommonUniforms(le,pe),pe.draw(H,oe.TRIANGLES,te,Qr.disabled,H.colorModeForRenderPass(),Gr.backCW,Ne,"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,ge=H.transform,pe=H.getOrCreateProgram("skyboxGradient");Y.skyboxGeometry||(Y.skyboxGeometry=new Qo(le)),le.activeTexture.set(oe.TEXTURE0);let Ne=Y.colorRampTexture;Ne||(Ne=Y.colorRampTexture=new s.T(le,Y.colorRamp,oe.RGBA8)),Ne.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const Le=((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}))(ge.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,Le,"skyboxGradient",Y.skyboxGeometry.vertexBuffer,Y.skyboxGeometry.indexBuffer,Y.skyboxGeometry.segment)}(v,g,F,A,$)},custom:function(v,d,g,w){const A=v.context,N=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=N.prerender;if(L){if(v.setCustomLayerDefaults(),A.setColorMode(v.colorModeForRenderPass()),v.transform.projection.name==="globe"){const F=v.transform.pointMerc;L.call(N,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(N,A.gl,v.transform.customLayerMatrix());A.setDirty(),v.setBaseState()}}else if(v.renderPass==="translucent"){if(v.terrain&&v.terrain.renderingToTexture){const F=N.renderToTile;if(F){const $=w[0].canonical,H={x:$.x+w[0].wrap*(N.wrapTileId?0:1<<$.z),y:$.y,z:$.z};A.setDepthMode(Ir.disabled),A.setStencilMode(Qr.disabled),A.setColorMode(v.colorModeForRenderPass()),v.setCustomLayerDefaults(),F.call(N,A.gl,H),A.setDirty(),v.setBaseState()}return}v.setCustomLayerDefaults(),A.setColorMode(v.colorModeForRenderPass()),A.setStencilMode(Qr.disabled);const L=N.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;N.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 N.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),N=g.paint.get("model-elevation-reference"),L=N==="ground",F=N==="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 Be=xe.transform,qe=Be.projection.name==="globe",st=Be.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!==Be.projection.name)continue;const bt=gt.getModelUris();if(bt&&!gt.modelsRequested&&(Qe.addModelsFromBucket(bt,De),gt.modelsRequested=!0),qe)Rt.zoom=et.overscaledZ;else{const yr=Ag(et,Be);Rt.zoom=yr}const St=ft.possiblyEvaluate(Rt);if(Qt(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 yr=Be.calculatePosMatrix(et.toUnwrapped(),Be.worldSize);if(qt.tileMatrix.set(yr),qt.shadowTileMatrix=Float32Array.from(xt.calculateShadowPassMatrixFromMatrix(yr)),qt.aabb.min=[0,0,0],qt.aabb.max[0]=qt.aabb.max[1]=s.an,qt.aabb.max[2]=0,OI(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 Wt=0;const Dt=new Array,Ar=new Array,Lr=new Array;for(let yr in gt.instancesPerModel){const Tr=gt.instancesPerModel[yr];Tr.features.length>0&&!qe&&(yr=St.evaluate(Tr.features[0].feature,{}));const Hr=Qe.getModel(yr,De);if(Hr||Qe.hasURLBeenRequested(yr)||gt.modelUris.includes(yr)||(gt.modelUris.push(yr),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&&wn.elevationUpdate(yr.terrain,en,Ur,Hr.source),wn.needsReEvaluation(yr,bn,Hr)&&wn.evaluate(Hr))}})(xe,Ze,ze,Ke),function(){const yr=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),bn=s.ce(),Ur=new s.P(0,0);for(let wn=Tr;wn!==Hr;wn+=sn){const tn=Ke[wn],qn=Ze.getTile(tn).getBucket(ze);if(!qn||!qn.uploaded)continue;let bi=!1;st&&(bi=st.getMaxCascadeForTile(tn.toUnwrapped())===0);const Zi=Be.calculatePosMatrix(tn.toUnwrapped(),Be.worldSize),ki=qn.modelTraits;!rr&&Dt&&(s.b7(en,Zi),s.ah(bn,xt,en),Ur.x=bn[0],Ur.y=bn[1]);const Jn=[];qn.setFilter(ze.filter);for(const gn of qn.getNodesInfo()){if(gn.hiddenByReplacement||!gn.node.meshes)continue;const yn=gn.node;let Ci=0;xe.terrain&&yn.elevation&&(Ci=yn.elevation*xe.terrain.exaggeration());const ns=(()=>{const qa=gn.aabb;return St.min=[...qa.min],St.max=[...qa.max],St.min[2]+=Ci,St.max[2]+=Ci,s.ah(St.min,St.min,Zi),s.ah(St.max,St.max,Zi),St})(),ei=gn.evaluatedScale;if(ei[0]<=1&&ei[1]<=1&&ei[2]<=1&&ns.intersects(Ht)===0)continue;if(!rr&&Dt){const qa=.16666666666666666;gn.cameraCollisionOpacity=xt[0]>ns.min[0]&&xt[0]ns.min[1]&&xt[1]!Dt||gn.opacity===1&&yn.opacity===1?gn.depthyn.depth?-1:1);for(const gn of Jn){const yn=gn.nodeInfo,Ci=yn.node;if(xe._debugParams.show3DModelFootprints&&Ci.footprint){const In=Ci.id||Ci.name||"footprint";yr.has(In)||yr.set(In,{node:Ci,mvp:gn.wvpForTile})}let ns=s.aD([],ot,gn.tileModelMatrix);s.aD(ns,Rt,ns);const ei=s.b7([],ns);s.e6(ei,ei),s.cC(ei,ei,nt),ns=s.aD(ns,ns,Ci.globalMatrix);const on=xe.renderPass==="light-beam",Ki=ze.paint.get("model-color-use-theme").constantOr("default")==="none",wi=ki&s.ez.HasMapboxMeshFeatures,Os=wi?0:yn.evaluatedRMEA[0][2];for(let In=0;In=Ln||hc>=Ln}}const oi=Ai.material;let Ic;oi.occlusionTexture&&oi.occlusionTexture.offsetScale&&(Ic=oi.occlusionTexture.offsetScale,ha.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Nc=xe.getOrCreateProgram("model",ha);!rr&&st&&st.setupShadowsFromMatrix(gn.tileModelMatrix,Nc,st.useNormalOffset),xe.uploadCommonUniforms(De,Nc,null,dc);const Li=oi.pbrMetallicRoughness;Li.metallicFactor=.9,Li.roughnessFactor=.5;const $i=Bm(new Float32Array(wo),new Float32Array(ns),new Float32Array(ei),new Float32Array(Ci.globalMatrix),xe,gn.opacity,Li.baseColorFactor,oi.emissiveFactor,Li.metallicFactor,Li.roughnessFactor,oi,Os,ze,[0,0,0],Ic);!Js&&(yn.hasTranslucentParts||gn.opacity<1)&&Nc.draw(xe,De.gl.TRIANGLES,gt,Qr.disabled,Kr.disabled,Gr.backCCW,$i,ze.id,Ai.vertexBuffer,Ai.indexBuffer,Ai.segments,ze.paint,xe.transform.zoom,void 0,qa),Nc.draw(xe,De.gl.TRIANGLES,Js?bt:gt,Qr.disabled,Js||gn.opacity<1||yn.hasTranslucentParts?Kr.alphaBlended:Kr.unblended,Gr.backCCW,$i,ze.id,Ai.vertexBuffer,Ai.indexBuffer,Ai.segments,ze.paint,xe.transform.zoom,void 0,qa)}}}if(xe._debugParams.show3DModelFootprints&&yr.size>0){const wn=Array.from(yr.keys()).sort();for(const tn of wn){const{node:qn,mvp:bi}=yr.get(tn);fE(xe,0,qn,bi)}}}()}(v,d,g,w),void te();if(ee.type!=="model")return;const ie=ee.getModels(),le=[],oe=v.transform.getFreeCameraOptions().position,ge=s.bJ([],[oe.x,oe.y,oe.z],v.transform.worldSize);s.eo(ge,ge);const pe=[],Ne=[];let Le=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),Be=g.paint.get("model-translation").evaluate(ze,Ze),qe=g.paint.get("model-opacity").evaluate(ze,Ze);mE(g,xe.id,Ze,xe.featureProperties,xe.nodeOverrideNames,xe.nodeOverrides),Vm(g,xe.id,Ze,xe.featureProperties,xe.materialOverrideNames,xe.materialOverrides),xe.nodeOverrides.size>0&&xe.computeBoundsAndApplyParent(),xe.computeModelMatrix(v,Ke,De,Be,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,ge),le.push({zScaleMatrix:xt,negCameraPosMatrix:st});for(const ft of xe.nodes)nb(v,ft,xe.matrix,v.transform.expandedFarZProjMatrix,Le,pe,Ne,xe.materialOverrides,qe);Le++}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,Be)=>{if(De.footprint){const qe=De.id||De.name||"footprint";if(!Ze.has(qe)){const st=s.aD([],xe,Be);Ze.set(qe,{node:De,mvp:st})}}};for(const De of Ne)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:Be,mvp:qe}=Ze.get(De);fE(v,0,Be,qe)}}_h(v,g,pe,Ne,le),te()}else{for(const xe of Ne)Eg(xe.mesh,xe.nodeModelMatrix,v,g);for(const xe of pe)Eg(xe.mesh,xe.nodeModelMatrix,v,g);te()}}},yE={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 N=d.getTile(A).getBucket(v);if(N&&(N.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,rb(g,v)));if(w.type==="batched-model"||w.type!=="model")return;const A=w.getModels();for(const N of A)N.upload(g.context)},raster:function(v,d,g){const w=d.getSource();if(!(w instanceof jm&&w.loaded()))return;const A=v.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!A)return;const N=v.paint.get("raster-array-band")||w.getInitialBand(A);if(N==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(v.id,N)&&w.prepareTile(F,A,v.id,N)},"raster-particle":function(v,d,g){const w=d.getSource();if(!(w instanceof jm&&w.loaded()))return;const A=v.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!A)return;const N=v.paint.get("raster-particle-array-band")||w.getInitialBand(A);if(N==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(v.id,N)&&w.prepareTile(F,A,v.id,N)}},xE={fill:u0},_E={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,N=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=QT(H.toUnwrapped(),F),le=v.translatePosMatrix(H.projMatrix,Y,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor")),oe=s0(le,ie,0,1,0);$.draw(v,A.TRIANGLES,N,L,Kr.disabled,Gr.disabled,oe,g.id,ee.vertexBuffer,ee.indexBuffer,ee.depthSegments,g.paint,v.transform.zoom)}}};class S5{constructor(d,g,w,A,N){this.context=new Sg(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 BI,this.setup(),this.numSublayers=lu.maxUnderzooming+lu.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 Gx(this),this._wireframeDebugCache=new FI,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=N,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 i0(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 N=w+.78*(A-w);this.transform.fogCullDistSq=N*N}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 i0(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 N=new s.eH;N.emplaceBack(0,0,0,0),N.emplaceBack(s.an,0,s.an,0),N.emplaceBack(0,s.an,0,s.an),N.emplaceBack(s.an,s.an,s.an,s.an),this.mercatorBoundsBuffer=d.createVertexBuffer(N,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,r0(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,N=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,N.TRIANGLES,Ir.disabled,new Qr({func:N.ALWAYS,mask:0},H,255,N.KEEP,N.KEEP,N.REPLACE),Kr.disabled,Gr.disabled,r0(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,N=w[0].overscaledZ-A+1;if(N>1){this.currentStencilSource=void 0,this.nextStencilID+N>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,N=!(!this.terrain||!this.terrain.enabled),L=()=>this.style._getOrder(N).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 ge={},pe={},Ne={},Le={},xe={};for(const ot in le){const et=le[ot];ge[ot]=et.getVisibleCoordinates(),pe[ot]=ge[ot].slice().reverse(),Ne[ot]=et.getVisibleCoordinates(!0).reverse(),Le[ot]=et.getShadowCasterCoordinates(),xe[ot]=et.sortCoordinatesByDistance(ge[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 bt of ie)this.isSourceForClippingOrConflation(bt,Ze(bt))&&(ot.push(bt),et.push(gt)),gt++;if(ot&&(oe||ot.length>1)||this._clippingActiveLastFrame){oe=!1;const bt=[];for(let St=0;St0){const bt=Ze(et);bt&&(this.minCutoffZoom=Math.max(bt.minzoom,this.minCutoffZoom)),et.minzoom&&(this.minCutoffZoom=Math.max(et.minzoom,this.minCutoffZoom))}et.is3D(N)&&(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(Ne),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 ge[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 DI(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const De=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Be=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(De&&!this._snow&&(this._snow=new UI(this)),!De&&this._snow&&(this._snow.destroy(),delete this._snow),Be&&!this._rain&&(this._rain=new m0(this)),!Be&&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 xh);const ot=this.style.getLayerSourceCache(Y);this.buildingTileBorderManager.updateBorders(ot,Y)}if(!xr.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,Le)),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",bt=ot.properties.get("color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new s.aq(...bt)}if(qe){const gt=ot.properties.get("space-color-use-theme")==="none",bt=ot.properties.get("space-color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new s.aq(...bt)}}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(N)?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 bt of this.layersWithOcclusionOpacity){this.currentLayer=bt;const St=ie[this.currentLayer],rr=d.getLayerSourceCache(St),Ht=rr?pe[rr.id]:void 0;this.terrain||this._renderTileClippingMasks(St,rr,rr?ge[rr.id]:void 0),this.renderLayer(this,rr,St,Ht)}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,N=[];return this.style&&this.style.enable3dLights()&&(d==="globeRaster"||d==="terrainRaster"?(N.push("LIGHTING_3D_MODE"),N.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):A||N.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(N.push("TERRAIN"),this.linearFloatFilteringSupported()&&N.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&N.push("GLOBE"),!this._fogVisible||A||g!==void 0&&!g||N.push("FOG"),A&&N.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&N.push("OVERDRAW_INSPECTOR"),N}getOrCreateProgram(d,g){this.cache=this.cache||{};const w=g&&g.defines||[],A=g&&g.config,N=this.currentGlobalDefines(d,g&&g.overrideFog,g&&g.overrideRtt).concat(w),L=Fm.cacheKey(JC[d],d,N,A);return this.cache[L]||(this.cache[L]=new Fm(this.context,d,JC[d],A,Kv[d],N)),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 N=((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"),ge=[H.x,H.y,H.z],pe=s.dD(le,oe),Ne=s.dD(te,ee);return{u_lighting_ambient_color:pe,u_lighting_directional_dir:ge,u_lighting_directional_color:Ne,u_ground_radiance:WT(ge,Ne,pe)}})(w,A,this.style);g.setLightsUniformValues(d,N)}}}uploadCommonUniforms(d,g,w,A,N){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,ge,pe,Ne,Le,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,[Be,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(Be,qe),qe],u_fog_temporal_offset:De,u_frustum_tl:ie,u_frustum_tr:le,u_frustum_br:oe,u_frustum_bl:ge,u_globe_pos:pe,u_globe_radius:Ne,u_viewport:Le,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,$)}N&&g.setCutoffUniformValues(d,N.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]>=Ln||g[1]>=Ln}setupDepthForOcclusion(d,g,w){const A=this.context,N=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(N.TEXTURE3),d&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(N.NEAREST,N.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(N.NEAREST,N.CLAMP_TO_EDGE),A.activeTexture.set(N.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 vE(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 T5{constructor(d){this._hashName=d&&encodeURIComponent(d),s.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=vE(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=Jo(d);if(this._hashName){const w=this._hashName;let A=!1;const N=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||N.push(`${w}=${g}`),`#${N.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 Jo(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),N=Math.pow(10,A),L=Math.round(g.lng*N)/N,F=Math.round(g.lat*N)/N,$=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 lb={linearity:.3,easing:s.eN(0,0,.3,1)},p0=Object.assign({deceleration:2500,maxSpeed:1400},lb),E5=Object.assign({deceleration:20,maxSpeed:1400},lb),Vi=Object.assign({deceleration:1e3,maxSpeed:360},lb),Pn=Object.assign({deceleration:1e3,maxSpeed:90},lb);class qI{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:N}of this._inertiaBuffer)g.zoom+=N.zoomDelta||0,g.bearing+=N.bearingDelta||0,g.pitch+=N.pitchDelta||0,N.panDelta&&g.pan._add(N.panDelta),N.around&&(g.around=N.around),N.pinchAround&&(g.pinchAround=N.pinchAround);const w=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,A={};if(g.pan.mag()){const N=Id(g.pan.mag(),w,Object.assign({},p0,d||{}));A.offset=g.pan.mult(N.amount/g.pan.mag()),A.center=this._map.transform.center,uc(A,N)}if(g.zoom){const N=Id(g.zoom,w,E5);A.zoom=this._map.transform.zoom+N.amount,uc(A,N)}if(g.bearing){const N=Id(g.bearing,w,Vi);A.bearing=this._map.transform.bearing+s.aC(N.amount,-179,179),uc(A,N)}if(g.pitch){const N=Id(g.pitch,w,Pn);A.pitch=this._map.transform.pitch+N.amount,uc(A,N)}if(A.zoom||A.bearing){const N=g.pinchAround===void 0?g.around:g.pinchAround;A.around=N?this._map.unproject(N):this._map.getCenter()}return this.clear(),A.noMoveStart=!0,A}}function uc(v,d){(!v.duration||v.durationg.unproject($)),F=N.reduce(($,H,Y,te)=>$.add(H.div(te.length)),new s.P(0,0));super(d,{points:N,point:F,lngLats:L,lngLat:g.unproject(F),originalEvent:w}),this._defaultPrevented=!1}}class bE extends s.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(d,g){super("wheel",{originalEvent:g}),this._defaultPrevented=!1}}class wE{constructor(d,g){this._map=d,this._clickTolerance=g.clickTolerance}reset(){this._mousedownPos=void 0}wheel(d){return this._firePreventable(new bE(this._map,d))}mousedown(d,g){return this._mousedownPos=g,this._firePreventable(new bo(d.type,this._map,d))}mouseup(d){this._map.fire(new bo(d.type,this._map,d))}preclick(d){const g=new MouseEvent("preclick",d);this._map.fire(new bo(g.type,this._map,g))}click(d,g){this._mousedownPos&&this._mousedownPos.dist(g)>=this._clickTolerance||(this.preclick(d),this._map.fire(new bo(d.type,this._map,d)))}dblclick(d){return this._firePreventable(new bo(d.type,this._map,d))}mouseover(d){this._map.fire(new bo(d.type,this._map,d))}mouseout(d){this._map.fire(new bo(d.type,this._map,d))}touchstart(d){return this._firePreventable(new kc(d.type,this._map,d))}touchmove(d){this._map.fire(new kc(d.type,this._map,d))}touchend(d){this._map.fire(new kc(d.type,this._map,d))}touchcancel(d){this._map.fire(new kc(d.type,this._map,d))}_firePreventable(d){if(this._map.fire(d),d.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class SE{constructor(d){this._map=d}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(d){this._map.fire(new bo(d.type,this._map,d))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new bo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(d){this._delayContextMenu?this._contextMenuEvent=d:this._map.fire(new bo(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,N=this._lastPos;if(!A||!N||N.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(),Z(),w.x!==A.x||w.y!==A.y)return this._map.fire(new s.C("boxzoomend",{originalEvent:d})),{cameraAnimation:N=>N.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 g0(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 N=new s.P(0,0);for(const L of A)N._add(L);return N.div(A.length)}(g),this.touches=g0(w,g)))}touchmove(d,g,w){if(this.aborted||!this.centroid)return;const A=g0(w,g);for(const N in this.touches){const L=A[N];(!L||L.dist(this.touches[N])>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 Nd{constructor(d){this.singleTap=new fu(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 N=d.timeStamp-this.lastTime<500,L=!this.lastTap||this.lastTap.dist(A)<30;if(N&&L||this.reset(),this.count++,this.lastTime=d.timeStamp,this.lastTap=A,this.count===this.numTaps)return this.reset(),A}}}class kg{constructor(){this._zoomIn=new Nd({numTouches:1,numTaps:2}),this._zoomOut=new Nd({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),N=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})}):N?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()-1,around:L.unproject(N)},{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 cb=0,EE=2,AE={[cb]:1,[EE]:2},bh={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class y0{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,N){const L=AE[N];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=g0(w,g),N=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&&(N._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 _0{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[N,L]=A,F=vs(w,g,N),$=vs(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,N]=this._firstTwoTouches,L=vs(w,g,A),F=vs(w,g,N);L&&F||(this._active&&Z(),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 vs(v,d,g){for(let w=0;wMath.abs(v.x)}class CE extends _0{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,v0(d[0].sub(d[1]))&&(this._valid=!1)}_move(d,g,w){const A=this._lastPoints;if(!A)return;const N=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(N,L,w.timeStamp),!this._valid)?void 0:(this._lastPoints=d,this._active=!0,{pitchDelta:(N.y+L.y)/2*-.5})}gestureBeginsVertically(d,g,w){if(this._valid!==void 0)return this._valid;const A=d.mag()>=2,N=g.mag()>=2;if(!A&&!N)return;if(!A||!N)return this._firstMove==null&&(this._firstMove=w),w-this._firstMove<100&&void 0;const L=d.y>0==g.y>0;return v0(d)&&v0(g)&&L}}const IE={panStep:100,bearingStep:15,pitchStep:10};class Hm{constructor(){const d=IE;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,N=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(),N=-1);break;case 39:d.shiftKey?w=1:(d.preventDefault(),N=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:NE,zoom:g?Math.round($)+g*(d.shiftKey?2:1):$,bearing:F.getBearing()+w*this._bearingStep,pitch:F.getPitch()+A*this._pitchStep,offset:[-N*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 NE(v){return v*(2-v)}const Wm=4.000244140625,PE=1/450;class fb{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._handler=g,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=PE,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%Wm===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)>Wm?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,N=this._easing;let L,F=!1;if(this._type==="wheel"&&A&&N){const H=Math.min((s.o.now()-this._lastWheelEventTime)/200,1),Y=N(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,N=w.easing(A+.01)-w.easing(A),L=.27/Math.sqrt(N*N+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=P("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 mb{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 pb{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 GI{constructor(){this._tap=new Nd({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],N=A.y-this._swipePoint.y;return this._swipePoint=A,d.preventDefault(),this._active=!0,{zoomDelta:N/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 RE{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 HI{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 WI{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 b0=v=>v.zoom||v.drag||v.pitch||v.rotate;class KI extends s.C{}class YI{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),N=s.cT([],g,s.bJ([],s.ax([],s.cT([],A,w),g),2));g[0]=N[0],g[1]=N[1]}return g}}function w0(v){return v.panDelta&&v.panDelta.mag()||v.zoomDelta||v.bearingDelta||v.pitchDelta}class ZI{constructor(d,g){this._map=d,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new qI(d),this._bearingSnap=g.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new YI,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,N,L]of this._listeners){const F=A===document?this.handleWindowEvent:this.handleEvent;A.addEventListener(N,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 wE(g,d));const A=g.boxZoom=new TE(g,d);this._add("boxZoom",A);const N=new kg,L=new pb;g.doubleClickZoom=new mb(L,N),this._add("tapZoom",N),this._add("clickZoom",L);const F=new GI;this._add("tapDragZoom",F);const $=g.touchPitch=new CE(g);this._add("touchPitch",$);const H=new ub(d),Y=new x0(d);g.dragRotate=new HI(d,H,Y),this._add("mouseRotate",H,["mousePitch"]),this._add("mousePitch",Y,["mouseRotate"]);const te=new mu(d),ee=new jE(g,d);g.dragPan=new RE(w,te,ee),this._add("mousePan",te),this._add("touchPan",ee,["touchZoom","touchRotate"]);const ie=new Gm,le=new kE;g.touchZoomRotate=new WI(w,le,ie,F),this._add("touchRotate",ie,["touchPan","touchZoom"]),this._add("touchZoom",le,["touchPan","touchRotate"]),this._add("blockableMapEvent",new SE(g));const oe=g.scrollZoom=new fb(g,this);this._add("scrollZoom",oe,["mousePan"]);const ge=g.keyboard=new Hm;this._add("keyboard",ge);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!!b0(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,N={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(N,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||w0(N))&&(this._changes.push([N,L,Y]),this._triggerRenderFrame()),(Object.keys(F).length||w0(N))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:te}=N;te&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],te(this._map))}mergeHandlerResult(d,g,w,A,N){if(!w)return;Object.assign(d,w);const L={handlerName:A,originalEvent:w.originalEvent||N};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,N,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,N),Object.assign(w,L);this._updateMapTransform(d,g,w),this._changes=[]}_updateMapTransform(d,g,w){const A=this._map,N=A.transform,L=Ne=>[Ne.x,Ne.y,Ne.z];if((()=>{const Ne=this._eventsInProgress.drag;return Ne&&!this._handlersById[Ne.handlerName].isActive()})()&&!w0(d)){const Ne=N.zoom;N.cameraElevationReference="sea",this._originalZoom!=null&&N._orthographicProjectionAtLowPitch&&N.projection.name!=="globe"&&N.pitch===0?(N.cameraElevationReference="ground",N.zoom=this._originalZoom):(N.recenterOnTerrain(),N.cameraElevationReference="ground"),Ne!==N.zoom&&this._map._update(!0)}if(N._isCameraConstrained&&A._stop(!0),!w0(d))return void this._fireEvents(g,w,!0);let{panDelta:F,zoomDelta:$,bearingDelta:H,pitchDelta:Y,around:te,aroundCoord:ee,pinchAround:ie}=d;N._isCameraConstrained&&($>0&&($=0),N._isCameraConstrained=!1),ie!==void 0&&(te=ie),($||(Ne=>g[Ne]&&!this._eventsInProgress[Ne])("drag"))&&te&&(this._dragOrigin=L(N.pointCoordinate3D(te)),this._originalZoom=N.zoom,this._trackingEllipsoid.setup(N._camera.position,this._dragOrigin)),N.cameraElevationReference="sea",A._stop(!0),te=te||A.transform.centerPoint,H&&(N.bearing+=H),Y&&(N.pitch+=Y),N._updateCameraState();const le=[0,0,0];if(F)if(N.projection.name==="mercator"){const Ne=this._trackingEllipsoid.projectRay(N.screenPointToMercatorRay(te).dir),Le=this._trackingEllipsoid.projectRay(N.screenPointToMercatorRay(te.sub(F)).dir);le[0]=Le[0]-Ne[0],le[1]=Le[1]-Ne[1]}else{const Ne=N.pointCoordinate(te);if(N.projection.name==="globe"){F=F.rotate(-N.angle);const Le=N._pixelsPerMercatorPixel/N.worldSize;le[0]=-F.x*s.eQ(s.bV(Ne.y))*Le,le[1]=-F.y*s.eQ(N.center.lat)*Le}else{const Le=N.pointCoordinate(te.sub(F));Ne&&Le&&(le[0]=Le.x-Ne.x,le[1]=Le.y-Ne.y)}}const oe=N.zoom,ge=[0,0,0];if($){const Ne=L(ee||N.pointCoordinate3D(te)),Le={dir:s.ay([],s.ax([],Ne,N._camera.position))};if(Le.dir[2]<0){const xe=N.zoomDeltaToMovement(Ne,$);s.bJ(ge,Le.dir,xe)}}const pe=s.cT(le,le,ge);N._translateCameraConstrained(pe),$&&Math.abs(N.zoom-oe)>1e-4&&N.recenterOnTerrain(),N.cameraElevationReference="ground",this._map._update(),d.noInertia||this._inertia.record(d),this._fireEvents(g,w,!0)}_fireEvents(d,g,w){const A=b0(this._eventsInProgress),N=b0(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&&N&&this._fireEvent("movestart",N.originalEvent);for(const Y in L)this._fireEvent(Y,L[Y]);N&&this._fireEvent("move",N.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=b0(this._eventsInProgress);if(w&&(A||N)&&!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 KI("renderFrame",{timeStamp:d})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const LE="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class XI 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,N,L){const F=d.clone(),$=this._extendCameraOptions(L);F.bearing=A,F.pitch=N;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])),ge=s.bh([],oe,le),pe=[oe[0],oe[1],oe[2],0,ge[0],ge[1],ge[2],0,le[0],le[1],le[2],0,0,0,0,1],Ne=[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 Le=s.cU.fromPoints(Ne.map(bt=>[s.bi(oe,bt),s.bi(ge,bt),s.bi(le,bt)]));const xe=s.ah([],Le.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);Le=s.cU.applyTransform(Le,s.aD([],Ze,pe));const Ke=this._extendAABB(Le,F,$,A);if(!Ke)return void s.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Le=Ke,s.ah(xe,xe,Ze);const De=.5*(Le.max[2]-Le.min[2]),Be=this._minimumAABBFrustumDistance(F,Le),qe=s.bJ([],[0,0,1],De),st=s.cT(qe,xe,qe),Qe=Be+(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,N,L)):{center:F.center,zoom:gt,bearing:A,pitch:N}}_extendAABB(d,g,w,A){const N=.5*((w.padding.left||0)+(w.padding.right||0)),L=.5*((w.padding.top||0)+(w.padding.bottom||0)),F=L,$=N,H=N,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 ge=g.scale/g.zoomScale(oe),pe=new s.cU([d.min[0]-$*ge,d.min[1]-Y*ge,d.min[2]],[d.max[0]+H*ge,d.max[1]+F*ge,d.max[2]]),Ne=(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]-=Ne.x*ge,pe.center[1]+=Ne.y*ge,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,N,L){if(d.projection.name==="globe")return this._cameraForBoundsOnGlobe(d,g,w,A,N,L);const F=d.clone(),$=this._extendCameraOptions(L);F.bearing=A,F.pitch=N;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),ge=this.queryTerrainElevation(Y),pe=this.queryTerrainElevation(te),Ne=this.queryTerrainElevation(ee),Le=[[ie.x,ie.y,Math.min(oe||0,ge||0,pe||0,Ne||0)],[le.x,le.y,Math.max(oe||0,ge||0,pe||0,Ne||0)]];let xe=s.cU.fromPoints(Le);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],Be=this._minimumAABBFrustumDistance(F,xe),qe=[0,0,1,0];s.aE(qe,qe,Ze),s.eX(qe,qe);const st=s.bJ([],qe,Be+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,N,L)):{center:xt,zoom:Ft,bearing:A,pitch:N}}fitBounds(d,g,w){const A=this.cameraForBounds(d,g);return this._fitInternal(A,g,w)}fitScreenCoordinates(d,g,w,A,N){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)],ge=A&&A.pitch?A.pitch:this.getPitch(),pe=this._cameraForBounds(this.transform,le,oe,w,ge,A);return this._fitInternal(pe,A,N)}_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,N=!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&&(N=!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)),N&&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(LE),this.transform.getFreeCameraOptions()}setFreeCameraOptions(d,g){const w=this.transform;if(!w.projection.supportsFreeCamera)return s.w(LE),this;this.stop();const A=w.zoom,N=w.pitch,L=w.bearing;w.setFreeCameraOptions(d);const F=A!==w.zoom,$=N!==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(),N=this.getBearing(),L=this.getPitch(),F=this.getPadding(),$="zoom"in d?+d.zoom:A,H="bearing"in d?this._normalizeBearing(d.bearing,N):N,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 ge=w.zoomScale($-A);let pe,Ne;d.around&&(pe=s.aU.convert(d.around),Ne=w.locationPoint(pe));const Le=this._zooming||$!==A,xe=this._rotating||N!==H,Ze=this._pitching||Y!==L,ze=!w.isPaddingEqual(te),Ke=d.retainPadding===!1?w.clone():w,De=qe=>st=>{if(Le&&(qe.zoom=s.am(A,$,st)),xe&&(qe.bearing=s.am(N,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,Ne);else{const Qe=qe.zoomScale(qe.zoom-A),xt=$>A?Math.min(2,ge):Math.max(.5,ge),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 Be={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Le,this._rotating=xe,this._pitching=Ze,this._padding=ze,this._easeId=d.easeId,this._prepareEase(g,d.noMoveStart,Be),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,N=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)),N&&this.fire(new s.C("pitchend",d)),this.fire(new s.C("moveend",d))}flyTo(d,g){if(this._prefersReducedMotion(d)){const bt=s.aJ(d,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(bt,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(),N=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,N):N,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),ge=s.aU.convert(d.center||oe);this._normalizeCenter(ge);const pe=w.project(oe),Ne=w.project(ge).sub(pe);let Le=d.curve;const xe=Math.max(w.width,w.height),Ze=xe/ee,ze=Ne.mag();if("minZoom"in d){const bt=s.aC(Math.min(d.minZoom,A,$),w.minZoom,w.maxZoom),St=xe/w.zoomScale(bt-A);Le=Math.sqrt(St/ze*2)}const Ke=Le*Le;function De(bt){const St=(Ze*Ze-xe*xe+(bt?-1:1)*Ke*Ke*ze*ze)/(2*(bt?Ze:xe)*Ke*ze);return Math.log(Math.sqrt(St*St+1)-St)}function Be(bt){return(Math.exp(bt)-Math.exp(-bt))/2}function qe(bt){return(Math.exp(bt)+Math.exp(-bt))/2}const st=De(0);let Qe=function(bt){return qe(st)/qe(st+Le*bt)},xt=function(bt){return xe*((qe(st)*(Be(St=st+Le*bt)/qe(St))-Be(st))/Ke)/ze;var St},ft=(De(1)-st)/Le;if(Math.abs(ze)<1e-6||!isFinite(ft)){if(Math.abs(xe-Ze)<1e-6)return this.easeTo(d,g);const bt=Zed.maxDuration&&(d.duration=0);const Rt=N!==H,Ft=Y!==L,ot=!w.isPaddingEqual(te),et=d.retainPadding===!1?w.clone():w,gt=bt=>St=>{const rr=St*ft,Ht=1/Qe(rr);bt.zoom=St===1?$:A+bt.scaleZoom(Ht),Rt&&(bt.bearing=s.am(N,H,St)),Ft&&(bt.pitch=s.am(L,Y,St)),ot&&(et.interpolatePadding(F,te,St),le=et.centerPoint.add(ie));const Wt=St===1?ge:bt.unproject(pe.add(Ne.mult(xt(rr))).mult(Ht));return bt.setLocationAtPoint(bt.renderWorldCopies?Wt.wrap():Wt,le),bt._updateCameraOnTerrain(),d.preloadOnly||this._fireMoveEvents(g),bt};if(d.preloadOnly){const bt=this._emulate(gt,d.duration,w);return this._preloadTiles(bt),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),N=[],L=d(w.clone());for(let F=0;F<=A;F++){const $=L(F/A);N.push($.clone())}return N}_preloadTiles(d,g){}}class DE{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=P("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=P("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=P("span","mapboxgl-ctrl-icon",this._compactButton);return A.setAttribute("aria-hidden","true"),A.setAttribute("title",w),this._innerContainer=P("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,N,L)=>(N.value&&(A+=`${N.key}=${N.value}${LA.length-N.length),d=d.filter((A,N)=>{for(let L=N+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(N){const L=new DOMParser().parseFromString(N,"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 ME{constructor(){s.aZ(["_updateLogo","_updateCompact"],this)}onAdd(d){this._map=d,this._container=P("div","mapboxgl-ctrl");const g=P("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 QI{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 A5{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 j5={"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 ji extends s.C{constructor(d,g,w,A){const{point:N,lngLat:L,originalEvent:F,target:$}=d;super(d.type,{point:N,lngLat:L,originalEvent:F,target:$}),this.preventDefault=()=>{d.preventDefault()},this.id=g,this.interaction=w,this.feature=A}}class gb{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 N=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)):N.size===0&&this.map.on(A,this.handleType),N.size===0&&this.interactionsByType.set(A,N),N.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,N]of g)N.target&&w.push({targetId:A,target:N.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:N}]of this.prevHoveredFeatures)this.hoveredFeatures.has(A)||w.set(N.id,N);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(),N=!!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(Ed(ee,$,F,H))continue;const ie=new s.di($,ee),le=gT(ee,$,H);N&&ie.id!==void 0&&(ie.state=this.map.getFeatureState(ie));const oe=w?this.prevHoveredFeatures.get(le):null,ge=new ji(d,H,Y,ie),pe=oe?oe.stop:Y.handler(ge);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 ji(d,$,H,null))!==!1)break}}}function k5(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 C5={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},I5={showCompass:!0,showZoom:!0,visualizePitch:!1};class S0{constructor(d,g,w=!1){this._clickTolerance=10,this.element=g,this.mouseRotate=new ub({clickTolerance:d.dragRotate._mouseRotate._clickTolerance}),this.map=d,w&&(this.mousePitch=new x0({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),N=A&&A.bearingDelta;if(N&&w.setBearing(w.getBearing()+N),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 T0={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%)"},Cc={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class pu 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:N=1,draggable:L=!1,clickTolerance:F=0,rotation:$=Cc.rotation,rotationAlignment:H=Cc.rotationAlignment,pitchAlignment:Y=Cc.pitchAlignment,occludedOpacity:te=Cc.occludedOpacity,altitude:ee=Cc.altitude}=d||{};this._anchor=w,this._color=A,this._scale=N,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 T0)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=P("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||Cc.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 N=A.position.toLngLat();return N.distanceTo(w)<.9*N.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) ${T0[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)),N=d.sub(s.f1(g.transform)),L=Math.abs(N.x)+Math.abs(N.y);if(L===0)return"";const F=A/L;return`rotateX(${-N.y*F}deg) rotateY(${N.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 N=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(N);w=s.cH(Math.atan2(L.y,L.x))-90}else w=-g.getBearing();else if(A==="horizon"){const N=s.aj(4,6,g.getZoom()),L=s.f1(g.transform);L.y+=N*g.transform.height;const F=d.sub(L),$=s.cH(Math.atan2(F.y,F.x));w=($>90?$-270:$+90)*(1-N)}return w+=this._rotation,w?`rotateZ(${w}deg)`:""}_update(d){cancelAnimationFrame(this._updateFrameId);const g=this._map;g&&(g.transform.renderWorldCopies&&(this._lngLat=OE(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 N=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 qx(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 QI,this._domRenderTaskQueue=new QI,this._controls=[],this._markers=[],this._popups=[],this._mapId=s.r(),this._locale=Object.assign({},j5,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 A5(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=v.scaleFactor,this._requestManager=new Ce(v.transformRequest,v.accessToken,v.testMode);const g=Pe(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 ZI(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 T5(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 DE({customAttribution:v.customAttribution})),this._logoControl=new ME,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 gb(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 N=[];if(Array.isArray(d)){const L=d.filter(F=>this.getLayer(F));N=L.length?this.queryRenderedFeatures(A,{layers:L}):[]}else N=this.queryRenderedFeatures(A,{target:d});return N};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 bo(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 bo(v,this,F.originalEvent)))},mouseout:F=>{A&&(A=!1,g.call(this,new bo(v,this,F.originalEvent)))}}}}{const A=N=>{const L=w(N.point);L.length&&(N.features=L,g.call(this,N),delete N.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 N=0;N{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 hu(this,g).load(v),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new hu(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:N,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:N,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:N,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:N,height:L,data:F}=A;if(N===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(N!==(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 (${N}, ${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:N,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,N=this._container;for(;N&&(!w||!A);){const L=window.getComputedStyle(N).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])),N=N.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=P("div","mapboxgl-canary",v)).style.visibility="hidden",this._detectMissingCSS();const d=this._canvasContainer=P("div","mapboxgl-canvas-container",v);this._canvas=P("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=P("div","mapboxgl-control-container",v),w=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(A=>{w[A]=P("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({},k.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 S5(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 N=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:N,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,N,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:N,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,y.mark(p.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,y.mark(p.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 N=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(N)?N=0:this._averageElevationLastSampledAt=v;const L=Math.abs(A-N);if(L>1){if(this._isInitialLoad||w)return this._averageElevation.jumpTo(N),g(N);this._averageElevation.easeTo(N,v,300)}else if(L>1e-4)return this._averageElevation.jumpTo(N),g(N)}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 ME&&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(){cr(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,v=>{v&&(v.message!==we&&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()&&Nt(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){vt(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(N){g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,N,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 N=0;N{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({},I5,v),this._container=P("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})}),P("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})}),P("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=P("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 S0(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=P("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},E0,v),s.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=vE(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(v){return this._map=v,this._container=P("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=P("button","mapboxgl-ctrl-geolocate",this._container),P("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=P("div","mapboxgl-user-location"),this._dotElement.appendChild(P("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(P("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new pu({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=P("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new pu({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??E0.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:DE,ScaleControl:class{constructor(v={}){this.options=Object.assign({},da,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]),N=d.unproject([w+v,g]),L=A.distanceTo(N);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(N){const L=Math.pow(10,`${Math.floor(N)}`.length-1);let F=N/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} ${gu[g]}`,this._container.style.width=v*A+"px"})}onAdd(v){return this._map=v,this._language=v.getLanguage(),this._container=P("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=P("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=P("button","mapboxgl-ctrl-fullscreen",this._controlContainer);P("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=P("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=P("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 N,L;A<=5?(N=0,L=A-1):this._visibleFloorStart===0?(N=0,L=3):this._visibleFloorStart>=A-3?(N=A-3-1,L=A-1):(N=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);P("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);P("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}let N=[];if(N=w?d.slice(1,4):A?d.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):d.slice(this._visibleFloorStart,this._visibleFloorStart+3),N.forEach(L=>this._createFloorButton(L)),A)this._createFloorButton(d[g-1]);else{const L=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);P("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}}_createFloorButton(v){const d=this._createButton("mapboxgl-ctrl-level-button",()=>{const N=v.id;this._model&&this._model.selectedFloorId===N&&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(N))}),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(A0),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=P("div","mapboxgl-popup-content",this._container||void 0);if(d.appendChild(v),this.options.closeButton){const g=this._closeButton=P("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,N=g.offsetHeight,L=w.xd.transform.width-A/2;if(w.y+vd.transform.height-N){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=P("div","mapboxgl-popup",d.getContainer()),this._tip=P("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=OE(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),N=yb(this.options.offset),L=this._anchor=this._getAnchor(N.y),F=yb(this.options.offset,L),$=A.add(F).round();d._requestDomTask(()=>{this._container&&L&&(this._container.style.transform=`${T0[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(N5);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:pu,Style:hu,LngLat:s.aU,LngLatBounds:s.aK,Point:s.P,MercatorCoordinate:s.ag,FreeCameraOptions:Ux,Evented:s.E,config:s.g,prewarm:function(){Rn().acquire(dr)},clearPrewarmedResources:function(){const v=Xt;v&&(v.isPreloaded()&&v.numActive()===1?(v.release(dr),Xt=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 ur.workerCount},set workerCount(v){ur.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})})(mve);var wZe=mve.exports;const Kd=ds(wZe),Fre={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"},Bre={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 SZe(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function TZe({listings:t,isLoading:e}){const r=Gs(),n=I.useRef(null),i=I.useRef(null),o=I.useRef([]),[c,s]=I.useState(""),[f,p]=I.useState(!0);return I.useEffect(()=>{(async()=>{p(!0);try{const{data:T}=await Re.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)}p(!1)})()},[]),I.useEffect(()=>{if(!n.current||!c||i.current)return;Kd.accessToken=c;const _=t.filter(k=>k.latitude!=null&&k.longitude!=null);let T=[-98.5795,39.8283],E=4;if(_.length>0){const k=_.reduce((R,D)=>R+D.longitude,0)/_.length,P=_.reduce((R,D)=>R+D.latitude,0)/_.length;T=[k,P],E=_.length===1?12:10}return i.current=new Kd.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:E,center:T}),i.current.addControl(new Kd.NavigationControl,"top-right"),()=>{var k;(k=i.current)==null||k.remove(),i.current=null}},[c]),I.useEffect(()=>{if(!i.current||!c)return;o.current.forEach(T=>T.remove()),o.current=[];const _=t.filter(T=>T.latitude!=null&&T.longitude!=null);if(_.forEach(T=>{var V,G,W;const E=Fre[T.status]||"#10B981",k=((V=T.photos)==null?void 0:V.find(Z=>Z.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 Kd.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${k!=null&&k.photo_url?``:""}
${SZe(T.price)}
${T.property_address||""}
${T.city}, ${T.state}
${Bre[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 Kd.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(M).addTo(i.current);o.current.push(B)}),_.length>1){const T=new Kd.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]),I.useEffect(()=>(window.__navigateToPublicListing__=_=>{r(_)},()=>{delete window.__navigateToPublicListing__}),[r]),f||e?a.jsx(dl,{className:"w-full h-[500px] rounded-lg"}):!c||t.filter(_=>_.latitude!=null&&_.longitude!=null).length===0?null:a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(Fre).map(([_,T])=>a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:T}}),a.jsx("span",{className:"text-xs text-gray-600",children:Bre[_]})]},_))}),a.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const Cz={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"},EZe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},nw="#0d0d0d",zre="#1a1a1a",Xi="#c9a84c",Wg="#f0d78c";function gve(){const[t,e]=I.useState(""),[r,n]=I.useState(!1),[i,o]=I.useState(!1),[c,s]=I.useState(!1),[f,p]=I.useState(-1),y=I.useRef(null),[_,T]=I.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:E}=nZe(),k=I.useMemo(()=>{if(!E)return[];const ue=t.trim().toLowerCase(),_e=[...E.cities.map(Ce=>({label:Ce.label,value:Ce.city,type:"city",count:Ce.count})),...E.neighborhoods.map(Ce=>({label:Ce.label,value:Ce.neighborhood,type:"neighborhood",count:Ce.count})),...E.zips.map(Ce=>({label:`ZIP ${Ce.label}`,value:Ce.zip,type:"zip",count:Ce.count}))];return(ue?_e.filter(Ce=>Ce.label.toLowerCase().includes(ue)||Ce.value.toLowerCase().includes(ue)):_e).slice(0,8)},[E,t]);I.useEffect(()=>{const ue=_e=>{y.current&&!y.current.contains(_e.target)&&s(!1)};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[]);const{data:P,isLoading:R}=rZe({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:Z,luxeCount:Q,cities:re,activeCount:se}=I.useMemo(()=>{const ue=P||[],_e=ue.filter(rt=>rt.status==="active"),we=_e.length>0?_e:ue,Ce=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Me,Ae,be]=Ce.split("-").map(Number),me=Math.floor(Date.UTC(Me,Ae-1,be)/864e5),Pe=we.length>0?we[me%we.length]:void 0,Ie=ue.filter(rt=>!Pe||rt.id!==Pe.id),Se=Array.from(new Set(ue.map(rt=>rt.city).filter(Boolean))).slice(0,8),ve=ue.filter(rt=>(rt.price||0)>=1e6).length,We=_e.length;return{featured:Pe,restListings:Ie,luxeCount:ve,cities:Se,activeCount:We}},[P]);return a.jsxs(a.Fragment,{children:[a.jsxs(Wo,{children:[a.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),a.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."}),a.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),a.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),a.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),a.jsx("meta",{property:"og:type",content:"website"}),a.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),a.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),a.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:nw,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[a.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: ${Xi}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Xi}, 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; } `}),a.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:[a.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[a.jsxs(mn,{to:"/",className:"flex items-center gap-3",children:[a.jsx("img",{src:Ore,alt:"LevelUp",className:"h-7"}),a.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),a.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),a.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[a.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),a.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),a.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),a.jsx(mn,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),a.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 ${Xi}`,color:Xi},children:"About LevelUp"})]}),a.jsx("button",{type:"button",onClick:()=>o(ue=>!ue),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Xi}`,color:Xi},"aria-label":"Toggle menu","aria-expanded":i,children:i?a.jsx(Ds,{className:"w-5 h-5"}):a.jsx(IS,{className:"w-5 h-5"})})]}),i&&a.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:a.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[a.jsx("a",{href:"#featured",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),a.jsx("a",{href:"#collection",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),a.jsx("a",{href:"#map",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),a.jsx(mn,{to:"/home-value",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),a.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>o(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${Xi}`,color:Xi},children:"About LevelUp"})]})})]}),a.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[a.jsxs("div",{className:"absolute inset-0",children:[a.jsx("img",{src:bZe,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),a.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%)"}})]}),a.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:[a.jsxs("div",{className:"max-w-4xl",children:[a.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[a.jsx("span",{className:"h-px w-10",style:{background:Xi}}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),a.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",a.jsx("br",{}),a.jsx("span",{className:"italic",style:{color:Wg},children:"quiet"})," kind of luxury."]}),a.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."}),a.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:y,children:[a.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${Xi}`,backdropFilter:"blur(12px)"},children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(hd,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Xi}}),a.jsx($r,{placeholder:"City, neighborhood, or ZIP",value:t,onChange:ue=>{e(ue.target.value),s(!0),p(-1)},onFocus:()=>s(!0),onKeyDown:ue=>{if(!(!c||k.length===0))if(ue.key==="ArrowDown")ue.preventDefault(),p(_e=>Math.min(_e+1,k.length-1));else if(ue.key==="ArrowUp")ue.preventDefault(),p(_e=>Math.max(_e-1,0));else if(ue.key==="Enter"&&f>=0){ue.preventDefault();const _e=k[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"})]}),a.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:[a.jsx(SDe,{className:"h-4 w-4"}),"Filters"]}),a.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:Xi,color:nw},onClick:()=>s(!1),children:[a.jsx(hd,{className:"h-5 w-5"}),a.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),c&&k.length>0&&a.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:[a.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Xi},children:"Suggestions"}),a.jsx("ul",{className:"max-h-80 overflow-y-auto",children:k.map((ue,_e)=>a.jsx("li",{children:a.jsxs("button",{type:"button",onMouseEnter:()=>p(_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:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[ue.type==="city"&&a.jsx(qs,{className:"h-4 w-4 shrink-0",style:{color:Xi}}),ue.type==="neighborhood"&&a.jsx(go,{className:"h-4 w-4 shrink-0",style:{color:Xi}}),ue.type==="zip"&&a.jsx(La,{className:"h-4 w-4 shrink-0",style:{color:Xi}}),a.jsx("span",{className:"text-white/90 truncate",children:ue.label})]}),a.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()&&k.length===0&&a.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&&a.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:[a.jsxs("div",{children:[a.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),a.jsxs(_a,{value:_.status||"all",onValueChange:ue=>T({..._,status:ue==="all"?"":ue}),children:[a.jsx(aa,{className:"lu-input-dark",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"Any status"}),Object.entries(Cz).map(([ue,_e])=>a.jsx(fn,{value:ue,children:_e},ue))]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),a.jsxs(_a,{value:_.propertyType||"all",onValueChange:ue=>T({..._,propertyType:ue==="all"?"":ue}),children:[a.jsx(aa,{className:"lu-input-dark",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"Any type"}),Object.entries(EZe).map(([ue,_e])=>a.jsx(fn,{value:ue,children:_e},ue))]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),a.jsx($r,{type:"number",placeholder:"No min",value:_.minPrice,onChange:ue=>T({..._,minPrice:ue.target.value}),className:"lu-input-dark"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),a.jsx($r,{type:"number",placeholder:"No max",value:_.maxPrice,onChange:ue=>T({..._,maxPrice:ue.target.value}),className:"lu-input-dark"})]}),B&&a.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:a.jsxs(zt,{variant:"ghost",size:"sm",onClick:M,className:"text-white/70 hover:text-white gap-1",children:[a.jsx(Ds,{className:"h-4 w-4"})," Clear all"]})})]})]}),a.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((P==null?void 0:P.length)??0).toString()},{label:"Active Now",value:se.toString()},{label:"Luxury $1M+",value:Q.toString()}].map(ue=>a.jsxs("div",{children:[a.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:Wg},children:ue.value}),a.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:ue.label})]},ue.label))})]}),a.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[a.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),a.jsx(wc,{className:"h-4 w-4 animate-bounce"})]})]})]}),re.length>0&&a.jsx("section",{className:"py-8 overflow-hidden",style:{background:zre,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:a.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...re,...re,...re].map((ue,_e)=>a.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[ue,a.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Xi}})]},_e))})}),W&&a.jsx("section",{id:"featured",className:"py-20 md:py-28",children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[a.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx(xs,{className:"h-4 w-4",style:{color:Xi}}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),a.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",a.jsx("span",{className:"italic",style:{color:Wg},children:"standout"}),"."]})]}),a.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),a.jsx(mn,{to:G(W),className:"group block",children:a.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[a.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var _e,we;const ue=((_e=W.photos)==null?void 0:_e.find(Ce=>Ce.is_primary))||((we=W.photos)==null?void 0:we[0]);return ue?a.jsx("img",{src:ue.photo_url,alt:W.property_address||W.city,className:"w-full h-full object-cover lu-img-zoom"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(La,{className:"h-16 w-16 text-white/20"})})})(),a.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:Xi,color:nw},children:Cz[W.status]||"Featured"})]}),a.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[a.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[a.jsx(qs,{className:"h-3.5 w-3.5",style:{color:Xi}}),W.city,W.state?`, ${W.state}`:""]}),W.property_address&&a.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:W.property_address}),a.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:Wg},children:D(W.price)}),a.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[W.bedrooms&&a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(CS,{className:"h-4 w-4",style:{color:Xi}}),W.bedrooms," bd"]}),W.bathrooms&&a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(nv,{className:"h-4 w-4",style:{color:Xi}}),W.bathrooms," ba"]}),W.square_footage&&a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(o9,{className:"h-4 w-4",style:{color:Xi}}),W.square_footage.toLocaleString()," sf"]})]}),W.description&&a.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:W.description}),a.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Xi},children:["View Residence ",a.jsx(ra,{className:"h-4 w-4"})]})]})]})})]})}),a.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:zre},children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[a.jsxs("div",{className:"text-center mb-14",children:[a.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[a.jsx("span",{className:"h-px w-10",style:{background:Xi}}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),a.jsx("span",{className:"h-px w-10",style:{background:Xi}})]}),a.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",a.jsx("span",{className:"italic",style:{color:Wg},children:"carefully considered"}),"."]}),a.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?a.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((ue,_e)=>a.jsxs("div",{className:"space-y-3",children:[a.jsx(dl,{className:"aspect-[4/5] bg-white/5"}),a.jsx(dl,{className:"h-6 w-32 bg-white/5"}),a.jsx(dl,{className:"h-4 w-full bg-white/5"})]},_e))}):Z.length>0?a.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:Z.map(ue=>{var we,Ce,Me,Ae,be;const _e=((we=ue.photos)==null?void 0:we.find(me=>me.is_primary))||((Ce=ue.photos)==null?void 0:Ce[0]);return a.jsxs(mn,{to:G(ue),className:"group lu-card-hover block",children:[a.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[_e?a.jsx("img",{src:_e.photo_url,alt:ue.property_address||ue.city,className:"w-full h-full object-cover lu-img-zoom"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(La,{className:"h-12 w-12 text-white/20"})}),a.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%)"}}),a.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:Xi,border:`1px solid ${Xi}`},children:Cz[ue.status]}),a.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&&a.jsxs("span",{children:[ue.bedrooms," bd"]}),ue.bathrooms&&a.jsxs("span",{children:[ue.bathrooms," ba"]}),ue.square_footage&&a.jsxs("span",{children:[ue.square_footage.toLocaleString()," sf"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[a.jsx(qs,{className:"h-3 w-3",style:{color:Xi}}),ue.city,ue.state?`, ${ue.state}`:""]}),a.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:Wg},children:D(ue.price)}),ue.property_address&&a.jsx("p",{className:"text-white/70 text-sm truncate",children:ue.property_address}),((Me=ue.agent)==null?void 0:Me.name)&&a.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[a.jsx(go,{className:"h-3 w-3"}),ue.agent.name,(((Ae=ue.agent.brokerage)==null?void 0:Ae.name)||ue.agent.brokerage_name)&&a.jsxs("span",{className:"truncate",children:["· ",((be=ue.agent.brokerage)==null?void 0:be.name)||ue.agent.brokerage_name]})]})]})]},ue.id)})}):a.jsxs("div",{className:"text-center py-20",children:[a.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Xi}`},children:a.jsx(La,{className:"h-8 w-8",style:{color:Xi}})}),a.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),a.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),B&&a.jsx(zt,{onClick:M,style:{background:Xi,color:nw},className:"hover:brightness-110",children:"Clear filters"})]})]})}),P&&P.length>0&&a.jsx("section",{id:"map",className:"py-20 md:py-28",children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[a.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("span",{className:"h-px w-10",style:{background:Xi}}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),a.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",a.jsx("span",{className:"italic",style:{color:Wg},children:"on the map"}),"."]})]})}),a.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:a.jsx(TZe,{listings:P,isLoading:R})})]})}),a.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[a.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${nw} 70%)`}}),a.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[a.jsx("span",{className:"h-px w-10",style:{background:Xi}}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),a.jsx("span",{className:"h-px w-10",style:{background:Xi}})]}),a.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",a.jsx("br",{}),a.jsx("span",{className:"italic",style:{color:Wg},children:"stage this good"}),"."]}),a.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."}),a.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:Xi,color:nw},children:["Explore LevelUp",a.jsx(ra,{className:"h-4 w-4"})]})]})]}),a.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("img",{src:Ore,alt:"LevelUp",className:"h-6"}),a.jsx("span",{className:"h-4 w-px bg-white/20"}),a.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),a.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),a.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),a.jsx(RYe,{}),a.jsx(LYe,{})]})}const AZe=Object.freeze(Object.defineProperty({__proto__:null,default:gve},Symbol.toStringTag,{value:"Module"})),jZe=I.lazy(()=>Fe(()=>import("./PublicHomeValue-Jyz-AuXT.js"),[]));function kZe(){const t=Bi(),e=window.location.hostname;if(!(e==="listings.relevelup.com"||e.startsWith("listings.")))return null;const n=t.pathname.slice(1);return!n||n===""?a.jsx(gve,{}):n==="home-value"||n==="whats-my-home-worth"?a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(jZe,{})}):n.startsWith("public/")?null:a.jsx(Z7,{slugOverride:n})}const CZe=I.lazy(()=>Fe(()=>import("./CommercialMarketplace-CQzNtviw.js"),[]));function IZe(){const e=Bi().pathname.slice(1);return e?e.startsWith("public/")?null:a.jsx(Z7,{slugOverride:e}):a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:a.jsx(CZe,{})})}function L3({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 a.jsx("div",{className:`rounded-2xl p-4 mb-6 ${i.container}`,children:a.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&a.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[t.brokerage_logo_url&&a.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&&a.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.brokerage_display_name})]}),n&&a.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[t.team_logo_url&&a.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&&a.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.team_name})]})]})})}const NZe=t=>gr({queryKey:["agent-card-public",t],queryFn:async()=>{if(!t)throw new Error("No slug provided");const{data:e,error:r}=await Re.from("agent_cards").select("*").eq("slug",t).eq("is_published",!0).single();if(r)throw r;const{data:n}=await Re.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 Re.from("brokerages").select("name").eq("id",n.brokerage_id).single();i=(s==null?void 0:s.name)||null}let o=null;try{const{data:s}=await Re.from("profiles").select("avatar_url").eq("id",e.user_id).single();if(s!=null&&s.avatar_url)o=s.avatar_url;else{const{data:f}=await Re.storage.from("avatars").list(`${e.user_id}`);if(f&&f.length>0){const{data:p}=Re.storage.from("avatars").getPublicUrl(`${e.user_id}/${f[0].name}`);o=`${p.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:o}},enabled:!!t}),J8t=()=>gr({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:t,error:e}=await Re.from("agent_cards").select("*").order("created_at",{ascending:!1});if(e)throw e;return t}}),eqt=t=>gr({queryKey:["agent-card",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_cards").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),tqt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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"]}),Gt.success("Agent card created")},onError:e=>Gt.error(e.message)})},rqt=()=>{const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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"]}),Gt.success("Agent card updated")},onError:e=>Gt.error(e.message)})},es=async(t,e,r,n)=>{const i=new URLSearchParams(window.location.search);await Re.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:{}})},PZe=async(t,e)=>{const{error:r}=await Re.from("agent_card_leads").insert({card_id:t,...e});if(r)throw r},nqt=t=>gr({queryKey:["agent-card-analytics",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.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 Re.from("agent_card_leads").select("*").eq("card_id",t).order("created_at",{ascending:!1});if(i)throw i;const o=(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:o,clicks:c,saves:s,leads:n||[],interactions:e||[]}},enabled:!!t});function D3({open:t,onOpenChange:e,cardId:r,type:n,agentName:i}){const[o,c]=I.useState(""),[s,f]=I.useState(""),[p,y]=I.useState(""),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(!1),D=async M=>{if(M.preventDefault(),!o.trim()){Gt.error("Please enter your name");return}R(!0);try{await PZe(r,{lead_type:n,name:o.trim(),email:s.trim()||void 0,phone:p.trim()||void 0,message:E.trim()||void 0,intent:_||void 0}),es(r,"lead_submitted",n),Re.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:o.trim(),email:s.trim()||void 0,phone:p.trim()||void 0,message:E.trim()||void 0,intent:_||void 0}}).catch(B=>console.error("Card lead notify failed:",B)),Gt.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(""),y(""),T(""),k("")}catch{Gt.error("Something went wrong. Please try again.")}finally{R(!1)}};return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"sm:max-w-md rounded-2xl",children:[a.jsxs(ml,{children:[a.jsx(Ko,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),a.jsx(gd,{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?`})]}),a.jsxs("form",{onSubmit:D,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lead-name",children:"Name *"}),a.jsx($r,{id:"lead-name",value:o,onChange:M=>c(M.target.value),placeholder:"Your name",required:!0})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lead-phone",children:"Phone"}),a.jsx($r,{id:"lead-phone",type:"tel",value:p,onChange:M=>y(M.target.value),placeholder:"(555) 123-4567"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lead-email",children:"Email"}),a.jsx($r,{id:"lead-email",type:"email",value:s,onChange:M=>f(M.target.value),placeholder:"you@example.com"})]}),n==="booking"&&a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lead-intent",children:"I'm looking to..."}),a.jsxs(_a,{value:_,onValueChange:T,children:[a.jsx(aa,{children:a.jsx(va,{placeholder:"Select one"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"buy",children:"Buy a home"}),a.jsx(fn,{value:"sell",children:"Sell my home"}),a.jsx(fn,{value:"both",children:"Buy & Sell"}),a.jsx(fn,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),a.jsx($r,{id:"lead-message",value:E,onChange:M=>k(M.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),a.jsx(zt,{type:"submit",className:"w-full rounded-2xl",disabled:P,children:P?"Sending...":"Submit"})]})]})})}const RZe=t=>gr({queryKey:["card-blocks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.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}),iqt=t=>gr({queryKey:["card-blocks-all",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("card_blocks").select("*").eq("card_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),sqt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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]}),Gt.success("Block added")},onError:e=>Gt.error(e.message)})},aqt=()=>{const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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"]}),Gt.success("Block updated")},onError:e=>Gt.error(e.message)})},oqt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("card_blocks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),Gt.success("Block removed")},onError:e=>Gt.error(e.message)})};function LZe(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 DZe(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 MZe={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 OZe({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=DZe(r.video_url),o=n||!!i,c=n?LZe(r.video_url):i||r.video_url;return a.jsx("div",{className:MZe[e],children:o?a.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:a.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})}):a.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const FZe={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 BZe({block:t,variant:e}){const n=t.config.testimonials||[],[i,o]=I.useState(0);if(n.length===0)return null;const c=FZe[e],s=n[i];return a.jsxs("div",{className:c.container,children:[a.jsxs("div",{className:c.card,children:[a.jsx(xDe,{className:"h-4 w-4 mb-2 opacity-30"}),a.jsxs("p",{className:`${c.quote} mb-3`,children:['"',s.quote,'"']}),a.jsxs("div",{children:[a.jsx("p",{className:c.name,children:s.name}),s.role&&a.jsx("p",{className:c.role,children:s.role})]})]}),n.length>1&&a.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[a.jsx("button",{onClick:()=>o(f=>(f-1+n.length)%n.length),className:c.nav,children:a.jsx(xm,{className:"h-4 w-4"})}),a.jsx("div",{className:"flex gap-1.5",children:n.map((f,p)=>a.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${p===i?c.dot:c.dotInactive}`,onClick:()=>o(p)},p))}),a.jsx("button",{onClick:()=>o(f=>(f+1)%n.length),className:c.nav,children:a.jsx(vd,{className:"h-4 w-4"})})]})]})}const zZe={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 $Ze({block:t,variant:e}){const n=t.config.tags||[];if(n.length===0)return null;const i=zZe[e];return a.jsx("div",{className:i.container,children:n.map((o,c)=>a.jsx("span",{className:i.tag,children:o},c))})}const UZe={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 VZe({block:t,cardId:e,variant:r}){const i=t.config.links||[];if(i.length===0)return null;const o=UZe[r];return a.jsx("div",{className:o.container,children:i.map((c,s)=>a.jsxs("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(e,"button_click",`custom_link_${c.label}`),className:o.link,children:[a.jsx("span",{children:c.label}),a.jsx(iv,{className:`h-4 w-4 ${o.icon}`})]},s))})}const qZe={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 GZe({path:t,color:e,size:r=20}){return a.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:e,children:a.jsx("path",{d:t})})}const HZe={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 WZe({block:t,cardId:e,variant:r}){const i=t.config.platforms||[],o=HZe[r];return i.length===0?null:a.jsxs("div",{className:o.container,children:[a.jsx("h3",{className:o.title,children:"Follow Me"}),a.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:i.map((c,s)=>{const f=qZe[c.platform.toLowerCase()];return!f||!c.url?null:a.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(e,"button_click",`social_${c.platform}`),className:o.linkClass,title:f.label,children:a.jsx(GZe,{path:f.icon,color:f.color})},s)})})]})}function M3({cardId:t,variant:e}){const{data:r}=RZe(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"),o=n.length>0?{...n[0],config:{platforms:n.flatMap(c=>c.config.platforms||[])}}:null;return r.findIndex(c=>c.block_type==="social_media"),a.jsxs(a.Fragment,{children:[i.map(c=>{switch(c.block_type){case"video_intro":return a.jsx(OZe,{block:c,variant:e},c.id);case"testimonials":return a.jsx(BZe,{block:c,variant:e},c.id);case"specialties":return a.jsx($Ze,{block:c,variant:e},c.id);case"custom_links":return a.jsx(VZe,{block:c,cardId:t,variant:e},c.id);default:return null}}),o&&a.jsx(WZe,{block:o,cardId:t,variant:e})]})}async function KZe(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 o=new FileReader;o.onloadend=()=>{const s=o.result.split(",")[1];i({base64:s,mimeType:n})},o.onerror=()=>i(null),o.readAsDataURL(r)})}catch{return null}}function YZe(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 O3(t){const{first:e,last:r}=YZe(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 KZe(t.avatarUrl);if(s){const p={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[s.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${p}:${s.base64}`)}}n.push("END:VCARD");const i=new Blob([n.join(`\r `)],{type:"text/vcard"}),o=URL.createObjectURL(i),c=document.createElement("a");c.href=o,c.download=`${t.name.replace(/\s+/g,"_")}.vcf`,c.click(),URL.revokeObjectURL(o),Gt.success("Contact saved!")}function ZZe({card:t}){var D;const[e,r]=I.useState(!1),[n,i]=I.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Gt.error("Phone number not available")}),p=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Gt.error("Phone number not available")}),y=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Gt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),O3({name:o,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()=>{es(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:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Gt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return a.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[a.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[a.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&a.jsxs(fd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[a.jsx(md,{src:t.avatar_url||void 0,alt:o}),a.jsx(pd,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:c})]}),a.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:o}),t.title&&a.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&a.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&a.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:t.team_name}),t.positioning_statement&&a.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',t.positioning_statement,'"']})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[a.jsxs(zt,{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:[a.jsx(ai,{className:"h-5 w-5"}),a.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),a.jsxs(zt,{onClick:p,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[a.jsx(of,{className:"h-5 w-5"}),a.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),a.jsxs(zt,{onClick:y,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:[a.jsx(Ti,{className:"h-5 w-5"}),a.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),a.jsxs(zt,{onClick:_,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[a.jsx(yo,{className:"h-5 w-5 mr-2"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&a.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:a.jsxs("div",{className:"text-center flex items-center gap-1",children:[a.jsx(ru,{className:"h-4 w-4 text-amber-500 fill-amber-500"}),a.jsx("span",{className:"font-bold text-slate-900",children:"5.0"})]})}),t.review_snippet&&a.jsx("div",{className:"bg-slate-50 rounded-2xl p-4 mb-6 border border-slate-100",children:a.jsxs("p",{className:"text-sm text-slate-600 italic text-center",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&a.jsxs("div",{className:"mb-6",children:[a.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-2",children:"About Me"}),a.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.bio})]}),a.jsx(L3,{card:t,variant:"standard"}),a.jsx(M3,{cardId:t.id,variant:"standard"}),a.jsxs("div",{className:"space-y-2 mb-6",children:[t.show_save_contact&&a.jsxs(zt,{variant:"ghost",onClick:T,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[a.jsx(rc,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),t.show_leave_review&&t.review_source_url&&a.jsxs(zt,{variant:"ghost",onClick:()=>{es(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:[a.jsx(ru,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),t.show_refer_friend&&a.jsxs(zt,{variant:"ghost",onClick:k,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[a.jsx(ul,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),a.jsxs(zt,{variant:"ghost",onClick:P,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[a.jsx(LO,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),a.jsxs(zt,{variant:"ghost",onClick:E,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[a.jsx(eC,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&a.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>a.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(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))}),a.jsx("div",{className:"text-center",children:a.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),a.jsx(D3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function XZe({card:t}){var D;const[e,r]=I.useState(!1),[n,i]=I.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Gt.error("Phone number not available")}),p=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Gt.error("Phone number not available")}),y=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Gt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),O3({name:o,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()=>{es(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:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Gt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return a.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[a.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[a.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),a.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&a.jsxs(fd,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[a.jsx(md,{src:t.avatar_url||void 0,alt:o}),a.jsx(pd,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:c})]}),a.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:o}),t.title&&a.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&a.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&&a.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&a.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),a.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:ai,label:"Call",handler:f},{icon:of,label:"Text",handler:p},{icon:Ti,label:"Email",handler:y}].map(({icon:M,label:B,handler:V})=>a.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:[a.jsx(M,{className:"h-5 w-5 text-[#c9a84c]"}),a.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:B})]},B))}),a.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:[a.jsx(yo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&a.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:a.jsxs("div",{className:"text-center flex items-center gap-1",children:[a.jsx(ru,{className:"h-4 w-4 text-[#c9a84c] fill-[#c9a84c]"}),a.jsx("span",{className:"font-bold text-white",children:"5.0"})]})}),t.review_snippet&&a.jsx("div",{className:"bg-[#1e2636] rounded-xl p-4 mb-6 border border-[#c9a84c]/10",children:a.jsxs("p",{className:"text-sm text-[#a0aec0] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&a.jsxs("div",{className:"mb-6",children:[a.jsx("h2",{className:"text-sm font-semibold text-[#c9a84c] mb-2 tracking-wide uppercase",children:"About"}),a.jsx("p",{className:"text-sm text-[#a0aec0] leading-relaxed",children:t.bio})]}),a.jsx(L3,{card:t,variant:"luxury"}),a.jsx(M3,{cardId:t.id,variant:"luxury"}),a.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&a.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:[a.jsx(rc,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&a.jsxs("button",{onClick:()=>{es(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:[a.jsx(ru,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),t.show_refer_friend&&a.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[a.jsx(ul,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),a.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[a.jsx(LO,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),a.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:[a.jsx(eC,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&a.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>a.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(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))}),a.jsx("div",{className:"text-center",children:a.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),a.jsx(D3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function QZe({card:t}){var B,V,G,W;const[e,r]=I.useState(!1),[n,i]=I.useState("booking"),o=((B=t.profile)==null?void 0:B.name)||"Agent",c=o.split(" ").map(Z=>Z[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=(Z,Q)=>{const re=parseInt(Z.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 p=(Z,Q)=>{es(t.id,"button_click",Z),Q()},y=()=>p("call",()=>{var Z;(Z=t.profile)!=null&&Z.phone?window.location.href=`tel:${t.profile.phone}`:Gt.error("Phone number not available")}),_=()=>p("text",()=>{var Z;(Z=t.profile)!=null&&Z.phone?window.location.href=`sms:${t.profile.phone}`:Gt.error("Phone number not available")}),T=()=>p("email",()=>{var Z;(Z=t.profile)!=null&&Z.email?window.location.href=`mailto:${t.profile.email}`:Gt.error("Email not available")}),E=()=>{t.booking_url?p("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},k=()=>{var Z,Q;es(t.id,"contact_saved"),O3({name:o,phone:(Z=t.profile)==null?void 0:Z.phone,email:(Q=t.profile)==null?void 0:Q.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},P=async()=>{es(t.id,"share_event");const Z=`https://cards.relevelup.com/${t.slug}`,Q="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:Q,url:Z})}catch{}else await navigator.clipboard.writeText(Z),Gt.success("Link copied!")},R=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},D=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},M={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return a.jsxs("div",{className:"min-h-screen",style:{backgroundColor:s.accent},children:[a.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:s.dark},children:[t.show_photo&&a.jsxs(fd,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${s.accent}`},children:[a.jsx(md,{src:t.avatar_url||void 0,alt:o}),a.jsx(pd,{className:"text-2xl font-black text-white",style:{backgroundColor:s.accent},children:c})]}),a.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:o}),t.title&&a.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${s.accent}cc`},children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&a.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&&a.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:t.team_name})]}),a.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[a.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[t.positioning_statement&&a.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}),a.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:ai,label:"Call",handler:y},{icon:of,label:"Text",handler:_},{icon:Ti,label:"Email",handler:T}].map(({icon:Z,label:Q,handler:re})=>a.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:[a.jsx(Z,{className:"h-5 w-5"}),a.jsx("span",{className:"text-xs",children:Q})]},Q))}),a.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:[a.jsx(yo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&a.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:t.review_snippet&&a.jsxs("div",{className:"text-center flex items-center gap-1",children:[a.jsx(ru,{className:"h-5 w-5",style:{color:s.accent,fill:s.accent}}),a.jsx("span",{className:"font-black text-2xl",style:{color:s.dark},children:"5.0"})]})}),t.review_snippet&&a.jsx("div",{className:"rounded-2xl p-4 mb-6",style:{backgroundColor:`${s.accent}15`},children:a.jsxs("p",{className:"text-sm font-medium text-center",style:{color:s.dark},children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&a.jsxs("div",{className:"mb-6",children:[a.jsx("h2",{className:"text-xs font-black mb-2 uppercase tracking-wider",style:{color:s.accent},children:"About Me"}),a.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:t.bio})]}),a.jsx(L3,{card:t,variant:"bold"}),a.jsx(M3,{cardId:t.id,variant:"bold"}),a.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&a.jsxs("button",{onClick:k,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:[a.jsx(rc,{className:"h-4 w-4",style:{color:s.accent}})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&a.jsxs("button",{onClick:()=>{es(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:[a.jsx(ru,{className:"h-4 w-4",style:{color:s.accent}})," Leave a Review"]}),t.show_refer_friend&&a.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:[a.jsx(ul,{className:"h-4 w-4",style:{color:s.accent}})," Refer a Friend"]}),a.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:[a.jsx(LO,{className:"h-4 w-4",style:{color:s.accent}})," Connect with Me"]}),a.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:s.dark},children:[a.jsx(eC,{className:"h-4 w-4",style:{color:s.accent}})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&a.jsx("div",{className:"flex justify-center gap-4 mb-6",children:t.social_links.slice(0,3).map((Z,Q)=>a.jsx("a",{href:Z.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(t.id,"button_click",`social_${Z.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:s.dark},children:M[Z.platform.toLowerCase()]||"🔗"},Q))})]}),a.jsx("div",{className:"text-center py-6",children:a.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),a.jsx(D3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function JZe({card:t}){var D;const[e,r]=I.useState(!1),[n,i]=I.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Gt.error("Phone number not available")}),p=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Gt.error("Phone number not available")}),y=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Gt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),O3({name:o,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()=>{es(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:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Gt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return a.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[a.jsx("div",{className:"bg-[#1b3a4b] h-2"}),a.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[a.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&a.jsxs(fd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[a.jsx(md,{src:t.avatar_url||void 0,alt:o}),a.jsx(pd,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:c})]}),a.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:o}),t.title&&a.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&a.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&a.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&a.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),a.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:ai,label:"Call",handler:f},{icon:of,label:"Text",handler:p},{icon:Ti,label:"Email",handler:y}].map(({icon:M,label:B,handler:V})=>a.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:[a.jsx(M,{className:"h-5 w-5 text-[#1b3a4b]"}),a.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:B})]},B))}),a.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:[a.jsx(yo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&a.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:a.jsx("div",{className:"flex items-center justify-center gap-6",children:a.jsxs("div",{className:"text-center flex items-center gap-1",children:[a.jsx(ru,{className:"h-4 w-4 text-[#d4a843] fill-[#d4a843]"}),a.jsx("span",{className:"font-bold text-[#1b3a4b] font-serif",children:"5.0"})]})})}),t.review_snippet&&a.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:a.jsxs("p",{className:"text-sm text-[#4a5568] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&a.jsxs("div",{className:"mb-6",children:[a.jsx("h2",{className:"text-sm font-semibold text-[#1b3a4b] mb-2 font-serif",children:"About"}),a.jsx("p",{className:"text-sm text-[#4a5568] leading-relaxed",children:t.bio})]}),a.jsx(L3,{card:t,variant:"classic"}),a.jsx(M3,{cardId:t.id,variant:"classic"}),a.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[t.show_save_contact&&a.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:[a.jsx(rc,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&a.jsxs("button",{onClick:()=>{es(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:[a.jsx(ru,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),t.show_refer_friend&&a.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[a.jsx(ul,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),a.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[a.jsx(LO,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),a.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:[a.jsx(eC,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&a.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>a.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(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))}),a.jsx("div",{className:"text-center",children:a.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),a.jsx(D3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function eXe({card:t}){switch(t.theme){case"luxury":return a.jsx(XZe,{card:t});case"bold":return a.jsx(QZe,{card:t});case"classic":return a.jsx(JZe,{card:t});case"standard":default:return a.jsx(ZZe,{card:t})}}function tXe(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 rXe(t){return`https://docs.google.com/gview?url=${encodeURIComponent(t)}&embedded=true`}function nXe(){if(typeof window>"u")return null;const t=tXe(new URLSearchParams(window.location.search).get("oh_disclosure"));return t?a.jsx("div",{className:"sticky top-0 z-50 bg-primary text-primary-foreground shadow-md",children:a.jsxs("div",{className:"mx-auto flex max-w-md items-center justify-between gap-3 px-4 py-2.5",children:[a.jsx("span",{className:"text-sm font-medium",children:"Thanks for visiting the open house!"}),a.jsxs("a",{href:rXe(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:[a.jsx(cm,{className:"h-3.5 w-3.5"})," See Disclosures"]})]})}):null}function iXe(){const t=Bi();I.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),a.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):a.jsx(sXe,{slug:e})}function sXe({slug:t}){return a.jsx(aXe,{slug:t})}function aXe({slug:t}){var o;const{data:e,isLoading:r,error:n}=NZe(t);if(I.useEffect(()=>{e!=null&&e.id&&es(e.id,"card_view")},[e==null?void 0:e.id]),r)return a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(dl,{className:"h-28 w-28 rounded-full"}),a.jsx(dl,{className:"h-6 w-48"}),a.jsx(dl,{className:"h-4 w-36"})]}),a.jsx(dl,{className:"h-12 w-full"}),a.jsx(dl,{className:"h-12 w-full"})]})});if(n||!e)return a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),a.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const i=((o=e.profile)==null?void 0:o.name)||"Agent";return a.jsxs(a.Fragment,{children:[a.jsxs(Wo,{children:[a.jsxs("title",{children:[i," | Real Estate Agent"]}),a.jsx("meta",{name:"description",content:e.positioning_statement||`Connect with ${i}, your trusted real estate professional.`}),a.jsx("meta",{property:"og:title",content:`${i} | Real Estate Agent`}),a.jsx("meta",{property:"og:description",content:e.positioning_statement||`Connect with ${i}`}),e.avatar_url&&a.jsx("meta",{property:"og:image",content:e.avatar_url})]}),a.jsx(nXe,{}),a.jsx(eXe,{card:e})]})}function oXe({presentationId:t,ctaLabel:e,agentName:r,prefillName:n,prefillEmail:i,prefillPhone:o}){const[c,s]=I.useState(n||""),[f,p]=I.useState(i||""),[y,_]=I.useState(o||""),[T,E]=I.useState(""),[k,P]=I.useState(""),[R,D]=I.useState(!1),[M,B]=I.useState(!1),V=async G=>{if(G.preventDefault(),!c.trim()){Gt.error("Please enter your name");return}D(!0);try{const{error:W}=await Re.from("smart_presentation_leads").insert({presentation_id:t,name:c.trim(),email:f.trim()||null,phone:y.trim()||null,intent:T||null,message:k.trim()||null});if(W)throw W;try{await Re.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{}Re.functions.invoke("presentation-lead-notify",{body:{presentationId:t,name:c.trim(),email:f.trim()||void 0,phone:y.trim()||void 0,intent:T||void 0,message:k.trim()||void 0}}).catch(Z=>console.error("Presentation lead notify failed:",Z)),B(!0)}catch{Gt.error("Something went wrong. Please try again.")}finally{D(!1)}};return M?a.jsxs("div",{className:"text-center py-8",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:a.jsx(ko,{className:"h-8 w-8 text-emerald-600"})}),a.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),a.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):a.jsxs("form",{onSubmit:V,className:"space-y-4 max-w-md mx-auto",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"pres-lead-name",children:"Name *"}),a.jsx($r,{id:"pres-lead-name",value:c,onChange:G=>s(G.target.value),placeholder:"Your name",required:!0})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"pres-lead-phone",children:"Phone"}),a.jsx($r,{id:"pres-lead-phone",type:"tel",value:y,onChange:G=>_(G.target.value),placeholder:"(555) 123-4567"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"pres-lead-email",children:"Email"}),a.jsx($r,{id:"pres-lead-email",type:"email",value:f,onChange:G=>p(G.target.value),placeholder:"you@example.com"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),a.jsxs(_a,{value:T,onValueChange:E,children:[a.jsx(aa,{children:a.jsx(va,{placeholder:"Select one"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"buy",children:"Buy a home"}),a.jsx(fn,{value:"sell",children:"Sell my home"}),a.jsx(fn,{value:"both",children:"Buy & Sell"}),a.jsx(fn,{value:"other",children:"Something else"})]})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"pres-lead-message",children:"Message (optional)"}),a.jsx($r,{id:"pres-lead-message",value:k,onChange:G=>P(G.target.value),placeholder:"Anything you'd like us to know"})]}),a.jsx(zt,{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 lXe(){const t=Bi();I.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),a.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):a.jsx(cXe,{shareToken:e})}function cXe({shareToken:t}){var k;const[e,r]=I.useState(null),[n,i]=I.useState(!0),[o,c]=I.useState(0),[s,f]=I.useState(!1);I.useEffect(()=>{p()},[t]);const p=async()=>{const{data:P,error:R}=await Re.from("smart_presentations").select("*").eq("share_token",t).eq("status","published").single();if(R||!P){f(!0),i(!1);return}const{data:D}=await Re.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",P.owner_user_id).single();let M;if(D!=null&&D.brokerage_id){const{data:V}=await Re.from("brokerages").select("name").eq("id",D.brokerage_id).single();M=(V==null?void 0:V.name)||void 0}let B=null;if(P.contact_id){const{data:V}=await Re.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",P.contact_id).single();B=V}r({...P,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 Re.rpc("log_presentation_view",{p_presentation_id:P.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},y=async()=>{if(e){try{await Re.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")}},_=P=>{const R=P.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(R)return`https://www.youtube.com/embed/${R[1]}?rel=0`;if(P.includes("iframe.mediadelivery.net/play/")){const B=P.replace("/play/","/embed/"),V=B.includes("?")?"&":"?";return`${B}${V}responsive=true`}if(P.includes("iframe.mediadelivery.net")){const B=P.includes("?")?"&":"?";return`${P}${B}responsive=true`}const D=P.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(D)return`https://www.loom.com/embed/${D[1]}`;const M=P.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return M?`https://iframe.mediadelivery.net/embed/${M[1]}/${M[2]}?responsive=true`:P};if(n)return a.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:a.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[a.jsx(dl,{className:"h-12 w-3/4 mx-auto"}),a.jsx(dl,{className:"h-64 w-full"}),a.jsx(dl,{className:"h-8 w-1/2 mx-auto"})]})});if(s||!e)return a.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),a.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const T=e.sections.filter(P=>P.is_visible!==!1),E=T[o];return a.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[a.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:a.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:a.jsxs("div",{className:"flex items-center gap-3",children:[e.owner_avatar&&a.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),a.jsxs("div",{className:"text-right text-sm",children:[a.jsx("p",{className:"font-semibold text-gray-900",children:e.owner_name}),e.owner_title&&a.jsx("p",{className:"text-gray-500 text-xs",children:e.owner_title}),e.brokerage_name&&!e.owner_title&&a.jsx("p",{className:"text-gray-500 text-xs",children:e.brokerage_name})]})]})})}),a.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[a.jsxs("div",{className:"text-center mb-8",children:[a.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&&a.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",a.jsx("strong",{children:e.property_address}),"."]})]}),a.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[a.jsxs("div",{className:"md:col-span-3",children:[E!=null&&E.video_url?a.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:a.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?a.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:a.jsx("img",{src:E.image_url,alt:E.title,className:"w-full h-auto object-cover",loading:"lazy"})}):a.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:[a.jsx("span",{className:"text-5xl mb-3",children:E==null?void 0:E.icon}),a.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:E==null?void 0:E.title}),a.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:E==null?void 0:E.description})]}),(E==null?void 0:E.text)&&a.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}})]}),a.jsx("div",{className:"md:col-span-2 space-y-3",children:T.map((P,R)=>a.jsx("button",{onClick:()=>c(R),className:sr("w-full text-left p-4 rounded-xl border transition-all",o===R?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(R+1).padStart(2,"0"),"."]}),a.jsxs("div",{children:[a.jsx("span",{className:"mr-2",children:P.icon}),a.jsx("span",{className:"font-semibold text-gray-900",children:P.title}),a.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:P.description})]})]})},R))})]}),a.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&&a.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"}),a.jsx("h3",{className:"text-lg font-bold text-gray-900",children:e.owner_name}),e.owner_title&&a.jsx("p",{className:"text-sm text-gray-500",children:e.owner_title}),e.brokerage_name&&a.jsx("p",{className:"text-sm text-gray-500",children:e.brokerage_name}),a.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[e.owner_phone&&a.jsx("a",{href:`tel:${e.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:e.owner_phone}),e.owner_email&&a.jsx("a",{href:`mailto:${e.owner_email}`,className:"hover:text-blue-600 transition-colors",children:e.owner_email})]})]}),e.cta_label&&a.jsxs("div",{className:"text-center mt-8 py-8",children:[a.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(k=e.cta_url)!=null&&k.trim()?a.jsxs(zt,{size:"lg",onClick:y,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[e.cta_label,a.jsx(iv,{className:"h-5 w-5 ml-2"})]}):a.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:a.jsx(oXe,{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})})]})]}),a.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 lqt(){const{user:t}=Gn(),e=Gi(),{data:r}=GS();return gr({queryKey:["open-houses",e,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:i}=await Re.from("open_houses").select("*").eq("agent_id",e).order("event_date",{ascending:!1});if(i)throw i;let o=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:c,error:s}=await Re.rpc("get_team_open_houses",{_user_id:e});if(!s&&c){const f=[...new Set(c.map(_=>_.agent_id))],p={};if(f.length>0){const{data:_}=await Re.from("profiles").select("id, name").in("id",f);_==null||_.forEach(T=>{T.name&&(p[T.id]=T.name)})}const y=c.map(_=>({..._,agent_name:p[_.agent_id]||void 0}));o=[...o,...y]}}return o.sort((c,s)=>s.event_date.localeCompare(c.event_date)),o},enabled:!!t&&!!e})}function cqt(t){const{user:e}=Gn();return gr({queryKey:["open-house",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_houses").select("*").eq("id",t).single();if(n)throw n;return r},enabled:!!e&&!!t})}function uqt(t){const{user:e}=Gn(),r=Nr();return I.useEffect(()=>{if(!t)return;const n=`visitors-${t}-${Math.random().toString(36).slice(2,10)}`,i=Re.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()=>{Re.removeChannel(i)}},[t,r]),gr({queryKey:["open-house-visitors",t],queryFn:async()=>{const{data:n,error:i}=await Re.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 dqt(){const t=Nr(),e=Gi();return kr({mutationFn:async r=>{const{data:n,error:i}=await Re.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 hqt(){const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{error:n}=await Re.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 fqt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("open_houses").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Ts({title:"Open house deleted"})}})}function yve(t){return gr({queryKey:["public-open-house",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 Re.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 mqt(t){const{user:e}=Gn();return gr({queryKey:["survey-questions",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;return r},enabled:!!e&&!!t})}function uXe(t){return gr({queryKey:["public-survey-questions",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 dXe(){return kr({mutationFn:async t=>{const{error:e}=await Re.from("open_house_survey_responses").insert(t);if(e)throw e}})}function pqt(t){const{user:e}=Gn();return gr({queryKey:["survey-responses",t],queryFn:async()=>{const{data:r,error:n}=await Re.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:o,error:c}=await Re.from("open_house_survey_responses").select("*").in("question_id",i).order("created_at",{ascending:!1});if(c)throw c;return{questions:r,responses:o||[]}},enabled:!!e&&!!t})}function gqt(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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 yqt(){const t=Nr();return kr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Re.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 xqt(){const t=Nr();return kr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.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 _qt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.rpc("seed_default_survey_questions",{_open_house_id:e});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r]})}})}function hXe(){return kr({mutationFn:async t=>{const e=crypto.randomUUID(),{error:r}=await Re.from("open_house_visitors").insert({...t,id:e});if(r)throw r;return{id:e}}})}function fXe(){return kr({mutationFn:async({visitor_id:t,...e})=>{const{error:r}=await Re.from("open_house_visitors").update(e).eq("id",t);if(r)throw r}})}function mXe(){return kr({mutationFn:async t=>{await Re.rpc("increment_open_house_scan",{_slug:t})}})}async function xve(t){const{data:e,error:r}=await Re.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:o,error:c}=await Re.from("open_house_room_media").select("*").in("room_id",i).order("sort_order");if(c)throw c;const s={};return(o||[]).forEach(f=>{var y;const p=f;(s[y=p.room_id]||(s[y]=[])).push(p)}),n.map(f=>({...f,media:s[f.id]||[]}))}function vqt(t){const{user:e}=Gn();return gr({queryKey:["open-house-rooms",t],queryFn:()=>xve(t),enabled:!!e&&!!t})}function pXe(t){return gr({queryKey:["public-open-house-rooms",t],queryFn:()=>xve(t),enabled:!!t})}function bqt(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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 wqt(){const t=Nr();return kr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Re.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 Sqt(){const t=Nr();return kr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.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 Tqt(){const t=Nr();return kr({mutationFn:async({open_house_id:e,...r})=>{const{data:n,error:i}=await Re.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 Eqt(){const t=Nr();return kr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.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 Aqt(){const t=Nr();return kr({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 o=new Map(i.map(s=>[s.id,s])),c=r.map((s,f)=>({...o.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 jqt(){const t=Nr();return kr({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 o=t.getQueryData(i);return o&&t.setQueryData(i,o.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,p)=>{const y=s.get(f);return y?{...y,sort_order:p}:null}).filter(Boolean)}})),{prev:o,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 kqt(t){const{user:e}=Gn();return gr({queryKey:["open-house-leads",t],queryFn:async()=>{const{data:r,error:n}=await Re.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 Cqt(){const t=Nr();return kr({mutationFn:async({id:e,status:r,open_house_id:n})=>{const{error:i}=await Re.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 F3="Switch",[gXe,Iqt]=Yo(F3),[yXe,xXe]=gXe(F3),_ve=I.forwardRef((t,e)=>{const{__scopeSwitch:r,name:n,checked:i,defaultChecked:o,required:c,disabled:s,value:f="on",onCheckedChange:p,form:y,..._}=t,[T,E]=I.useState(null),k=Kn(e,B=>E(B)),P=I.useRef(!1),R=T?y||!!T.closest("form"):!0,[D,M]=dd({prop:i,defaultProp:o??!1,onChange:p,caller:F3});return a.jsxs(yXe,{scope:r,checked:D,disabled:s,children:[a.jsx(rn.button,{type:"button",role:"switch","aria-checked":D,"aria-required":c,"data-state":Sve(D),"data-disabled":s?"":void 0,disabled:s,value:f,..._,ref:k,onClick:Or(t.onClick,B=>{M(V=>!V),R&&(P.current=B.isPropagationStopped(),P.current||B.stopPropagation())})}),R&&a.jsx(wve,{control:T,bubbles:!P.current,name:n,value:f,checked:D,required:c,disabled:s,form:y,style:{transform:"translateX(-100%)"}})]})});_ve.displayName=F3;var vve="SwitchThumb",bve=I.forwardRef((t,e)=>{const{__scopeSwitch:r,...n}=t,i=xXe(vve,r);return a.jsx(rn.span,{"data-state":Sve(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e})});bve.displayName=vve;var _Xe="SwitchBubbleInput",wve=I.forwardRef(({__scopeSwitch:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=I.useRef(null),s=Kn(c,o),f=xC(r),p=oC(e);return I.useEffect(()=>{const y=c.current;if(!y)return;const _=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(_,"checked").set;if(f!==r&&E){const k=new Event("click",{bubbles:n});E.call(y,r),y.dispatchEvent(k)}},[f,r,n]),a.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:s,style:{...i.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});wve.displayName=_Xe;function Sve(t){return t?"checked":"unchecked"}var Tve=_ve,vXe=bve;const YS=I.forwardRef(({className:t,...e},r)=>a.jsx(Tve,{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:a.jsx(vXe,{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")})}));YS.displayName=Tve.displayName;const bXe=["Excellent","Good","Neutral","Bad","Very Bad"],wXe=[5,4,3,2,1];function SXe({questions:t,visitorId:e,onComplete:r,onSkip:n}){const i=dXe(),[o,c]=I.useState({}),s=t.filter(T=>T.question_type==="rating"),f=t.filter(T=>T.question_type!=="rating"),p=(T,E)=>{c(k=>({...k,[T]:{rating_value:E}}))},y=(T,E)=>{c(k=>({...k,[T]:{text_value:E}}))},_=async()=>{const T=Object.entries(o).filter(([,E])=>E.rating_value!=null||E.text_value&&E.text_value.trim()).map(([E,k])=>{var P;return{visitor_id:e,question_id:E,rating_value:k.rating_value??null,text_value:((P=k.text_value)==null?void 0:P.trim())||null}});if(T.length>0)try{await i.mutateAsync(T)}catch{}r()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),a.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),a.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),s.length>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("div",{className:"flex-1"}),bXe.map(T=>a.jsx("div",{className:"w-12 text-center",children:a.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:T})},T))]}),s.map(T=>a.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[a.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:T.question_text}),wXe.map(E=>{var k;return a.jsx("div",{className:"w-12 flex justify-center",children:a.jsx("button",{type:"button",onClick:()=>p(T.id,E),className:`w-6 h-6 rounded-full border-2 transition-all ${((k=o[T.id])==null?void 0:k.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 a.jsxs("div",{children:[a.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:T.question_text}),a.jsx(bd,{value:((E=o[T.id])==null?void 0:E.text_value)||"",onChange:k=>y(T.id,k.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},T.id)}),a.jsx(zt,{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?a.jsx(Ru,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function IV(t){return/iframe\.mediadelivery\.net\/embed\//.test(t)}function TXe({rooms:t}){var P;const[e,r]=I.useState(((P=t[0])==null?void 0:P.id)||""),[n,i]=I.useState(null),[o,c]=I.useState(null),s=I.useRef({}),f=t.find(R=>R.id===n)||t[0],p=o!==null?f==null?void 0:f.media[o]:null,y=(f==null?void 0:f.media.length)??0,_=()=>{c(null),i(null)},T=()=>c(R=>R===null||y===0?R:(R-1+y)%y),E=()=>c(R=>R===null||y===0?R:(R+1)%y);I.useEffect(()=>{if(o===null)return;const R=D=>{D.key==="Escape"?_():D.key==="ArrowLeft"?T():D.key==="ArrowRight"&&E()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[o,y]),I.useEffect(()=>{const R=new IntersectionObserver(D=>{const M=D.filter(B=>B.isIntersecting).sort((B,V)=>B.boundingClientRect.top-V.boundingClientRect.top);M[0]&&r(M[0].target.dataset.roomId||"")},{rootMargin:"-90px 0px -55% 0px"});return Object.values(s.current).forEach(D=>D&&R.observe(D)),()=>R.disconnect()},[t]);const k=R=>{r(R);const D=s.current[R];D&&window.scrollTo({top:D.getBoundingClientRect().top+window.scrollY-80,behavior:"smooth"})};return t.length?a.jsxs("div",{className:"hidden md:block",children:[a.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:a.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(R=>a.jsxs("button",{onClick:()=>k(R.id),className:sr("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",e===R.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[R.name,a.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:R.media.length})]},R.id))})}),t.map(R=>a.jsxs("section",{"data-room-id":R.id,ref:D=>{s.current[R.id]=D},className:"mt-10 first:mt-6",children:[a.jsx("h3",{className:"text-2xl font-bold",children:R.name}),R.description&&a.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:R.description}),R.media.length===0?a.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):a.jsx("div",{className:"mt-5 grid grid-cols-2 gap-4",children:R.media.map((D,M)=>a.jsx("button",{onClick:()=>{i(R.id),c(M)},className:sr("relative aspect-[3/2] rounded-xl overflow-hidden bg-white/5 group",M===0&&R.media.length!==2&&"col-span-2 aspect-[16/9]"),children:D.kind==="video"?a.jsxs(a.Fragment,{children:[IV(D.url)?a.jsx("div",{className:"absolute inset-0 bg-slate-900"}):a.jsx("video",{src:D.url,className:"w-full h-full object-cover"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:a.jsx("div",{className:"w-14 h-14 rounded-full bg-white/90 flex items-center justify-center",children:a.jsx(DA,{className:"h-6 w-6 text-slate-900"})})})]}):a.jsx("img",{src:D.url,alt:R.name,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-[1.03] transition-transform duration-500"})},D.id))})]},R.id)),p&&f&&a.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:_,children:[a.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:[f.name," — ",(o??0)+1," / ",y]}),a.jsx("button",{onClick:R=>{R.stopPropagation(),_()},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:"×"}),y>1&&a.jsx("button",{onClick:R=>{R.stopPropagation(),T()},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:a.jsx(xm,{className:"h-6 w-6"})}),p.kind==="video"?IV(p.url)?a.jsx("iframe",{src:`${p.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:R=>R.stopPropagation()},p.url):a.jsx("video",{src:p.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:R=>R.stopPropagation()},p.url):a.jsx("img",{src:p.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:R=>R.stopPropagation()}),y>1&&a.jsx("button",{onClick:R=>{R.stopPropagation(),E()},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:a.jsx(vd,{className:"h-6 w-6"})})]})]}):null}function EXe({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((p,y)=>{e.push({type:"media",roomId:f.id,roomName:f.name,url:p.url,kind:p.kind,index:y,total:f.media.length})})});const r=I.useRef(null),[n,i]=I.useState(0);I.useEffect(()=>{const f=r.current;if(!f)return;let p=0;const y=()=>{cancelAnimationFrame(p),p=requestAnimationFrame(()=>{const _=Math.round(f.scrollLeft/f.clientWidth);i(_)})};return f.addEventListener("scroll",y,{passive:!0}),()=>{f.removeEventListener("scroll",y),cancelAnimationFrame(p)}},[]);const o=f=>{const p=r.current;p&&p.scrollTo({left:f*p.clientWidth,behavior:"smooth"})};if(!e.length)return null;const c=(s=e[n])==null?void 0:s.roomId;return a.jsxs("div",{className:"md:hidden -mx-5",children:[a.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:a.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(f=>{const p=e.findIndex(_=>_.roomId===f.id),y=c===f.id;return a.jsx("button",{onClick:()=>o(p),className:sr("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",y?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:f.name},f.id)})})}),a.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,p)=>a.jsx("div",{className:"shrink-0 w-screen snap-center",children:a.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[f.type==="cover"?a.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:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),a.jsx("h3",{className:"text-3xl font-bold",children:f.roomName}),f.description&&a.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:f.description}),a.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[f.mediaCount," ",f.mediaCount===1?"item":"items"," — swipe to view →"]})]}):f.kind==="video"?IV(f.url)?a.jsx("iframe",{src:f.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):a.jsx("video",{src:f.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):a.jsx("img",{src:f.url,alt:f.roomName,className:"w-full h-full object-cover"}),f.type==="media"&&a.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[a.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:f.roomName}),a.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]})]})]})},p))}),a.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[a.jsxs("button",{onClick:()=>o(Math.max(0,n-1)),disabled:n===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[a.jsx(xm,{className:"h-4 w-4"})," Prev"]}),a.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",e.length]}),a.jsxs("button",{onClick:()=>o(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 ",a.jsx(vd,{className:"h-4 w-4"})]})]})]})}const Iz={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:of},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:yo},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:cm},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:jp}},AXe=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function jXe(t){return t==null||t<=0?null:`$${t.toLocaleString("en-US")}`}function kXe({openHouse:t,visitorId:e,visitorName:r,visitorEmail:n,visitorPhone:i,previewMode:o=!1}){var er;const c=t.profiles,s=((er=c==null?void 0:c.name)==null?void 0:er.split(" ").map(vt=>vt[0]).join("").slice(0,2))||"?",f=t.brand_color_override||null,[p,y]=I.useState(null),[_,T]=I.useState(""),[E,k]=I.useState(n||""),[P,R]=I.useState(i||""),[D,M]=I.useState(!1),[B,V]=I.useState(null),[G,W]=I.useState(""),[Z,Q]=I.useState(""),[re,se]=I.useState(""),[ue,_e]=I.useState([]),[we,Ce]=I.useState(""),[Me,Ae]=I.useState(""),[be,me]=I.useState(""),[Pe,Ie]=I.useState(""),Se=jXe(t.price),ve=t.tour_mode==="rooms",{data:We=[]}=pXe(ve?t.id:void 0),rt=[t.enable_question&&"question",t.enable_showing&&"showing",t.enable_disclosures&&"disclosure",t.enable_offer&&"offer"].filter(Boolean),at=vt=>{y(vt),T(""),W(""),Q(""),se(""),_e([]),Ce(""),Ae(""),me(""),Ie("")},Et=()=>{y(null)},_t=vt=>{_e(or=>or.includes(vt)?or.filter(Sr=>Sr!==vt):[...or,vt])},Vt=vt=>vt==="showing"?{preferred_date:G||null,preferred_time:Z||null,alternate_date:re||null}:vt==="disclosure"?{requested_documents:ue}:vt==="offer"?{offer_amount:we||null,financing:Me||null,timeline:be||null,pre_approved:Pe||null}:{},pt=p?p==="showing"?!!G:p==="question"?_.trim().length>0:!0:!1,Nt=async()=>{if(p){if(o){Ts({title:"Preview mode",description:"Lead not sent — this is just a preview."}),V(p),setTimeout(()=>{y(null),V(null)},1500);return}M(!0);try{const vt=Vt(p),{error:or}=await Re.from("open_house_leads").insert({open_house_id:t.id,visitor_id:e,action_type:p,payload:{message:_.trim()||null,email:E.trim()||null,phone:P.trim()||null,visitor_name:r,...vt}});if(or)throw or;Re.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:t.id,visitor_id:e,action_type:p,message:_.trim()||null,visitor_name:r,visitor_email:E.trim()||null,visitor_phone:P.trim()||null,extras:vt}}).catch(()=>{}),V(p),Ts({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Et(),V(null)},1400)}catch(vt){Ts({title:"Something went wrong",description:vt.message,variant:"destructive"})}finally{M(!1)}}};return a.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[a.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[t.hero_video_url?a.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?a.jsx("img",{src:t.photo_url,alt:t.property_address,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),a.jsxs("div",{className:"max-w-5xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[a.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[a.jsx("h1",{className:"text-2xl font-bold leading-tight",children:t.property_address}),t.city&&a.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[a.jsx(qs,{className:"h-3.5 w-3.5"}),t.city,t.state?`, ${t.state}`:""," ",t.zip]}),Se&&a.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:Se}),a.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[t.beds!=null&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(CS,{className:"h-4 w-4"}),t.beds," bd"]}),t.baths!=null&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(nv,{className:"h-4 w-4"}),t.baths," ba"]}),t.sqft!=null&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(o9,{className:"h-4 w-4"}),t.sqft.toLocaleString()," sqft"]})]}),t.property_description?a.jsx("p",{className:"text-white/80 text-sm mt-5 whitespace-pre-wrap leading-relaxed",children:t.property_description}):t.agent_greeting&&a.jsxs("p",{className:"text-white/70 text-sm mt-5 border-l-2 border-white/20 pl-3 italic",children:['"',t.agent_greeting,'"']})]}),c&&a.jsxs("div",{className:"mt-5 flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl p-4",children:[t.team_photo_url?a.jsx("img",{src:t.team_photo_url,alt:c.name||"Team",className:"h-16 w-24 shrink-0 rounded-lg object-cover ring-2 ring-white/20"}):a.jsxs(a.Fragment,{children:[a.jsxs(fd,{className:"h-12 w-12 ring-2 ring-white/20",style:f?{boxShadow:`0 0 0 2px ${f}`}:void 0,children:[a.jsx(md,{src:c.avatar_url||"",alt:c.name||""}),a.jsx(pd,{className:"bg-white/10 text-white",children:s})]}),t.co_host_name&&a.jsxs(fd,{className:"h-12 w-12 -ml-6 ring-2 ring-slate-950",children:[a.jsx(md,{src:t.co_host_photo_url||"",alt:t.co_host_name}),a.jsx(pd,{className:"bg-white/10 text-white",children:String(t.co_host_name).split(" ").map(vt=>vt[0]).join("").slice(0,2)})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"font-semibold text-white truncate",children:[c.name,t.co_host_name?` & ${t.co_host_name}`:""]}),(t.brokerage_display_name||c.title)&&a.jsx("p",{className:"text-xs text-white/60 truncate",children:[!t.co_host_name&&c.title,t.brokerage_display_name].filter(Boolean).join(" · ")})]}),(c.phone||c.email)&&a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.phone&&a.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:a.jsx(ai,{className:"h-4 w-4"})}),c.email&&a.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:a.jsx(Ti,{className:"h-4 w-4"})})]})]}),ve&&We.length>0&&a.jsxs("div",{className:"mt-8",children:[a.jsx(TXe,{rooms:We}),a.jsx(EXe,{rooms:We})]}),rt.length>0&&a.jsxs("div",{className:"mt-10 pt-6 border-t border-white/10",children:[a.jsx("p",{className:"text-xs uppercase tracking-wider text-white/40 mb-3",children:"Interested in this home?"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:rt.map(vt=>{const or=Iz[vt],Sr=or.icon;return a.jsxs("button",{onClick:()=>at(vt),className:"flex items-center gap-2 px-4 py-2.5 rounded-full border border-white/15 bg-white/5 text-white/90 hover:bg-white/10 hover:border-white/30 transition-colors text-sm",children:[a.jsx(Sr,{className:"h-4 w-4",style:f?{color:f}:void 0}),a.jsx("span",{className:"font-medium",children:or.label})]},vt)})})]}),a.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),a.jsx(Uye,{open:!!p,onOpenChange:vt=>!vt&&Et(),children:a.jsx(r7,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:p&&a.jsxs(a.Fragment,{children:[a.jsxs(qye,{className:"text-left",children:[a.jsx(Gye,{children:Iz[p].title}),a.jsxs(Hye,{children:[(c==null?void 0:c.name)||"The agent"," will be notified by email."]})]}),B===p?a.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[a.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:a.jsx(ic,{className:"h-7 w-7 text-green-600"})}),a.jsx("p",{className:"font-medium",children:"Message sent!"})]}):a.jsxs("div",{className:"space-y-4 pt-4",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Email"}),a.jsx($r,{type:"email",value:E,onChange:vt=>k(vt.target.value),placeholder:"you@example.com",className:"mt-1"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Phone"}),a.jsx($r,{type:"tel",value:P,onChange:vt=>R(vt.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),p==="showing"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Preferred date *"}),a.jsx($r,{type:"date",value:G,onChange:vt=>W(vt.target.value),className:"mt-1"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Preferred time"}),a.jsx($r,{type:"time",value:Z,onChange:vt=>Q(vt.target.value),className:"mt-1"})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Alternate date (optional)"}),a.jsx($r,{type:"date",value:re,onChange:vt=>se(vt.target.value),className:"mt-1"})]})]}),p==="disclosure"&&a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Which documents? (select all that apply)"}),a.jsx("div",{className:"mt-2 space-y-2",children:AXe.map(vt=>a.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[a.jsx(wC,{checked:ue.includes(vt),onCheckedChange:()=>_t(vt)}),a.jsx("span",{children:vt})]},vt))})]}),p==="offer"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Estimated offer"}),a.jsx($r,{value:we,onChange:vt=>Ce(vt.target.value),placeholder:"$",className:"mt-1"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Financing"}),a.jsxs(_a,{value:Me,onValueChange:Ae,children:[a.jsx(aa,{className:"mt-1",children:a.jsx(va,{placeholder:"Select..."})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"Cash",children:"Cash"}),a.jsx(fn,{value:"Conventional",children:"Conventional"}),a.jsx(fn,{value:"FHA",children:"FHA"}),a.jsx(fn,{value:"VA",children:"VA"}),a.jsx(fn,{value:"Other",children:"Other"})]})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Timeline"}),a.jsxs(_a,{value:be,onValueChange:me,children:[a.jsx(aa,{className:"mt-1",children:a.jsx(va,{placeholder:"Select..."})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"ASAP",children:"ASAP"}),a.jsx(fn,{value:"30 days",children:"30 days"}),a.jsx(fn,{value:"60 days",children:"60 days"}),a.jsx(fn,{value:"90+ days",children:"90+ days"})]})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Pre-approved?"}),a.jsxs(_a,{value:Pe,onValueChange:Ie,children:[a.jsx(aa,{className:"mt-1",children:a.jsx(va,{placeholder:"Select..."})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"Yes",children:"Yes"}),a.jsx(fn,{value:"No",children:"No"}),a.jsx(fn,{value:"In progress",children:"In progress"})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs(Mr,{className:"text-xs",children:["Message",p==="question"?" *":" (optional)"]}),a.jsx(bd,{value:_,onChange:vt=>T(vt.target.value),placeholder:Iz[p].placeholder,rows:4,className:"mt-1"})]}),a.jsx(zt,{onClick:Nt,disabled:D||!pt,className:"w-full h-12 text-white hover:opacity-90",style:f?{backgroundColor:f}:void 0,children:D?a.jsx(Ru,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const CXe=_x({first_name:Ji().trim().min(1,"First name is required").max(50),last_name:Ji().trim().max(50).optional(),email:Ji().trim().email("Please enter a valid email").max(255).optional().or(OD("")),phone:Ji().trim().max(20).optional().or(OD(""))}),IXe=[{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 Eve({slug:t}={}){var hr;const e=bm(),r=t||e.slug,[n]=px(),i=n.get("kiosk")==="1"||n.get("mode")==="kiosk",o=8,{data:c,isLoading:s,error:f}=yve(r),p=hXe(),y=fXe(),_=mXe(),T=I.useRef(!1),[E,k]=I.useState("welcome"),[P,R]=I.useState(null),[D,M]=I.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[B,V]=I.useState(""),[G,W]=I.useState(!1),[Z,Q]=I.useState(!1),[re,se]=I.useState(""),[ue,_e]=I.useState(""),[we,Ce]=I.useState(o),[Me,Ae]=I.useState(!1),[be,me]=I.useState(null),Pe=c==null?void 0:c.agent_card_slug,Ie=Pe?`https://cards.relevelup.com/${Pe}${c!=null&&c.disclosure_pdf_url?`?oh_disclosure=${encodeURIComponent(c.disclosure_pdf_url)}`:""}`:null,Se=E==="done"&&!i&&!!Ie&&!!(c!=null&&c.auto_forward_to_card);I.useEffect(()=>{if(!Se||Me){me(null);return}let Xt=c!=null&&c.disclosure_pdf_url?10:3;me(Xt);const Pr=setInterval(()=>{if(Xt-=1,Xt<=0){clearInterval(Pr),window.location.href=Ie;return}me(Xt)},1e3);return()=>clearInterval(Pr)},[Se,Me,Ie,c==null?void 0:c.disclosure_pdf_url]);const ve=I.useCallback(()=>{R(null),M({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),V(""),W(!1),Q(!1),se(""),_e(""),Ce(o),k(i?"info":"welcome")},[i]),We=I.useCallback((Xt,Pr)=>{c!=null&&c.id&&Re.functions.invoke("guestbook-lead-notify",{body:{open_house_id:c.id,visitor_id:Xt,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??Z,working_with_agent_name:Pr.working_with_agent_name??re,visitor_address:Pr.visitor_address??D.visitor_address}}).catch(Rn=>console.error("Guest book lead notify failed:",Rn))},[c==null?void 0:c.id,D,B,G,Z,re]);I.useEffect(()=>{if(!i||E!=="done")return;Ce(o);const Xt=setInterval(()=>{Ce(Pr=>Pr<=1?(clearInterval(Xt),ve(),0):Pr-1)},1e3);return()=>clearInterval(Xt)},[i,E,ve]),I.useEffect(()=>{if(!i)return;k(Pr=>Pr==="welcome"?"info":Pr);let Xt=null;return(async()=>{var Pr,Rn;try{Xt=await((Rn=(Pr=navigator.wakeLock)==null?void 0:Pr.request)==null?void 0:Rn.call(Pr,"screen"))}catch{}})(),()=>{var Pr;try{(Pr=Xt==null?void 0:Xt.release)==null||Pr.call(Xt)}catch{}}},[i]);const rt=I.useCallback(()=>{var Pr;const Xt=document.documentElement;document.fullscreenElement||(Pr=Xt.requestFullscreen||Xt.webkitRequestFullscreen)==null||Pr.call(Xt).catch(()=>{})},[]),{data:at,isLoading:Et}=uXe(c==null?void 0:c.id),_t=!!(c!=null&&c.enable_survey),Vt=(c==null?void 0:c.ask_visitor_intent)!==!1,pt=(c==null?void 0:c.ask_visitor_address)===!0;I.useEffect(()=>{if(!r||!(c!=null&&c.id)||T.current)return;const Xt=`oh_scan_${c.id}`;if(sessionStorage.getItem(Xt)){T.current=!0;return}T.current=!0,sessionStorage.setItem(Xt,"1"),_.mutate(r)},[r,c==null?void 0:c.id]),I.useEffect(()=>{E==="pending_survey"&&(Et||k(_t&&((at==null?void 0:at.length)??0)>0?"survey":"done"))},[E,Et,_t,at]);const Nt=Xt=>{if(!Xt)return"";const[Pr,Rn]=Xt.split(":"),ci=parseInt(Pr),ti=ci>=12?"PM":"AM";return`${ci>12?ci-12:ci||12}:${Rn} ${ti}`},er=async()=>{_e("");const Xt=CXe.safeParse(D);if(!Xt.success){_e(Xt.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 Rn=null;if(!P&&(c!=null&&c.id))try{const ci=await p.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:pt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&re.trim()?re.trim():void 0,partial_signin:Pr?!1:Vt});Rn=ci.id,R(ci.id)}catch{if(Pr){_e("We could not start the virtual tour. Please try again.");return}}if(Pr){Vt?k("intent"):(Rn&&We(Rn,{}),k("done"));return}if(!Vt){Rn&&We(Rn,{}),_t?!Et&&at&&at.length>0?k("survey"):k("pending_survey"):k("done");return}k("intent")},vt=async Xt=>{V(Xt);try{let Pr=P;if(Pr?await y.mutateAsync({visitor_id:Pr,visitor_intent:Xt,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&re.trim()?re.trim():null,partial_signin:!1}):(Pr=(await p.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:pt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,visitor_intent:Xt,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&re.trim()?re.trim():void 0,partial_signin:!1})).id,R(Pr)),Pr&&We(Pr,{visitor_intent:Xt,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&re.trim()?re.trim():null}),(c==null?void 0:c.kind)==="virtual"){k("done");return}_t?!Et&&at&&at.length>0?k("survey"):k("pending_survey"):k("done")}catch{_e("Something went wrong. Please try again.")}};if(s)return a.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:a.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(f||!c)return a.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:a.jsxs("div",{className:"text-center text-white",children:[a.jsx(La,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),a.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(Xt=>Xt[0]).join("").slice(0,2))||"?",nn=c.event_type==="community",cr=c.kind==="virtual",xr=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(cr&&(xr||E==="done"))return!xr&&!P?a.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:a.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):a.jsxs(a.Fragment,{children:[a.jsxs(Wo,{children:[a.jsxs("title",{children:["Virtual Tour | ",c.property_address]}),a.jsx("meta",{name:"description",content:`Take a virtual tour of ${c.property_address}`}),a.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),xr&&a.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"}),a.jsx(kXe,{openHouse:c,visitorId:xr?"preview":P,visitorName:xr?"Preview Visitor":`${D.first_name} ${D.last_name}`.trim(),visitorEmail:xr?"":D.email,visitorPhone:xr?"":D.phone,previewMode:xr})]});const _n=`${cr?"Virtual Open House":nn?"Community Event":"Open House"} — ${c.property_address}`,At=[[c.city,c.state].filter(Boolean).join(", "),c.event_date?Ni(new Date(c.event_date+"T00:00:00"),"EEE, MMM d"):null,or!=null&&or.name?`Hosted by ${or.name}`:null].filter(Boolean).join(" · "),Mt=c.photo_url||"",dr=Mt&&Mt.includes("/storage/v1/object/public/")?Mt.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Mt||"https://dashboard.relevelup.com/og-image.png",ur=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return a.jsxs(a.Fragment,{children:[a.jsxs(Wo,{children:[a.jsx("title",{children:_n}),a.jsx("meta",{name:"description",content:At||`Sign in to ${c.property_address}`}),a.jsx("meta",{property:"og:type",content:"website"}),a.jsx("meta",{property:"og:title",content:_n}),a.jsx("meta",{property:"og:description",content:At||`Sign in to ${c.property_address}`}),a.jsx("meta",{property:"og:image",content:dr}),a.jsx("meta",{property:"og:image:width",content:"1200"}),a.jsx("meta",{property:"og:image:height",content:"630"}),a.jsx("meta",{property:"og:url",content:ur}),a.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),a.jsx("meta",{name:"twitter:title",content:_n}),a.jsx("meta",{name:"twitter:description",content:At||`Sign in to ${c.property_address}`}),a.jsx("meta",{name:"twitter:image",content:dr}),a.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),a.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:a.jsxs("div",{className:"w-full max-w-md",children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsxs(fd,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[a.jsx(md,{src:(or==null?void 0:or.avatar_url)||"",alt:(or==null?void 0:or.name)||""}),a.jsx(pd,{className:"bg-white/10 text-white text-lg",children:Sr})]}),a.jsx("p",{className:"text-white/60 text-sm",children:or==null?void 0:or.name}),(or==null?void 0:or.title)&&a.jsx("p",{className:"text-white/40 text-xs",children:or.title})]}),a.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[c.photo_url&&a.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[a.jsx("img",{src:c.photo_url,alt:c.property_address,className:"w-full h-full object-cover"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),a.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[a.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:c.property_address}),a.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[c.city&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(qs,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!cr&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(yo,{className:"h-3 w-3"}),Ni(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Rl,{className:"h-3 w-3"}),Nt(c.start_time),c.end_time?` – ${Nt(c.end_time)}`:""]})]})]})]})]}),!c.photo_url&&a.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:nn?a.jsx(go,{className:"h-5 w-5 text-white"}):a.jsx(La,{className:"h-5 w-5 text-white"})}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:c.property_address}),a.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[c.city&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(qs,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!cr&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(yo,{className:"h-3 w-3"}),Ni(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Rl,{className:"h-3 w-3"}),Nt(c.start_time),c.end_time?` – ${Nt(c.end_time)}`:""]})]})]})]})]})}),a.jsxs("div",{className:"p-6",children:[E==="welcome"&&a.jsxs("div",{className:"text-center space-y-6",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),a.jsx("p",{className:"text-slate-500 text-sm",children:c.agent_greeting||"Please sign in below."})]}),a.jsxs(zt,{onClick:()=>k("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",a.jsx(ra,{className:"h-5 w-5 ml-2"})]}),a.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),E==="info"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("button",{onClick:()=>k("welcome"),className:"text-slate-400 hover:text-slate-600",children:a.jsx(Yy,{className:"h-4 w-4"})}),a.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-slate-600 text-xs",children:"First Name *"}),a.jsx($r,{value:D.first_name,onChange:Xt=>M(Pr=>({...Pr,first_name:Xt.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-slate-600 text-xs",children:"Last Name"}),a.jsx($r,{value:D.last_name,onChange:Xt=>M(Pr=>({...Pr,last_name:Xt.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-slate-600 text-xs",children:"Email"}),a.jsx($r,{type:"email",value:D.email,onChange:Xt=>M(Pr=>({...Pr,email:Xt.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-slate-600 text-xs",children:"Phone"}),a.jsx($r,{type:"tel",value:D.phone,onChange:Xt=>M(Pr=>({...Pr,phone:Xt.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),pt&&a.jsxs("div",{children:[a.jsx(Mr,{className:"text-slate-600 text-xs",children:"Your Home Address"}),a.jsx($r,{value:D.visitor_address,onChange:Xt=>M(Pr=>({...Pr,visitor_address:Xt.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[a.jsx("input",{type:"checkbox",checked:G,onChange:Xt=>W(Xt.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),a.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),a.jsxs("div",{className:"space-y-2 pt-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs font-medium text-slate-400",children:Z?"Yes":"No"}),a.jsx(YS,{checked:Z,onCheckedChange:Q})]})]}),Z&&a.jsx($r,{value:re,onChange:Xt=>se(Xt.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),ue&&a.jsx("p",{className:"text-destructive text-sm",children:ue}),a.jsxs(zt,{onClick:er,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",a.jsx(ra,{className:"h-5 w-5 ml-2"})]})]}),E==="intent"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("button",{onClick:()=>k("info"),className:"text-slate-400 hover:text-slate-600",children:a.jsx(Yy,{className:"h-4 w-4"})}),a.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),a.jsx("div",{className:"grid grid-cols-2 gap-3",children:IXe.map(Xt=>a.jsxs("button",{onClick:()=>vt(Xt.value),disabled:p.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:[a.jsx("span",{className:"text-2xl",children:Xt.emoji}),a.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Xt.label})]},Xt.value))}),ue&&a.jsx("p",{className:"text-destructive text-sm text-center",children:ue})]}),E==="pending_survey"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),a.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),E==="survey"&&P&&at&&a.jsx(SXe,{questions:at,visitorId:P,onComplete:()=>k("done"),onSkip:()=>k("done")}),E==="done"&&a.jsxs("div",{className:"text-center space-y-4 py-4",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:a.jsx(ic,{className:"h-8 w-8 text-green-600"})}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),a.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!"]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[(c==null?void 0:c.disclosure_pdf_url)&&a.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:[a.jsx(cm,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),Ie&&a.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:[a.jsx(ra,{className:"h-4 w-4"}),"View ",or!=null&&or.name?`${or.name.split(" ")[0]}'s`:"My"," Business Card"]})]}),Ie&&be!==null&&!Me&&a.jsxs("p",{className:"text-xs text-slate-400",children:["Opening the business card in ",be,"s…"," ",a.jsx("button",{type:"button",className:"underline",onClick:()=>Ae(!0),children:"Stay here"})]}),(or==null?void 0:or.name)&&a.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",a.jsx("strong",{className:"text-slate-600",children:or.name})]}),i&&a.jsxs("div",{className:"pt-4 space-y-3",children:[a.jsx(zt,{onClick:ve,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),a.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",we,"s…"]})]})]})]})]}),a.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),i&&a.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[a.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:[a.jsx(ADe,{className:"h-3 w-3"})," Tablet Mode"]}),a.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:a.jsx(oDe,{className:"h-3 w-3"})})]})]})})]})}const NXe=Object.freeze(Object.defineProperty({__proto__:null,default:Eve},Symbol.toStringTag,{value:"Module"}));function Nqt(t){return gr({queryKey:["open-house-rsvps",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("open_house_rsvps").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(r)throw r;return e||[]},enabled:!!t})}function PXe(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.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 Pqt(t){const e=Nr();return kr({mutationFn:async r=>{const{error:n}=await Re.from("open_house_rsvps").delete().eq("id",r);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}function Rqt(t){const e=Nr();return kr({mutationFn:async({id:r,checkedIn:n})=>{const{error:i}=await Re.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 RXe=_x({first_name:Ji().trim().min(1,"First name is required").max(50),last_name:Ji().trim().max(50).optional(),email:Ji().trim().email("Please enter a valid email").max(255),phone:Ji().trim().max(20).optional().or(OD("")),message:Ji().trim().max(500).optional().or(OD(""))}),Nz=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}`},LXe=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 Ave({slug:t}={}){const e=bm(),r=t||e.slug,{data:n,isLoading:i,error:o}=yve(r),c=PXe(),[s,f]=I.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[p,y]=I.useState(!1),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(!1),D=I.useMemo(()=>LXe(n==null?void 0:n.event_date),[n==null?void 0:n.event_date]),M=I.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()=>{k("");const Q=RXe.safeParse(s);if(!Q.success){k(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:p,working_with_agent_name:p&&_.trim()?_.trim():void 0,message:s.message.trim()||void 0}),R(!0)}catch(re){k((re==null?void 0:re.message)||"Something went wrong. Please try again.")}},W=I.useMemo(()=>{if(!n||!D)return"";const Q=Ce=>String(Ce).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}`),we=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=${we}`},[n,D,V]);if(i)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:a.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(o||!n)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:a.jsxs("div",{className:"text-white/80",children:[a.jsx(La,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),a.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),a.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const Z=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([n.property_address,V,n.zip].filter(Boolean).join(", "))}`;return a.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[a.jsxs(Wo,{children:[a.jsx("title",{children:`RSVP — Open House at ${n.property_address}`}),a.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${n.property_address}${D?` on ${Ni(D,"EEEE, MMMM d")}`:""}.`})]}),a.jsxs("header",{className:"relative",children:[a.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[M&&a.jsx("img",{src:M,alt:n.property_address,className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:a.jsxs("div",{className:"mx-auto max-w-3xl",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),a.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:n.property_address}),V&&a.jsxs("p",{className:"mt-1 text-white/70",children:[V," ",n.zip||""]}),a.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[D&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(yo,{className:"h-4 w-4 text-[#d4b978]"}),Ni(D,"EEEE, MMMM d, yyyy")]}),n.start_time&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Rl,{className:"h-4 w-4 text-[#d4b978]"}),Nz(n.start_time),n.end_time?` – ${Nz(n.end_time)}`:""]})]})]})})]}),a.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),a.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)&&a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[n.price?a.jsx(KP,{icon:a.jsx(La,{className:"h-4 w-4"}),label:"Price",value:`$${Number(n.price).toLocaleString()}`}):null,n.beds?a.jsx(KP,{icon:a.jsx(VLe,{className:"h-4 w-4"}),label:"Beds",value:String(n.beds)}):null,n.baths?a.jsx(KP,{icon:a.jsx(nv,{className:"h-4 w-4"}),label:"Baths",value:String(n.baths)}):null,n.sqft?a.jsx(KP,{icon:a.jsx(RO,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(n.sqft).toLocaleString()}):null]}),n.property_description&&a.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:n.property_description}),a.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:P?a.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[a.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:a.jsx(ic,{className:"h-7 w-7 text-emerald-600"})}),a.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),a.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",D?Ni(D,"EEEE, MMMM d"):"soon",n.start_time?` at ${Nz(n.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),a.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[W&&a.jsx(zt,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:a.jsxs("a",{href:W,target:"_blank",rel:"noreferrer",children:[a.jsx(Nfe,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),a.jsx(zt,{asChild:!0,variant:"outline",children:a.jsxs("a",{href:Z,target:"_blank",rel:"noreferrer",children:[a.jsx(qs,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):a.jsxs("div",{className:"p-6 sm:p-8",children:[a.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),a.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."}),a.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"rsvp-first",children:"First name *"}),a.jsx($r,{id:"rsvp-first",value:s.first_name,onChange:Q=>f(re=>({...re,first_name:Q.target.value})),className:"h-11"})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"rsvp-last",children:"Last name"}),a.jsx($r,{id:"rsvp-last",value:s.last_name,onChange:Q=>f(re=>({...re,last_name:Q.target.value})),className:"h-11"})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"rsvp-email",children:"Email *"}),a.jsx($r,{id:"rsvp-email",type:"email",value:s.email,onChange:Q=>f(re=>({...re,email:Q.target.value})),className:"h-11"})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{htmlFor:"rsvp-phone",children:"Phone"}),a.jsx($r,{id:"rsvp-phone",type:"tel",value:s.phone,onChange:Q=>f(re=>({...re,phone:Q.target.value})),className:"h-11"})]})]}),a.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),a.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),a.jsx(YS,{checked:p,onCheckedChange:y})]}),p&&a.jsx($r,{value:_,onChange:Q=>T(Q.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),a.jsxs("div",{className:"mt-4 space-y-1.5",children:[a.jsx(Mr,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),a.jsx(bd,{id:"rsvp-msg",rows:3,value:s.message,onChange:Q=>f(re=>({...re,message:Q.target.value})),className:"resize-y"})]}),E&&a.jsx("p",{className:"mt-3 text-sm text-destructive",children:E}),a.jsx(zt,{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…":a.jsxs(a.Fragment,{children:["RSVP for this open house",a.jsx(ra,{className:"ml-2 h-4 w-4"})]})}),a.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)&&a.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[a.jsxs(fd,{className:"h-14 w-14",children:[a.jsx(md,{src:B.avatar_url||void 0,alt:B.name}),a.jsx(pd,{children:B.name.slice(0,1)})]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),a.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:B.name}),B.title&&a.jsx("p",{className:"text-sm text-[#5b6b72]",children:B.title}),a.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[B.phone&&a.jsx("a",{href:`tel:${B.phone}`,children:B.phone}),B.email&&a.jsx("a",{href:`mailto:${B.email}`,className:"truncate",children:B.email})]})]})]}),a.jsx("div",{className:"text-center",children:a.jsxs("a",{href:Z,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[a.jsx(qs,{className:"h-4 w-4"}),"Get directions to ",n.property_address]})})]})]})}function KP({icon:t,label:e,value:r}){return a.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[t,e]}),a.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:r})]})}const DXe=Object.freeze(Object.defineProperty({__proto__:null,default:Ave},Symbol.toStringTag,{value:"Module"}));function Lqt(t){const{user:e}=Gn();return gr({queryKey:["cohost-tokens",t],queryFn:async()=>{const{data:r,error:n}=await Re.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 Dqt(){const t=Nr(),{user:e}=Gn();return kr({mutationFn:async({openHouseId:r,label:n})=>{const{data:i,error:o}=await Re.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(o)throw o;return i},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function Mqt(){const t=Nr();return kr({mutationFn:async({id:e,openHouseId:r})=>{const{error:n}=await Re.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 MXe(t){return gr({queryKey:["cohost-validate",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 mm=(t,e,r)=>r>e?e:r{},H1=()=>{};const ix={},kve=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Cve(t){return typeof t=="object"&&t!==null}const Ive=t=>/^0[^.\s]+$/u.test(t);function Nve(t){let e;return()=>(e===void 0&&(e=t()),e)}const rh=t=>t,FXe=(t,e)=>r=>e(t(r)),TC=(...t)=>t.reduce(FXe),Gj=(t,e,r)=>{const n=e-t;return n===0?1:(r-t)/n};class eH{constructor(){this.subscriptions=[]}add(e){return J7(this.subscriptions,e),()=>$D(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 o=0;ot*1e3,Xd=t=>t/1e3;function Pve(t,e){return e?t*(1e3/e):0}const Rve=(t,e,r)=>(((1-3*r+3*e)*t+(3*r-6*e))*t+3*e)*t,BXe=1e-7,zXe=12;function $Xe(t,e,r,n,i){let o,c,s=0;do c=e+(r-e)/2,o=Rve(c,n,i)-t,o>0?r=c:e=c;while(Math.abs(o)>BXe&&++s$Xe(o,0,1,t,r);return o=>o===0||o===1?o:Rve(i(o),e,n)}const Lve=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Dve=t=>e=>1-t(1-e),Mve=EC(.33,1.53,.69,.99),tH=Dve(Mve),Ove=Lve(tH),Fve=t=>t>=1?1:(t*=2)<1?.5*tH(t):.5*(2-Math.pow(2,-10*(t-1))),rH=t=>1-Math.sin(Math.acos(t)),Bve=Dve(rH),zve=Lve(rH),UXe=EC(.42,0,1,1),VXe=EC(0,0,.58,1),$ve=EC(.42,0,.58,1),qXe=t=>Array.isArray(t)&&typeof t[0]!="number",Uve=t=>Array.isArray(t)&&typeof t[0]=="number",$re={linear:rh,easeIn:UXe,easeInOut:$ve,easeOut:VXe,circIn:rH,circInOut:zve,circOut:Bve,backIn:tH,backInOut:Ove,backOut:Mve,anticipate:Fve},GXe=t=>typeof t=="string",Ure=t=>{if(Uve(t)){H1(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,r,n,i]=t;return EC(e,r,n,i)}else if(GXe(t))return H1($re[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),$re[t];return t},YP=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Vre={value:null,addProjectionMetrics:null};function HXe(t,e){let r=new Set,n=new Set,i=!1,o=!1;const c=new WeakSet;let s={delta:0,timestamp:0,isProcessing:!1},f=0;function p(_){c.has(_)&&(y.schedule(_),t()),f++,_(s)}const y={schedule:(_,T=!1,E=!1)=>{const P=E&&i?r:n;return T&&c.add(_),P.add(_),_},cancel:_=>{n.delete(_),c.delete(_)},process:_=>{if(s=_,i){o=!0;return}i=!0;const T=r;r=n,n=T,r.forEach(p),e&&Vre.value&&Vre.value.frameloop[e].push(f),f=0,r.clear(),i=!1,o&&(o=!1,y.process(_))}};return y}const WXe=40;function Vve(t,e){let r=!1,n=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>r=!0,c=YP.reduce((B,V)=>(B[V]=HXe(o,e?V:void 0),B),{}),{setup:s,read:f,resolveKeyframes:p,preUpdate:y,update:_,preRender:T,render:E,postRender:k}=c,P=()=>{const B=ix.useManualTiming,V=B?i.timestamp:performance.now();r=!1,B||(i.delta=n?1e3/60:Math.max(Math.min(V-i.timestamp,WXe),1)),i.timestamp=V,i.isProcessing=!0,s.process(i),f.process(i),p.process(i),y.process(i),_.process(i),T.process(i),E.process(i),k.process(i),i.isProcessing=!1,r&&e&&(n=!1,t(P))},R=()=>{r=!0,n=!0,i.isProcessing||t(P)};return{schedule:YP.reduce((B,V)=>{const G=c[V];return B[V]=(W,Z=!1,Q=!1)=>(r||R(),G.schedule(W,Z,Q)),B},{}),cancel:B=>{for(let V=0;V(hL===void 0&&Kc.set(ql.isProcessing||ix.useManualTiming?ql.timestamp:performance.now()),hL),set:t=>{hL=t,queueMicrotask(KXe)}},qve=t=>e=>typeof e=="string"&&e.startsWith(t),Gve=qve("--"),YXe=qve("var(--"),nH=t=>YXe(t)?ZXe.test(t.split("/*")[0].trim()):!1,ZXe=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function qre(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const ZS={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Hj={...ZS,transform:t=>mm(0,1,t)},ZP={...ZS,default:1},VA=t=>Math.round(t*1e5)/1e5,iH=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function XXe(t){return t==null}const QXe=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,sH=(t,e)=>r=>!!(typeof r=="string"&&QXe.test(r)&&r.startsWith(t)||e&&!XXe(r)&&Object.prototype.hasOwnProperty.call(r,e)),Hve=(t,e,r)=>n=>{if(typeof n!="string")return n;const[i,o,c,s]=n.match(iH);return{[t]:parseFloat(i),[e]:parseFloat(o),[r]:parseFloat(c),alpha:s!==void 0?parseFloat(s):1}},JXe=t=>mm(0,255,t),Rz={...ZS,transform:t=>Math.round(JXe(t))},u_={test:sH("rgb","red"),parse:Hve("red","green","blue"),transform:({red:t,green:e,blue:r,alpha:n=1})=>"rgba("+Rz.transform(t)+", "+Rz.transform(e)+", "+Rz.transform(r)+", "+VA(Hj.transform(n))+")"};function eQe(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 NV={test:sH("#"),parse:eQe,transform:u_.transform},AC=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),ry=AC("deg"),am=AC("%"),Nn=AC("px"),tQe=AC("vh"),rQe=AC("vw"),Gre={...am,parse:t=>am.parse(t)/100,transform:t=>am.transform(t*100)},Pw={test:sH("hsl","hue"),parse:Hve("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:r,alpha:n=1})=>"hsla("+Math.round(t)+", "+am.transform(VA(e))+", "+am.transform(VA(r))+", "+VA(Hj.transform(n))+")"},Vo={test:t=>u_.test(t)||NV.test(t)||Pw.test(t),parse:t=>u_.test(t)?u_.parse(t):Pw.test(t)?Pw.parse(t):NV.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?u_.transform(t):Pw.transform(t),getAnimatableNone:t=>{const e=Vo.parse(t);return e.alpha=0,Vo.transform(e)}},nQe=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function iQe(t){var e,r;return isNaN(t)&&typeof t=="string"&&(((e=t.match(iH))==null?void 0:e.length)||0)+(((r=t.match(nQe))==null?void 0:r.length)||0)>0}const Wve="number",Kve="color",sQe="var",aQe="var(",Hre="${}",oQe=/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 W1(t){const e=t.toString(),r=[],n={color:[],number:[],var:[]},i=[];let o=0;const s=e.replace(oQe,f=>(Vo.test(f)?(n.color.push(o),i.push(Kve),r.push(Vo.parse(f))):f.startsWith(aQe)?(n.var.push(o),i.push(sQe),r.push(f)):(n.number.push(o),i.push(Wve),r.push(parseFloat(f))),++o,Hre)).split(Hre);return{values:r,split:s,indexes:n,types:i}}function lQe(t){return W1(t).values}function Yve({split:t,types:e}){const r=t.length;return n=>{let i="";for(let o=0;otypeof t=="number"?0:Vo.test(t)?Vo.getAnimatableNone(t):t,dQe=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:uQe(t);function hQe(t){const e=W1(t);return Yve(e)(e.values.map((n,i)=>dQe(n,e.split[i])))}const nf={test:iQe,parse:lQe,createTransformer:cQe,getAnimatableNone:hQe};function Lz(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 fQe({hue:t,saturation:e,lightness:r,alpha:n}){t/=360,e/=100,r/=100;let i=0,o=0,c=0;if(!e)i=o=c=r;else{const s=r<.5?r*(1+e):r+e-r*e,f=2*r-s;i=Lz(f,s,t+1/3),o=Lz(f,s,t),c=Lz(f,s,t-1/3)}return{red:Math.round(i*255),green:Math.round(o*255),blue:Math.round(c*255),alpha:n}}function UD(t,e){return r=>r>0?e:t}const Pa=(t,e,r)=>t+(e-t)*r,Dz=(t,e,r)=>{const n=t*t,i=r*(e*e-n)+n;return i<0?0:Math.sqrt(i)},mQe=[NV,u_,Pw],pQe=t=>mQe.find(e=>e.test(t));function Wre(t){const e=pQe(t);if(z3(!!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=fQe(r)),r}const Kre=(t,e)=>{const r=Wre(t),n=Wre(e);if(!r||!n)return UD(t,e);const i={...r};return o=>(i.red=Dz(r.red,n.red,o),i.green=Dz(r.green,n.green,o),i.blue=Dz(r.blue,n.blue,o),i.alpha=Pa(r.alpha,n.alpha,o),u_.transform(i))},PV=new Set(["none","hidden"]);function gQe(t,e){return PV.has(t)?r=>r<=0?t:e:r=>r>=1?e:t}function yQe(t,e){return r=>Pa(t,e,r)}function aH(t){return typeof t=="number"?yQe:typeof t=="string"?nH(t)?UD:Vo.test(t)?Kre:vQe:Array.isArray(t)?Zve:typeof t=="object"?Vo.test(t)?Kre:xQe:UD}function Zve(t,e){const r=[...t],n=r.length,i=t.map((o,c)=>aH(o)(o,e[c]));return o=>{for(let c=0;c{for(const o in n)r[o]=n[o](i);return r}}function _Qe(t,e){const r=[],n={color:0,var:0,number:0};for(let i=0;i{const r=nf.createTransformer(e),n=W1(t),i=W1(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?PV.has(t)&&!i.values.length||PV.has(e)&&!n.values.length?gQe(t,e):TC(Zve(_Qe(n,i),i.values),r):(z3(!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"),UD(t,e))};function Xve(t,e,r){return typeof t=="number"&&typeof e=="number"&&typeof r=="number"?Pa(t,e,r):aH(t)(t,e)}const bQe=t=>{const e=({timestamp:r})=>t(r);return{start:(r=!0)=>na.update(e,r),stop:()=>sx(e),now:()=>ql.isProcessing?ql.timestamp:Kc.now()}},Qve=(t,e,r=10)=>{let n="";const i=Math.max(Math.round(e/r),2);for(let o=0;o=VD?1/0:e}function wQe(t,e=100,r){const n=r({...t,keyframes:[0,e]}),i=Math.min(oH(n),VD);return{type:"keyframes",ease:o=>n.next(i*o).value/e,duration:Xd(i)}}const Xa={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 RV(t,e){return t*Math.sqrt(1-e*e)}const SQe=12;function TQe(t,e,r){let n=r;for(let i=1;i{const y=p*c,_=y*t,T=y-r,E=RV(p,c),k=Math.exp(-_);return Mz-T/E*k},o=p=>{const _=p*c*t,T=_*r+r,E=Math.pow(c,2)*Math.pow(p,2)*t,k=Math.exp(-_),P=RV(Math.pow(p,2),c);return(-i(p)+Mz>0?-1:1)*((T-E)*k)/P}):(i=p=>{const y=Math.exp(-p*t),_=(p-r)*t+1;return-Mz+y*_},o=p=>{const y=Math.exp(-p*t),_=(r-p)*(t*t);return y*_});const s=5/t,f=TQe(i,o,s);if(t=Pu(t),isNaN(f))return{stiffness:Xa.stiffness,damping:Xa.damping,duration:t};{const p=Math.pow(f,2)*n;return{stiffness:p,damping:c*2*Math.sqrt(n*p),duration:t}}}const AQe=["duration","bounce"],jQe=["stiffness","damping","mass"];function Yre(t,e){return e.some(r=>t[r]!==void 0)}function kQe(t){let e={velocity:Xa.velocity,stiffness:Xa.stiffness,damping:Xa.damping,mass:Xa.mass,isResolvedFromDuration:!1,...t};if(!Yre(t,jQe)&&Yre(t,AQe))if(e.velocity=0,t.visualDuration){const r=t.visualDuration,n=2*Math.PI/(r*1.2),i=n*n,o=2*mm(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:Xa.mass,stiffness:i,damping:o}}else{const r=EQe({...t,velocity:0});e={...e,...r,mass:Xa.mass},e.isResolvedFromDuration=!0}return e}function qD(t=Xa.visualDuration,e=Xa.bounce){const r=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:i}=r;const o=r.keyframes[0],c=r.keyframes[r.keyframes.length-1],s={done:!1,value:o},{stiffness:f,damping:p,mass:y,duration:_,velocity:T,isResolvedFromDuration:E}=kQe({...r,velocity:-Xd(r.velocity||0)}),k=T||0,P=p/(2*Math.sqrt(f*y)),R=c-o,D=Xd(Math.sqrt(f/y)),M=Math.abs(R)<5;n||(n=M?Xa.restSpeed.granular:Xa.restSpeed.default),i||(i=M?Xa.restDelta.granular:Xa.restDelta.default);let B,V,G,W,Z,Q;if(P<1)G=RV(D,P),W=(k+P*D*R)/G,B=se=>{const ue=Math.exp(-P*D*se);return c-ue*(W*Math.sin(G*se)+R*Math.cos(G*se))},Z=P*D*W+R*G,Q=P*D*R-W*G,V=se=>Math.exp(-P*D*se)*(Z*Math.sin(G*se)+Q*Math.cos(G*se));else if(P===1){B=ue=>c-Math.exp(-D*ue)*(R+(k+D*R)*ue);const se=k+D*R;V=ue=>Math.exp(-D*ue)*(D*se*ue-k)}else{const se=D*Math.sqrt(P*P-1);B=Ce=>{const Me=Math.exp(-P*D*Ce),Ae=Math.min(se*Ce,300);return c-Me*((k+P*D*R)*Math.sinh(Ae)+se*R*Math.cosh(Ae))/se};const ue=(k+P*D*R)/se,_e=P*D*ue-R*se,we=P*D*R-ue*se;V=Ce=>{const Me=Math.exp(-P*D*Ce),Ae=Math.min(se*Ce,300);return Me*(_e*Math.sinh(Ae)+we*Math.cosh(Ae))}}const re={calculatedDuration:E&&_||null,velocity:se=>Pu(V(se)),next:se=>{if(!E&&P<1){const _e=Math.exp(-P*D*se),we=Math.sin(G*se),Ce=Math.cos(G*se),Me=c-_e*(W*we+R*Ce),Ae=Pu(_e*(Z*we+Q*Ce));return s.done=Math.abs(Ae)<=n&&Math.abs(c-Me)<=i,s.value=s.done?c:Me,s}const ue=B(se);if(E)s.done=se>=_;else{const _e=Pu(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(oH(re),VD),ue=Qve(_e=>re.next(se*_e).value,se,30);return se+"ms "+ue},toTransition:()=>{}};return re}qD.applyToOptions=t=>{const e=wQe(t,100,qD);return t.ease=e.ease,t.duration=Pu(e.duration),t.type="keyframes",t};const CQe=5;function Jve(t,e,r){const n=Math.max(e-CQe,0);return Pve(r-t(n),e-n)}function LV({keyframes:t,velocity:e=0,power:r=.8,timeConstant:n=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:c,min:s,max:f,restDelta:p=.5,restSpeed:y}){const _=t[0],T={done:!1,value:_},E=Q=>s!==void 0&&Qf,k=Q=>s===void 0?f:f===void 0||Math.abs(s-Q)-P*Math.exp(-Q/n),B=Q=>D+M(Q),V=Q=>{const re=M(Q),se=B(Q);T.done=Math.abs(re)<=p,T.value=T.done?D:se};let G,W;const Z=Q=>{E(T.value)&&(G=Q,W=qD({keyframes:[T.value,k(T.value)],velocity:Jve(B,Q,T.value),damping:i,stiffness:o,restDelta:p,restSpeed:y}))};return Z(0),{calculatedDuration:null,next:Q=>{let re=!1;return!W&&G===void 0&&(re=!0,V(Q),Z(Q)),G!==void 0&&Q>=G?W.next(Q-G):(!re&&V(Q),T)}}}function IQe(t,e,r){const n=[],i=r||ix.mix||Xve,o=t.length-1;for(let c=0;ce[0];if(o===2&&e[0]===e[1])return()=>e[1];const c=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const s=IQe(e,n,i),f=s.length,p=y=>{if(c&&y1)for(;_p(mm(t[0],t[o-1],y)):p}function PQe(t,e){const r=t[t.length-1];for(let n=1;n<=e;n++){const i=Gj(0,e,n);t.push(Pa(r,1,i))}}function RQe(t){const e=[0];return PQe(e,t.length-1),e}function LQe(t,e){return t.map(r=>r*e)}function DQe(t,e){return t.map(()=>e||$ve).splice(0,t.length-1)}function qA({duration:t=300,keyframes:e,times:r,ease:n="easeInOut"}){const i=qXe(n)?n.map(Ure):Ure(n),o={done:!1,value:e[0]},c=LQe(r&&r.length===e.length?r:RQe(e),t),s=NQe(c,e,{ease:Array.isArray(i)?i:DQe(e,i)});return{calculatedDuration:t,next:f=>(o.value=s(f),o.done=f>=t,o)}}const MQe=t=>t!==null;function $3(t,{repeat:e,repeatType:r="loop"},n,i=1){const o=t.filter(MQe),s=i<0||e&&r!=="loop"&&e%2===1?0:o.length-1;return!s||n===void 0?o[s]:n}const OQe={decay:LV,inertia:LV,tween:qA,keyframes:qA,spring:qD};function ebe(t){typeof t.type=="string"&&(t.type=OQe[t.type])}class lH{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 FQe=t=>t/100;class GD extends lH{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!==Kc.now()&&this.tick(Kc.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;ebe(e);const{type:r=qA,repeat:n=0,repeatDelay:i=0,repeatType:o,velocity:c=0}=e;let{keyframes:s}=e;const f=r||qA;f!==qA&&typeof s[0]!="number"&&(this.mixKeyframes=TC(FQe,Xve(s[0],s[1])),s=[0,100]);const p=f({...e,keyframes:s});o==="mirror"&&(this.mirroredGenerator=f({...e,keyframes:[...s].reverse(),velocity:-c})),p.calculatedDuration===null&&(p.calculatedDuration=oH(p));const{calculatedDuration:y}=p;this.calculatedDuration=y,this.resolvedDuration=y+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=p}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:o,mirroredGenerator:c,resolvedDuration:s,calculatedDuration:f}=this;if(this.startTime===null)return n.next(0);const{delay:p=0,keyframes:y,repeat:_,repeatType:T,repeatDelay:E,type:k,onUpdate:P,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-p*(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=mm(0,1,se)*s}let G;M?(this.delayState.value=y[0],G=this.delayState):G=V.next(B),o&&!M&&(G.value=o(G.value));let{done:W}=G;!M&&f!==null&&(W=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const Z=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&W);return Z&&k!==LV&&(G.value=$3(y,this.options,R,this.speed)),P&&P(G.value),Z&&this.finish(),G}then(e,r){return this.finished.then(e,r)}get duration(){return Xd(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Xd(e)}get time(){return Xd(this.currentTime)}set time(e){e=Pu(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 Jve(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(Kc.now()),this.playbackSpeed=e,r&&this.driver&&(this.time=Xd(this.currentTime))}play(){var i,o;if(this.isStopped)return;const{driver:e=bQe,startTime:r}=this.options;this.driver||(this.driver=e(c=>this.tick(c))),(o=(i=this.options).onPlay)==null||o.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(Kc.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 BQe(t){for(let e=1;et*180/Math.PI,DV=t=>{const e=d_(Math.atan2(t[1],t[0]));return MV(e)},zQe={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:DV,rotateZ:DV,skewX:t=>d_(Math.atan(t[1])),skewY:t=>d_(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},MV=t=>(t=t%360,t<0&&(t+=360),t),Zre=DV,Xre=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Qre=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),$Qe={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Xre,scaleY:Qre,scale:t=>(Xre(t)+Qre(t))/2,rotateX:t=>MV(d_(Math.atan2(t[6],t[5]))),rotateY:t=>MV(d_(Math.atan2(-t[2],t[0]))),rotateZ:Zre,rotate:Zre,skewX:t=>d_(Math.atan(t[4])),skewY:t=>d_(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function OV(t){return t.includes("scale")?1:0}function FV(t,e){if(!t||t==="none")return OV(e);const r=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,i;if(r)n=$Qe,i=r;else{const s=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=zQe,i=s}if(!i)return OV(e);const o=n[e],c=i[1].split(",").map(VQe);return typeof o=="function"?o(c):c[o]}const UQe=(t,e)=>{const{transform:r="none"}=getComputedStyle(t);return FV(r,e)};function VQe(t){return parseFloat(t.trim())}const XS=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],QS=new Set(XS),Jre=t=>t===ZS||t===Nn,qQe=new Set(["x","y","z"]),GQe=XS.filter(t=>!qQe.has(t));function HQe(t){const e=[];return GQe.forEach(r=>{const n=t.getValue(r);n!==void 0&&(e.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),e}const Cy={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})=>FV(e,"x"),y:(t,{transform:e})=>FV(e,"y")};Cy.translateX=Cy.x;Cy.translateY=Cy.y;const k_=new Set;let BV=!1,zV=!1,$V=!1;function tbe(){if(zV){const t=Array.from(k_).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),r=new Map;e.forEach(n=>{const i=HQe(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(([o,c])=>{var s;(s=n.getValue(o))==null||s.set(c)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}zV=!1,BV=!1,k_.forEach(t=>t.complete($V)),k_.clear()}function rbe(){k_.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(zV=!0)})}function WQe(){$V=!0,rbe(),tbe(),$V=!1}class cH{constructor(e,r,n,i,o,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=o,this.isAsync=c}scheduleResolve(){this.state="scheduled",this.isAsync?(k_.add(this),BV||(BV=!0,na.read(rbe),na.resolveKeyframes(tbe))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:r,element:n,motionValue:i}=this;if(e[0]===null){const o=i==null?void 0:i.get(),c=e[e.length-1];if(o!==void 0)e[0]=o;else if(n&&r){const s=n.readValue(r,c);s!=null&&(e[0]=s)}e[0]===void 0&&(e[0]=c),i&&o===void 0&&i.set(e[0])}BQe(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),k_.delete(this)}cancel(){this.state==="scheduled"&&(k_.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const KQe=t=>t.startsWith("--");function nbe(t,e,r){KQe(e)?t.style.setProperty(e,r):t.style[e]=r}const YQe={};function ibe(t,e){const r=Nve(t);return()=>YQe[e]??r()}const ZQe=ibe(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),sbe=ibe(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),_A=([t,e,r,n])=>`cubic-bezier(${t}, ${e}, ${r}, ${n})`,ene={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:_A([0,.65,.55,1]),circOut:_A([.55,0,1,.45]),backIn:_A([.31,.01,.66,-.59]),backOut:_A([.33,1.53,.69,.99])};function abe(t,e){if(t)return typeof t=="function"?sbe()?Qve(t,e):"ease-out":Uve(t)?_A(t):Array.isArray(t)?t.map(r=>abe(r,e)||ene.easeOut):ene[t]}function XQe(t,e,r,{delay:n=0,duration:i=300,repeat:o=0,repeatType:c="loop",ease:s="easeOut",times:f}={},p=void 0){const y={[e]:r};f&&(y.offset=f);const _=abe(s,i);Array.isArray(_)&&(y.easing=_);const T={delay:n,duration:i,easing:Array.isArray(_)?"linear":_,fill:"both",iterations:o+1,direction:c==="reverse"?"alternate":"normal"};return p&&(T.pseudoElement=p),t.animate(y,T)}function obe(t){return typeof t=="function"&&"applyToOptions"in t}function QQe({type:t,...e}){return obe(t)&&sbe()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class lbe extends lH{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:r,name:n,keyframes:i,pseudoElement:o,allowFlatten:c=!1,finalKeyframe:s,onComplete:f}=e;this.isPseudoElement=!!o,this.allowFlatten=c,this.options=e,H1(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const p=QQe(e);this.animation=XQe(r,n,i,p,o),p.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const y=$3(i,this.options,s,this.speed);this.updateMotionValue&&this.updateMotionValue(y),nbe(r,n,y),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 Xd(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Xd(e)}get time(){return Xd(Number(this.animation.currentTime)||0)}set time(e){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Pu(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 o;return this.allowFlatten&&((o=this.animation.effect)==null||o.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&ZQe()?(this.animation.timeline=e,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),rh):i(this)}}const cbe={anticipate:Fve,backInOut:Ove,circInOut:zve};function JQe(t){return t in cbe}function eJe(t){typeof t.ease=="string"&&JQe(t.ease)&&(t.ease=cbe[t.ease])}const Oz=10;class tJe extends lbe{constructor(e){eJe(e),ebe(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:o,...c}=this.options;if(!r)return;if(e!==void 0){r.set(e);return}const s=new GD({...c,autoplay:!1}),f=Math.max(Oz,Kc.now()-this.startTime),p=mm(0,Oz,f-Oz),y=s.sample(f).value,{name:_}=this.options;o&&_&&nbe(o,_,y),r.setWithVelocity(s.sample(Math.max(0,f-p)).value,y,p),s.stop()}}const tne=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(nf.test(t)||t==="0")&&!t.startsWith("url("));function rJe(t){const e=t[0];if(t.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function lJe(t){var _;const{motionValue:e,name:r,repeatDelay:n,repeatType:i,damping:o,type:c,keyframes:s}=t;if(!(((_=e==null?void 0:e.owner)==null?void 0:_.current)instanceof HTMLElement))return!1;const{onUpdate:p,transformTemplate:y}=e.owner.getProps();return oJe()&&r&&(ube.has(r)||aJe.has(r)&&sJe(s))&&(r!=="transform"||!y)&&!p&&!n&&i!=="mirror"&&o!==0&&c!=="inertia"}const cJe=40;class uJe extends lH{constructor({autoplay:e=!0,delay:r=0,type:n="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:c="loop",keyframes:s,name:f,motionValue:p,element:y,..._}){var k;super(),this.stop=()=>{var P,R;this._animation&&(this._animation.stop(),(P=this.stopTimeline)==null||P.call(this)),(R=this.keyframeResolver)==null||R.cancel()},this.createdAt=Kc.now();const T={autoplay:e,delay:r,type:n,repeat:i,repeatDelay:o,repeatType:c,name:f,motionValue:p,element:y,..._},E=(y==null?void 0:y.KeyframeResolver)||cH;this.keyframeResolver=new E(s,(P,R,D)=>this.onKeyframesResolved(P,R,T,!D),f,p,y),(k=this.keyframeResolver)==null||k.scheduleResolve()}onKeyframesResolved(e,r,n,i){var D,M;this.keyframeResolver=void 0;const{name:o,type:c,velocity:s,delay:f,isHandoff:p,onUpdate:y}=n;this.resolvedAt=Kc.now();let _=!0;nJe(e,o,c,s)||(_=!1,(ix.instantAnimations||!f)&&(y==null||y($3(e,n,r))),e[0]=e[e.length-1],UV(n),n.repeat=0);const E={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>cJe?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:e},k=_&&!p&&lJe(E),P=(M=(D=E.motionValue)==null?void 0:D.owner)==null?void 0:M.current;let R;if(k)try{R=new tJe({...E,element:P})}catch{R=new GD(E)}else R=new GD(E);R.finished.then(()=>{this.notifyFinished()}).catch(rh),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(),WQe()),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 dbe(t,e,r,n=0,i=1){const o=Array.from(t).sort((p,y)=>p.sortNodePosition(y)).indexOf(e),c=t.size,s=(c-1)*n;return typeof r=="function"?r(o,c):i===1?o*n:s-o*n}const dJe=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hJe(t){const e=dJe.exec(t);if(!e)return[,];const[,r,n,i]=e;return[`--${r??n}`,i]}const fJe=4;function hbe(t,e,r=1){H1(r<=fJe,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,i]=hJe(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const c=o.trim();return kve(c)?parseFloat(c):c}return nH(i)?hbe(i,e,r+1):i}const mJe={type:"spring",stiffness:500,damping:25,restSpeed:10},pJe=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),gJe={type:"keyframes",duration:.8},yJe={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},xJe=(t,{keyframes:e})=>e.length>2?gJe:QS.has(t)?t.startsWith("scale")?pJe(e[1]):mJe:yJe;function fbe(t,e){if(t!=null&&t.inherit&&e){const{inherit:r,...n}=t;return{...e,...n}}return t}function uH(t,e){const r=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return r!==t?fbe(r,t):r}const _Je=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function vJe(t){for(const e in t)if(!_Je.has(e))return!0;return!1}const dH=(t,e,r,n={},i,o)=>c=>{const s=uH(n,t)||{},f=s.delay||n.delay||0;let{elapsed:p=0}=n;p=p-Pu(f);const y={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:e.getVelocity(),...s,delay:-p,onUpdate:T=>{e.set(T),s.onUpdate&&s.onUpdate(T)},onComplete:()=>{c(),s.onComplete&&s.onComplete()},name:t,motionValue:e,element:o?void 0:i};vJe(s)||Object.assign(y,xJe(t,y)),y.duration&&(y.duration=Pu(y.duration)),y.repeatDelay&&(y.repeatDelay=Pu(y.repeatDelay)),y.from!==void 0&&(y.keyframes[0]=y.from);let _=!1;if((y.type===!1||y.duration===0&&!y.repeatDelay)&&(UV(y),y.delay===0&&(_=!0)),(ix.instantAnimations||ix.skipAnimations||i!=null&&i.shouldSkipAnimations)&&(_=!0,UV(y),y.delay=0),y.allowFlatten=!s.type&&!s.ease,_&&!o&&e.get()!==void 0){const T=$3(y.keyframes,s);if(T!==void 0){na.update(()=>{y.onUpdate(T),y.onComplete()});return}}return s.isSync?new GD(y):new uJe(y)};function rne(t){const e=[{},{}];return t==null||t.values.forEach((r,n)=>{e[0][n]=r.get(),e[1][n]=r.getVelocity()}),e}function hH(t,e,r,n){if(typeof e=="function"){const[i,o]=rne(n);e=e(r!==void 0?r:t.custom,i,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[i,o]=rne(n);e=e(r!==void 0?r:t.custom,i,o)}return e}function C_(t,e,r){const n=t.getProps();return hH(n,e,r!==void 0?r:n.custom,t)}const mbe=new Set(["width","height","top","left","right","bottom",...XS]),nne=30,bJe=t=>!isNaN(parseFloat(t));class wJe{constructor(e,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var o;const i=Kc.now();if(this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((o=this.events.change)==null||o.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=Kc.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=bJe(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 eH);const n=this.events[e].add(r);return e==="change"?()=>{n(),na.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=Kc.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>nne)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,nne);return Pve(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 K1(t,e){return new wJe(t,e)}const VV=t=>Array.isArray(t);function SJe(t,e,r){t.hasValue(e)?t.getValue(e).set(r):t.addValue(e,K1(r))}function TJe(t){return VV(t)?t[t.length-1]||0:t}function EJe(t,e){const r=C_(t,e);let{transitionEnd:n={},transition:i={},...o}=r||{};o={...o,...n};for(const c in o){const s=TJe(o[c]);SJe(t,c,s)}}const ec=t=>!!(t&&t.getVelocity);function AJe(t){return!!(ec(t)&&t.add)}function qV(t,e){const r=t.getValue("willChange");if(AJe(r))return r.add(e);if(!r&&ix.WillChange){const n=new ix.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function fH(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const jJe="framerAppearId",pbe="data-"+fH(jJe);function gbe(t){return t.props[pbe]}function kJe({protectedKeys:t,needsAnimating:e},r){const n=t.hasOwnProperty(r)&&e[r]!==!0;return e[r]=!1,n}function ybe(t,e,{delay:r=0,transitionOverride:n,type:i}={}){let{transition:o,transitionEnd:c,...s}=e;const f=t.getDefaultTransition();o=o?fbe(o,f):f;const p=o==null?void 0:o.reduceMotion;n&&(o=n);const y=[],_=i&&t.animationState&&t.animationState.getState()[i];for(const T in s){const E=t.getValue(T,t.latestValues[T]??null),k=s[T];if(k===void 0||_&&kJe(_,T))continue;const P={delay:r,...uH(o||{},T)},R=E.get();if(R!==void 0&&!E.isAnimating()&&!Array.isArray(k)&&k===R&&!P.velocity){na.update(()=>E.set(k));continue}let D=!1;if(window.MotionHandoffAnimation){const V=gbe(t);if(V){const G=window.MotionHandoffAnimation(V,T,na);G!==null&&(P.startTime=G,D=!0)}}qV(t,T);const M=p??t.shouldReduceMotion;E.start(dH(T,E,k,M&&mbe.has(T)?{type:!1}:P,t,D));const B=E.animation;B&&y.push(B)}if(c){const T=()=>na.update(()=>{c&&EJe(t,c)});y.length?Promise.all(y).then(T):T()}return y}function GV(t,e,r={}){var f;const n=C_(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 o=n?()=>Promise.all(ybe(t,n,r)):()=>Promise.resolve(),c=t.variantChildren&&t.variantChildren.size?(p=0)=>{const{delayChildren:y=0,staggerChildren:_,staggerDirection:T}=i;return CJe(t,e,p,y,_,T,r)}:()=>Promise.resolve(),{when:s}=i;if(s){const[p,y]=s==="beforeChildren"?[o,c]:[c,o];return p().then(()=>y())}else return Promise.all([o(),c(r.delay)])}function CJe(t,e,r=0,n=0,i=0,o=1,c){const s=[];for(const f of t.variantChildren)f.notify("AnimationStart",e),s.push(GV(f,e,{...c,delay:r+(typeof n=="function"?0:n)+dbe(t.variantChildren,f,n,i,o)}).then(()=>f.notify("AnimationComplete",e)));return Promise.all(s)}function IJe(t,e,r={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const i=e.map(o=>GV(t,o,r));n=Promise.all(i)}else if(typeof e=="string")n=GV(t,e,r);else{const i=typeof e=="function"?C_(t,e,r.custom):e;n=Promise.all(ybe(t,i,r))}return n.then(()=>{t.notify("AnimationComplete",e)})}const NJe={test:t=>t==="auto",parse:t=>t},xbe=t=>e=>e.test(t),_be=[ZS,Nn,am,ry,rQe,tQe,NJe],ine=t=>_be.find(xbe(t));function PJe(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ive(t):!0}const RJe=new Set(["brightness","contrast","saturate","opacity"]);function LJe(t){const[e,r]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=r.match(iH)||[];if(!n)return t;const i=r.replace(n,"");let o=RJe.has(e)?1:0;return n!==r&&(o*=100),e+"("+o+i+")"}const DJe=/\b([a-z-]*)\(.*?\)/gu,HV={...nf,getAnimatableNone:t=>{const e=t.match(DJe);return e?e.map(LJe).join(" "):t}},WV={...nf,getAnimatableNone:t=>{const e=nf.parse(t);return nf.createTransformer(t)(e.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},sne={...ZS,transform:Math.round},MJe={rotate:ry,rotateX:ry,rotateY:ry,rotateZ:ry,scale:ZP,scaleX:ZP,scaleY:ZP,scaleZ:ZP,skew:ry,skewX:ry,skewY:ry,distance:Nn,translateX:Nn,translateY:Nn,translateZ:Nn,x:Nn,y:Nn,z:Nn,perspective:Nn,transformPerspective:Nn,opacity:Hj,originX:Gre,originY:Gre,originZ:Nn},mH={borderWidth:Nn,borderTopWidth:Nn,borderRightWidth:Nn,borderBottomWidth:Nn,borderLeftWidth:Nn,borderRadius:Nn,borderTopLeftRadius:Nn,borderTopRightRadius:Nn,borderBottomRightRadius:Nn,borderBottomLeftRadius:Nn,width:Nn,maxWidth:Nn,height:Nn,maxHeight:Nn,top:Nn,right:Nn,bottom:Nn,left:Nn,inset:Nn,insetBlock:Nn,insetBlockStart:Nn,insetBlockEnd:Nn,insetInline:Nn,insetInlineStart:Nn,insetInlineEnd:Nn,padding:Nn,paddingTop:Nn,paddingRight:Nn,paddingBottom:Nn,paddingLeft:Nn,paddingBlock:Nn,paddingBlockStart:Nn,paddingBlockEnd:Nn,paddingInline:Nn,paddingInlineStart:Nn,paddingInlineEnd:Nn,margin:Nn,marginTop:Nn,marginRight:Nn,marginBottom:Nn,marginLeft:Nn,marginBlock:Nn,marginBlockStart:Nn,marginBlockEnd:Nn,marginInline:Nn,marginInlineStart:Nn,marginInlineEnd:Nn,fontSize:Nn,backgroundPositionX:Nn,backgroundPositionY:Nn,...MJe,zIndex:sne,fillOpacity:Hj,strokeOpacity:Hj,numOctaves:sne},OJe={...mH,color:Vo,backgroundColor:Vo,outlineColor:Vo,fill:Vo,stroke:Vo,borderColor:Vo,borderTopColor:Vo,borderRightColor:Vo,borderBottomColor:Vo,borderLeftColor:Vo,filter:HV,WebkitFilter:HV,mask:WV,WebkitMask:WV},vbe=t=>OJe[t],FJe=new Set([HV,WV]);function bbe(t,e){let r=vbe(t);return FJe.has(r)||(r=nf),r.getAnimatableNone?r.getAnimatableNone(e):void 0}const BJe=new Set(["auto","none","0"]);function zJe(t,e,r){let n=0,i;for(;n{e.getValue(f).set(p)}),this.resolveNoneKeyframes()}}function wbe(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 Sbe=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function fL(t){return Cve(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:pH,cancel:Oqt}=Vve(queueMicrotask,!1),Mh={x:!1,y:!1};function Tbe(){return Mh.x||Mh.y}function UJe(t){return t==="x"||t==="y"?Mh[t]?null:(Mh[t]=!0,()=>{Mh[t]=!1}):Mh.x||Mh.y?null:(Mh.x=Mh.y=!0,()=>{Mh.x=Mh.y=!1})}function Ebe(t,e){const r=wbe(t),n=new AbortController,i={passive:!0,...e,signal:n.signal};return[r,i,()=>n.abort()]}function VJe(t){return!(t.pointerType==="touch"||Tbe())}function qJe(t,e,r={}){const[n,i,o]=Ebe(t,r);return n.forEach(c=>{let s=!1,f=!1,p;const y=()=>{c.removeEventListener("pointerleave",k)},_=R=>{p&&(p(R),p=void 0),y()},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)},k=R=>{if(R.pointerType!=="touch"){if(s){f=!0;return}_(R)}},P=R=>{if(!VJe(R))return;f=!1;const D=e(c,R);typeof D=="function"&&(p=D,c.addEventListener("pointerleave",k,i))};c.addEventListener("pointerenter",P,i),c.addEventListener("pointerdown",E,i)}),o}const Abe=(t,e)=>e?t===e?!0:Abe(t,e.parentElement):!1,gH=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,GJe=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function HJe(t){return GJe.has(t.tagName)||t.isContentEditable===!0}const WJe=new Set(["INPUT","SELECT","TEXTAREA"]);function KJe(t){return WJe.has(t.tagName)||t.isContentEditable===!0}const mL=new WeakSet;function ane(t){return e=>{e.key==="Enter"&&t(e)}}function Fz(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const YJe=(t,e)=>{const r=t.currentTarget;if(!r)return;const n=ane(()=>{if(mL.has(r))return;Fz(r,"down");const i=ane(()=>{Fz(r,"up")}),o=()=>Fz(r,"cancel");r.addEventListener("keyup",i,e),r.addEventListener("blur",o,e)});r.addEventListener("keydown",n,e),r.addEventListener("blur",()=>r.removeEventListener("keydown",n),e)};function one(t){return gH(t)&&!Tbe()}const lne=new WeakSet;function ZJe(t,e,r={}){const[n,i,o]=Ebe(t,r),c=s=>{const f=s.currentTarget;if(!one(s)||lne.has(s))return;mL.add(f),r.stopPropagation&&lne.add(s);const p=e(f,s),y=(E,k)=>{window.removeEventListener("pointerup",_),window.removeEventListener("pointercancel",T),mL.has(f)&&mL.delete(f),one(E)&&typeof p=="function"&&p(E,{success:k})},_=E=>{y(E,f===window||f===document||r.useGlobalTarget||Abe(f,E.target))},T=E=>{y(E,!1)};window.addEventListener("pointerup",_,i),window.addEventListener("pointercancel",T,i)};return n.forEach(s=>{(r.useGlobalTarget?window:s).addEventListener("pointerdown",c,i),fL(s)&&(s.addEventListener("focus",p=>YJe(p,i)),!HJe(s)&&!s.hasAttribute("tabindex")&&(s.tabIndex=0))}),o}function yH(t){return Cve(t)&&"ownerSVGElement"in t}const pL=new WeakMap;let ny;const jbe=(t,e,r)=>(n,i)=>i&&i[0]?i[0][t+"Size"]:yH(n)&&"getBBox"in n?n.getBBox()[e]:n[r],XJe=jbe("inline","width","offsetWidth"),QJe=jbe("block","height","offsetHeight");function JJe({target:t,borderBoxSize:e}){var r;(r=pL.get(t))==null||r.forEach(n=>{n(t,{get width(){return XJe(t,e)},get height(){return QJe(t,e)}})})}function eet(t){t.forEach(JJe)}function tet(){typeof ResizeObserver>"u"||(ny=new ResizeObserver(eet))}function ret(t,e){ny||tet();const r=wbe(t);return r.forEach(n=>{let i=pL.get(n);i||(i=new Set,pL.set(n,i)),i.add(e),ny==null||ny.observe(n)}),()=>{r.forEach(n=>{const i=pL.get(n);i==null||i.delete(e),i!=null&&i.size||ny==null||ny.unobserve(n)})}}const gL=new Set;let Rw;function net(){Rw=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};gL.forEach(e=>e(t))},window.addEventListener("resize",Rw)}function iet(t){return gL.add(t),Rw||net(),()=>{gL.delete(t),!gL.size&&typeof Rw=="function"&&(window.removeEventListener("resize",Rw),Rw=void 0)}}function cne(t,e){return typeof t=="function"?iet(t):ret(t,e)}function set(t){return yH(t)&&t.tagName==="svg"}const aet=[..._be,Vo,nf],oet=t=>aet.find(xbe(t)),une=()=>({translate:0,scale:1,origin:0,originPoint:0}),Lw=()=>({x:une(),y:une()}),dne=()=>({min:0,max:0}),il=()=>({x:dne(),y:dne()}),cet=new WeakMap;function U3(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Wj(t){return typeof t=="string"||Array.isArray(t)}const xH=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],_H=["initial",...xH];function V3(t){return U3(t.animate)||_H.some(e=>Wj(t[e]))}function kbe(t){return!!(V3(t)||t.variants)}function uet(t,e,r){for(const n in e){const i=e[n],o=r[n];if(ec(i))t.addValue(n,i);else if(ec(o))t.addValue(n,K1(i,{owner:t}));else if(o!==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,K1(c!==void 0?c:i,{owner:t}))}}for(const n in r)e[n]===void 0&&t.removeValue(n);return e}const KV={current:null},Cbe={current:!1},det=typeof window<"u";function het(){if(Cbe.current=!0,!!det)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>KV.current=t.matches;t.addEventListener("change",e),e()}else KV.current=!1}const hne=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let HD={};function Ibe(t){HD=t}function fet(){return HD}class met{scrapeMotionValuesFromProps(e,r,n){return{}}constructor({parent:e,props:r,presenceContext:n,reducedMotionConfig:i,skipAnimations:o,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=cH,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=Kc.now();this.renderScheduledAtthis.bindToMotionValue(o,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Cbe.current||het(),this.shouldReduceMotion=KV.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(),sx(this.notifyUpdate),sx(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&&ube.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:s,times:f,ease:p,duration:y}=r.accelerate,_=new lbe({element:this.current,name:e,keyframes:s,times:f,ease:p,duration:Pu(y)}),T=c(_);this.valueSubscriptions.set(e,()=>{T(),_.cancel()});return}const n=QS.has(e);n&&this.onBindTransform&&this.onBindTransform();const i=r.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&na.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;typeof window<"u"&&window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,r)),this.valueSubscriptions.set(e,()=>{i(),o&&o(),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 HD){const r=HD[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 o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):il()}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=K1(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"&&(kve(n)||Ive(n))?n=parseFloat(n):!oet(n)&&nf.test(r)&&(n=bbe(e,r)),this.setBaseTarget(e,ec(n)?n.get():n)),ec(n)?n.get():n}setBaseTarget(e,r){this.baseTarget[e]=r}getBaseTarget(e){var o;const{initial:r}=this.props;let n;if(typeof r=="string"||typeof r=="object"){const c=hH(this.props,r,(o=this.presenceContext)==null?void 0:o.custom);c&&(n=c[e])}if(r&&n!==void 0)return n;const i=this.getBaseTargetFromProps(this.props,e);return i!==void 0&&!ec(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 eH),this.events[e].add(r)}notify(e,...r){this.events[e]&&this.events[e].notify(...r)}scheduleRenderMicrotask(){pH.render(this.render)}}class Nbe extends met{constructor(){super(...arguments),this.KeyframeResolver=$Je}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;ec(e)&&(this.childSubscription=e.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class Sx{constructor(e){this.isMounted=!1,this.node=e}update(){}}function Pbe({top:t,left:e,right:r,bottom:n}){return{x:{min:e,max:r},y:{min:t,max:n}}}function pet({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function get(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 Bz(t){return t===void 0||t===1}function YV({scale:t,scaleX:e,scaleY:r}){return!Bz(t)||!Bz(e)||!Bz(r)}function Q0(t){return YV(t)||Rbe(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Rbe(t){return fne(t.x)||fne(t.y)}function fne(t){return t&&t!=="0%"}function WD(t,e,r){const n=t-r,i=e*n;return r+i}function mne(t,e,r,n,i){return i!==void 0&&(t=WD(t,i,n)),WD(t,r,n)+e}function ZV(t,e=0,r=1,n,i){t.min=mne(t.min,e,r,n,i),t.max=mne(t.max,e,r,n,i)}function Lbe(t,{x:e,y:r}){ZV(t.x,e.translate,e.scale,e.originPoint),ZV(t.y,r.translate,r.scale,r.originPoint)}const pne=.999999999999,gne=1.0000000000001;function yet(t,e,r,n=!1){var s;const i=r.length;if(!i)return;e.x=e.y=1;let o,c;for(let f=0;fpne&&(e.x=1),e.ypne&&(e.y=1)}function Gf(t,e){t.min+=e,t.max+=e}function yne(t,e,r,n,i=.5){const o=Pa(t.min,t.max,i);ZV(t,e,r,o,n)}function xne(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function yL(t,e,r){const n=r??t;yne(t.x,xne(e.x,n.x),e.scaleX,e.scale,e.originX),yne(t.y,xne(e.y,n.y),e.scaleY,e.scale,e.originY)}function Dbe(t,e){return Pbe(get(t.getBoundingClientRect(),e))}function xet(t,e,r){const n=Dbe(t,r),{scroll:i}=e;return i&&(Gf(n.x,i.offset.x),Gf(n.y,i.offset.y)),n}const _et={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},vet=XS.length;function bet(t,e,r){let n="",i=!0;for(let o=0;o{if(!e.target)return t;if(typeof t=="string")if(Nn.test(t))t=parseFloat(t);else return t;const r=_ne(t,e.target.x),n=_ne(t,e.target.y);return`${r}% ${n}%`}},wet={correct:(t,{treeScale:e,projectionDelta:r})=>{const n=t,i=nf.parse(t);if(i.length>5)return n;const o=nf.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 p=Pa(s,f,.5);return typeof i[2+c]=="number"&&(i[2+c]/=p),typeof i[3+c]=="number"&&(i[3+c]/=p),o(i)}},XV={borderRadius:{...H2,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:H2,borderTopRightRadius:H2,borderBottomLeftRadius:H2,borderBottomRightRadius:H2,boxShadow:wet};function Obe(t,{layout:e,layoutId:r}){return QS.has(t)||t.startsWith("origin")||(e||r!==void 0)&&(!!XV[t]||t==="opacity")}function bH(t,e,r){var c;const n=t.style,i=e==null?void 0:e.style,o={};if(!n)return o;for(const s in n)(ec(n[s])||i&&ec(i[s])||Obe(s,t)||((c=r==null?void 0:r.getValue(s))==null?void 0:c.liveStyle)!==void 0)&&(o[s]=n[s]);return o}function Tet(t){return window.getComputedStyle(t)}class Eet extends Nbe{constructor(){super(...arguments),this.type="html",this.renderInstance=Mbe}readValueFromInstance(e,r){var n;if(QS.has(r))return(n=this.projection)!=null&&n.isProjecting?OV(r):UQe(e,r);{const i=Tet(e),o=(Gve(r)?i.getPropertyValue(r):i[r])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:r}){return Dbe(e,r)}build(e,r,n){vH(e,r,n.transformTemplate)}scrapeMotionValuesFromProps(e,r,n){return bH(e,r,n)}}const Aet={offset:"stroke-dashoffset",array:"stroke-dasharray"},jet={offset:"strokeDashoffset",array:"strokeDasharray"};function ket(t,e,r=1,n=0,i=!0){t.pathLength=1;const o=i?Aet:jet;t[o.offset]=`${-n}`,t[o.array]=`${e} ${r}`}const Cet=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Fbe(t,{attrX:e,attrY:r,attrScale:n,pathLength:i,pathSpacing:o=1,pathOffset:c=0,...s},f,p,y){if(vH(t,s,p),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=(y==null?void 0:y.transformBox)??"fill-box",delete _.transformBox);for(const E of Cet)_[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&&ket(_,i,o,c,!1)}const Bbe=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"]),zbe=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Iet(t,e,r,n){Mbe(t,e,void 0,n);for(const i in e.attrs)t.setAttribute(Bbe.has(i)?i:fH(i),e.attrs[i])}function $be(t,e,r){const n=bH(t,e,r);for(const i in t)if(ec(t[i])||ec(e[i])){const o=XS.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;n[o]=t[i]}return n}class Net extends Nbe{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=il}getBaseTargetFromProps(e,r){return e[r]}readValueFromInstance(e,r){if(QS.has(r)){const n=vbe(r);return n&&n.default||0}return r=Bbe.has(r)?r:fH(r),e.getAttribute(r)}scrapeMotionValuesFromProps(e,r,n){return $be(e,r,n)}build(e,r,n){Fbe(e,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,r,n,i){Iet(e,r,n,i)}mount(e){this.isSVGTag=zbe(e.tagName),super.mount(e)}}const Pet=_H.length;function Ube(t){if(!t)return;if(!t.isControllingVariants){const r=t.parent?Ube(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})=>IJe(t,r,n)))}function Met(t){let e=Det(t),r=vne(),n=!0,i=!1;const o=p=>(y,_)=>{var E;const T=C_(t,_,p==="exit"?(E=t.presenceContext)==null?void 0:E.custom:void 0);if(T){const{transition:k,transitionEnd:P,...R}=T;y={...y,...R,...P}}return y};function c(p){e=p(t)}function s(p){const{props:y}=t,_=Ube(t.parent)||{},T=[],E=new Set;let k={},P=1/0;for(let D=0;DP&&G,se=!1;const ue=Array.isArray(V)?V:[V];let _e=ue.reduce(o(M),{});W===!1&&(_e={});const{prevResolvedValues:we={}}=B,Ce={...we,..._e},Me=me=>{re=!0,E.has(me)&&(se=!0,E.delete(me)),B.needsAnimating[me]=!0;const Pe=t.getValue(me);Pe&&(Pe.liveStyle=!1)};for(const me in Ce){const Pe=_e[me],Ie=we[me];if(k.hasOwnProperty(me))continue;let Se=!1;VV(Pe)&&VV(Ie)?Se=!Vbe(Pe,Ie):Se=Pe!==Ie,Se?Pe!=null?Me(me):E.add(me):Pe!==void 0&&E.has(me)?Me(me):B.protectedKeys[me]=!0}B.prevProp=V,B.prevResolvedValues=_e,B.isActive&&(k={...k,..._e}),(n||i)&&t.blockInitialAnimation&&(re=!1);const Ae=Z&&Q;re&&(!Ae||se)&&T.push(...ue.map(me=>{const Pe={type:M};if(typeof me=="string"&&(n||i)&&!Ae&&t.manuallyAnimateOnMount&&t.parent){const{parent:Ie}=t,Se=C_(Ie,me);if(Ie.enteringChildren&&Se){const{delayChildren:ve}=Se.transition||{};Pe.delay=dbe(Ie.enteringChildren,t,ve)}}return{animation:me,options:Pe}}))}if(E.size){const D={};if(typeof y.initial!="boolean"){const M=C_(t,Array.isArray(y.initial)?y.initial[0]:y.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&&(y.initial===!1||y.initial===y.animate)&&!t.manuallyAnimateOnMount&&(R=!1),n=!1,i=!1,R?e(T):Promise.resolve()}function f(p,y){var T;if(r[p].isActive===y)return Promise.resolve();(T=t.variantChildren)==null||T.forEach(E=>{var k;return(k=E.animationState)==null?void 0:k.setActive(p,y)}),r[p].isActive=y;const _=s(p);for(const E in r)r[E].protectedKeys={};return _}return{animateChanges:s,setActive:f,setAnimateFunction:c,getState:()=>r,reset:()=>{r=vne(),i=!0}}}function Oet(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Vbe(e,t):!1}function U0(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function vne(){return{animate:U0(!0),whileInView:U0(),whileHover:U0(),whileTap:U0(),whileDrag:U0(),whileFocus:U0(),exit:U0()}}function QV(t,e){t.min=e.min,t.max=e.max}function Ph(t,e){QV(t.x,e.x),QV(t.y,e.y)}function bne(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const qbe=1e-4,Fet=1-qbe,Bet=1+qbe,Gbe=.01,zet=0-Gbe,$et=0+Gbe;function Yc(t){return t.max-t.min}function Uet(t,e,r){return Math.abs(t-e)<=r}function wne(t,e,r,n=.5){t.origin=n,t.originPoint=Pa(e.min,e.max,t.origin),t.scale=Yc(r)/Yc(e),t.translate=Pa(r.min,r.max,t.origin)-t.originPoint,(t.scale>=Fet&&t.scale<=Bet||isNaN(t.scale))&&(t.scale=1),(t.translate>=zet&&t.translate<=$et||isNaN(t.translate))&&(t.translate=0)}function GA(t,e,r,n){wne(t.x,e.x,r.x,n?n.originX:void 0),wne(t.y,e.y,r.y,n?n.originY:void 0)}function Sne(t,e,r,n=0){const i=n?Pa(r.min,r.max,n):r.min;t.min=i+e.min,t.max=t.min+Yc(e)}function Vet(t,e,r,n){Sne(t.x,e.x,r.x,n==null?void 0:n.x),Sne(t.y,e.y,r.y,n==null?void 0:n.y)}function Tne(t,e,r,n=0){const i=n?Pa(r.min,r.max,n):r.min;t.min=e.min-i,t.max=t.min+Yc(e)}function KD(t,e,r,n){Tne(t.x,e.x,r.x,n==null?void 0:n.x),Tne(t.y,e.y,r.y,n==null?void 0:n.y)}function Ene(t,e,r,n,i){return t-=e,t=WD(t,1/r,n),i!==void 0&&(t=WD(t,1/i,n)),t}function qet(t,e=0,r=1,n=.5,i,o=t,c=t){if(am.test(e)&&(e=parseFloat(e),e=Pa(c.min,c.max,e/100)-c.min),typeof e!="number")return;let s=Pa(o.min,o.max,n);t===o&&(s-=e),t.min=Ene(t.min,e,r,s,i),t.max=Ene(t.max,e,r,s,i)}function Ane(t,e,[r,n,i],o,c){qet(t,e[r],e[n],e[i],e.scale,o,c)}const Get=["x","scaleX","originX"],Het=["y","scaleY","originY"];function jne(t,e,r,n){Ane(t.x,e,Get,r?r.x:void 0,n?n.x:void 0),Ane(t.y,e,Het,r?r.y:void 0,n?n.y:void 0)}function kne(t){return t.translate===0&&t.scale===1}function Hbe(t){return kne(t.x)&&kne(t.y)}function Cne(t,e){return t.min===e.min&&t.max===e.max}function Wet(t,e){return Cne(t.x,e.x)&&Cne(t.y,e.y)}function Ine(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Wbe(t,e){return Ine(t.x,e.x)&&Ine(t.y,e.y)}function Nne(t){return Yc(t.x)/Yc(t.y)}function Pne(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function zf(t){return[t("x"),t("y")]}function Ket(t,e,r){let n="";const i=t.x.translate/e.x,o=t.y.translate/e.y,c=(r==null?void 0:r.z)||0;if((i||o||c)&&(n=`translate3d(${i}px, ${o}px, ${c}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),r){const{transformPerspective:p,rotate:y,rotateX:_,rotateY:T,skewX:E,skewY:k}=r;p&&(n=`perspective(${p}px) ${n}`),y&&(n+=`rotate(${y}deg) `),_&&(n+=`rotateX(${_}deg) `),T&&(n+=`rotateY(${T}deg) `),E&&(n+=`skewX(${E}deg) `),k&&(n+=`skewY(${k}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 Kbe=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],Yet=Kbe.length,Rne=t=>typeof t=="string"?parseFloat(t):t,Lne=t=>typeof t=="number"||Nn.test(t);function Zet(t,e,r,n,i,o){i?(t.opacity=Pa(0,r.opacity??1,Xet(n)),t.opacityExit=Pa(e.opacity??1,0,Qet(n))):o&&(t.opacity=Pa(e.opacity??1,r.opacity??1,n));for(let c=0;cne?1:r(Gj(t,e,n))}function Jet(t,e,r){const n=ec(t)?t:K1(t);return n.start(dH("",n,e,r)),n.animation}function Kj(t,e,r,n={passive:!0}){return t.addEventListener(e,r,n),()=>t.removeEventListener(e,r)}const ett=(t,e)=>t.depth-e.depth;class ttt{constructor(){this.children=[],this.isDirty=!1}add(e){J7(this.children,e),this.isDirty=!0}remove(e){$D(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(ett),this.isDirty=!1,this.children.forEach(e)}}function rtt(t,e){const r=Kc.now(),n=({timestamp:i})=>{const o=i-r;o>=e&&(sx(n),t(o-e))};return na.setup(n,!0),()=>sx(n)}function xL(t){return ec(t)?t.get():t}class ntt{constructor(){this.members=[]}add(e){J7(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&&($D(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if($D(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:o}=n.options,{layoutDependency:c}=e.options;(o===void 0||o!==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,o,c;(n=(r=e.options).onExitComplete)==null||n.call(r),(c=(i=e.resumingFrom)==null?void 0:(o=i.options).onExitComplete)==null||c.call(o)})}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 _L={hasAnimatedSinceResize:!0,hasEverUpdated:!1},zz=["","X","Y","Z"],itt=1e3;let stt=0;function $z(t,e,r,n){const{latestValues:i}=e;i[t]&&(r[t]=i[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Zbe(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const r=gbe(e);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:i,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(r,"transform",na,!(i||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&Zbe(n)}function Xbe({attachResizeListener:t,defaultParent:e,measureScroll:r,checkIsScrollRoot:n,resetTransform:i}){return class{constructor(c={},s=e==null?void 0:e()){this.id=stt++,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(ltt),this.nodes.forEach(mtt),this.nodes.forEach(ptt),this.nodes.forEach(ctt)},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;na.read(()=>{_=window.innerWidth}),t(c,()=>{const E=window.innerWidth;E!==_&&(_=E,this.root.updateBlockedByResize=!0,y&&y(),y=rtt(T,250),_L.hasAnimatedSinceResize&&(_L.hasAnimatedSinceResize=!1,this.nodes.forEach(Fne)))})}s&&this.root.registerSharedNode(s,this),this.options.animate!==!1&&p&&(s||f)&&this.addEventListener("didUpdate",({delta:y,hasLayoutChanged:_,hasRelativeLayoutChanged:T,layout:E})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const k=this.options.transition||p.getDefaultTransition()||vtt,{onLayoutAnimationStart:P,onLayoutAnimationComplete:R}=p.getProps(),D=!this.targetLayout||!Wbe(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={...uH(k,"layout"),onPlay:P,onComplete:R};(p.shouldReduceMotion||this.options.layoutRoot)&&(B.delay=0,B.type=!1),this.startAnimation(B),this.setAnimationOrigin(y,M)}else _||Fne(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(),sx(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(gtt),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&&Zbe(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let y=0;y{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Yc(this.snapshot.measuredBox.x)&&!Yc(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;Bne(_.x,c.x,G),Bne(_.y,c.y,G),this.setTargetDelta(_),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(KD(T,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),xtt(this.relativeTarget,this.relativeTargetOrigin,T,G),B&&Wet(this.relativeTarget,B)&&(this.isProjectionDirty=!1),B||(B=il()),Ph(B,this.relativeTarget)),P&&(this.animationValues=y,Zet(y,p,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,p;this.notifyListeners("animationStart"),(s=this.currentAnimation)==null||s.stop(),(p=(f=this.resumingFrom)==null?void 0:f.currentAnimation)==null||p.stop(),this.pendingAnimation&&(sx(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=na.update(()=>{_L.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=K1(0)),this.motionValue.jump(0,!1),this.currentAnimation=Jet(this.motionValue,[0,1e3],{...c,velocity:0,isSync:!0,onUpdate:y=>{this.mixTargetDelta(y),c.onUpdate&&c.onUpdate(y)},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(itt),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:s,target:f,layout:p,latestValues:y}=c;if(!(!s||!f||!p)){if(this!==c&&this.layout&&p&&Qbe(this.options.animationType,this.layout.layoutBox,p.layoutBox)){f=this.target||il();const _=Yc(this.layout.layoutBox.x);f.x.min=c.target.x.min,f.x.max=f.x.min+_;const T=Yc(this.layout.layoutBox.y);f.y.min=c.target.y.min,f.y.max=f.y.min+T}Ph(s,f),yL(s,y),GA(this.projectionDeltaWithTransform,this.layoutCorrected,s,y)}}registerSharedNode(c,s){this.sharedNodes.has(c)||this.sharedNodes.set(c,new ntt),this.sharedNodes.get(c).add(s);const p=s.options.initialPromotionConfig;s.promote({transition:p?p.transition:void 0,preserveFollowOpacity:p&&p.shouldPreserveFollowOpacity?p.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 p=this.getStack();p&&p.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 p={};f.z&&$z("z",c,p,this.animationValues);for(let y=0;y{var s;return(s=c.currentAnimation)==null?void 0:s.stop()}),this.root.nodes.forEach(Mne),this.root.sharedNodes.clear()}}}function att(t){t.updateLayout()}function ott(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:o}=t.options,c=e.source!==t.layout.source;if(o==="size")zf(_=>{const T=c?e.measuredBox[_]:e.layoutBox[_],E=Yc(T);T.min=n[_].min,T.max=T.min+E});else if(o==="x"||o==="y"){const _=o==="x"?"y":"x";QV(c?e.measuredBox[_]:e.layoutBox[_],n[_])}else Qbe(o,e.layoutBox,n)&&zf(_=>{const T=c?e.measuredBox[_]:e.layoutBox[_],E=Yc(n[_]);T.max=T.min+E,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[_].max=t.relativeTarget[_].min+E)});const s=Lw();GA(s,n,e.layoutBox);const f=Lw();c?GA(f,t.applyTransform(i,!0),e.measuredBox):GA(f,n,e.layoutBox);const p=!Hbe(s);let y=!1;if(!t.resumeFrom){const _=t.getClosestProjectingParent();if(_&&!_.resumeFrom){const{snapshot:T,layout:E}=_;if(T&&E){const k=t.options.layoutAnchor||void 0,P=il();KD(P,e.layoutBox,T.layoutBox,k);const R=il();KD(R,n,E.layoutBox,k),Wbe(P,R)||(y=!0),_.options.layoutRoot&&(t.relativeTarget=R,t.relativeTargetOrigin=P,t.relativeParent=_)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:f,layoutDelta:s,hasLayoutChanged:p,hasRelativeLayoutChanged:y})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function ltt(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 ctt(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function utt(t){t.clearSnapshot()}function Mne(t){t.clearMeasurements()}function dtt(t){t.isLayoutDirty=!0,t.updateLayout()}function One(t){t.isLayoutDirty=!1}function htt(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function ftt(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Fne(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function mtt(t){t.resolveTargetDelta()}function ptt(t){t.calcProjection()}function gtt(t){t.resetSkewAndRotation()}function ytt(t){t.removeLeadSnapshot()}function Bne(t,e,r){t.translate=Pa(e.translate,0,r),t.scale=Pa(e.scale,1,r),t.origin=e.origin,t.originPoint=e.originPoint}function zne(t,e,r,n){t.min=Pa(e.min,r.min,n),t.max=Pa(e.max,r.max,n)}function xtt(t,e,r,n){zne(t.x,e.x,r.x,n),zne(t.y,e.y,r.y,n)}function _tt(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const vtt={duration:.45,ease:[.4,0,.1,1]},$ne=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Une=$ne("applewebkit/")&&!$ne("chrome/")?Math.round:rh;function Vne(t){t.min=Une(t.min),t.max=Une(t.max)}function btt(t){Vne(t.x),Vne(t.y)}function Qbe(t,e,r){return t==="position"||t==="preserve-aspect"&&!Uet(Nne(e),Nne(r),.2)}function wtt(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Stt=Xbe({attachResizeListener:(t,e)=>Kj(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}),Uz={current:void 0},Jbe=Xbe({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Uz.current){const t=new Stt({});t.mount(window),t.setOptions({layoutScroll:!0}),Uz.current=t}return Uz.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),wH=I.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function qne(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Ttt(...t){return e=>{let r=!1;const n=t.map(i=>{const o=qne(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{width:E,height:k,top:P,left:R,right:D,bottom:M}=f.current;if(e||o===!1||!s.current||!E||!k)return;const B=r==="left"?`left: ${R}`:`right: ${D}`,V=n==="bottom"?`bottom: ${M}`:`top: ${P}`;s.current.dataset.motionPopId=c;const G=document.createElement("style");p&&(G.nonce=p);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: ${k}px !important; ${B}px !important; ${V}px !important; } `),()=>{var Z;(Z=s.current)==null||Z.removeAttribute("data-motion-pop-id"),W.contains(G)&&W.removeChild(G)}},[e]),a.jsx(Att,{isPresent:e,childRef:s,sizeRef:f,pop:o,children:o===!1?t:I.cloneElement(t,{ref:_})})}const ktt=({children:t,initial:e,isPresent:r,onExitComplete:n,custom:i,presenceAffectsLayout:o,mode:c,anchorX:s,anchorY:f,root:p})=>{const y=Q7(Ctt),_=I.useId();let T=!0,E=I.useMemo(()=>(T=!1,{id:_,initial:e,isPresent:r,custom:i,onExitComplete:k=>{y.set(k,!0);for(const P of y.values())if(!P)return;n&&n()},register:k=>(y.set(k,!1),()=>y.delete(k))}),[r,y,n]);return o&&T&&(E={...E}),I.useMemo(()=>{y.forEach((k,P)=>y.set(P,!1))},[r]),I.useEffect(()=>{!r&&!y.size&&n&&n()},[r]),t=a.jsx(jtt,{pop:c==="popLayout",isPresent:r,anchorX:s,anchorY:f,root:p,children:t}),a.jsx(B3.Provider,{value:E,children:t})};function Ctt(){return new Map}function ewe(t=!0){const e=I.useContext(B3);if(e===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:i}=e,o=I.useId();I.useEffect(()=>{if(t)return i(o)},[t]);const c=I.useCallback(()=>t&&n&&n(o),[o,n,t]);return!r&&n?[!1,c]:[!0]}const XP=t=>t.key||"";function Gne(t){const e=[];return I.Children.forEach(t,r=>{I.isValidElement(r)&&e.push(r)}),e}const twe=({children:t,custom:e,initial:r=!0,onExitComplete:n,presenceAffectsLayout:i=!0,mode:o="sync",propagate:c=!1,anchorX:s="left",anchorY:f="top",root:p})=>{const[y,_]=ewe(c),T=I.useMemo(()=>Gne(t),[t]),E=c&&!y?[]:T.map(XP),k=I.useRef(!0),P=I.useRef(T),R=Q7(()=>new Map),D=I.useRef(new Set),[M,B]=I.useState(T),[V,G]=I.useState(T);jve(()=>{k.current=!1,P.current=T;for(let Q=0;Q{const re=XP(Q),se=c&&!y?!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(we=>{we||(_e=!1)}),_e&&(Z==null||Z(),G(P.current),c&&(_==null||_()),n&&n())};return a.jsx(ktt,{isPresent:se,initial:!k.current||r?void 0:!1,custom:e,presenceAffectsLayout:i,mode:o,root:p,onExitComplete:se?void 0:ue,anchorX:s,anchorY:f,children:Q},re)})})},rwe=I.createContext({strict:!1}),Hne={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 Wne=!1;function Itt(){if(Wne)return;const t={};for(const e in Hne)t[e]={isEnabled:r=>Hne[e].some(n=>!!r[n])};Ibe(t),Wne=!0}function nwe(){return Itt(),fet()}function Ntt(t){const e=nwe();for(const r in t)e[r]={...e[r],...t[r]};Ibe(e)}const Ptt=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 YD(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Ptt.has(t)}let iwe=t=>!YD(t);function Rtt(t){typeof t=="function"&&(iwe=e=>e.startsWith("on")?!YD(e):t(e))}try{Rtt(require("@emotion/is-prop-valid").default)}catch{}function Ltt(t,e,r){const n={};for(const i in t)i==="values"&&typeof t.values=="object"||ec(t[i])||(iwe(i)||r===!0&&YD(i)||!e&&!YD(i)||t.draggable&&i.startsWith("onDrag"))&&(n[i]=t[i]);return n}const q3=I.createContext({});function Dtt(t,e){if(V3(t)){const{initial:r,animate:n}=t;return{initial:r===!1||Wj(r)?r:void 0,animate:Wj(n)?n:void 0}}return t.inherit!==!1?e:{}}function Mtt(t){const{initial:e,animate:r}=Dtt(t,I.useContext(q3));return I.useMemo(()=>({initial:e,animate:r}),[Kne(e),Kne(r)])}function Kne(t){return Array.isArray(t)?t.join(" "):t}const SH=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function swe(t,e,r){for(const n in e)!ec(e[n])&&!Obe(n,r)&&(t[n]=e[n])}function Ott({transformTemplate:t},e){return I.useMemo(()=>{const r=SH();return vH(r,e,t),Object.assign({},r.vars,r.style)},[e])}function Ftt(t,e){const r=t.style||{},n={};return swe(n,r,t),Object.assign(n,Ott(t,e)),n}function Btt(t,e){const r={},n=Ftt(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 awe=()=>({...SH(),attrs:{}});function ztt(t,e,r,n){const i=I.useMemo(()=>{const o=awe();return Fbe(o,e,zbe(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};swe(o,t.style,t),i.style={...o,...i.style}}return i}const $tt=["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 TH(t){return typeof t!="string"||t.includes("-")?!1:!!($tt.indexOf(t)>-1||/[A-Z]/u.test(t))}function Utt(t,e,r,{latestValues:n},i,o=!1,c){const f=(c??TH(t)?ztt:Btt)(e,n,i,t),p=Ltt(e,typeof t=="string",o),y=t!==I.Fragment?{...p,...f,ref:r}:{},{children:_}=e,T=I.useMemo(()=>ec(_)?_.get():_,[_]);return I.createElement(t,{...y,children:T})}function Vtt({scrapeMotionValuesFromProps:t,createRenderState:e},r,n,i){return{latestValues:qtt(r,n,i,t),renderState:e()}}function qtt(t,e,r,n){const i={},o=n(t,{});for(const T in o)i[T]=xL(o[T]);let{initial:c,animate:s}=t;const f=V3(t),p=kbe(t);e&&p&&!f&&t.inherit!==!1&&(c===void 0&&(c=e.initial),s===void 0&&(s=e.animate));let y=r?r.initial===!1:!1;y=y||c===!1;const _=y?s:c;if(_&&typeof _!="boolean"&&!U3(_)){const T=Array.isArray(_)?_:[_];for(let E=0;E(e,r)=>{const n=I.useContext(q3),i=I.useContext(B3),o=()=>Vtt(t,e,n,i);return r?o():Q7(o)},Gtt=owe({scrapeMotionValuesFromProps:bH,createRenderState:SH}),Htt=owe({scrapeMotionValuesFromProps:$be,createRenderState:awe}),Wtt=Symbol.for("motionComponentSymbol");function Ktt(t,e,r){const n=I.useRef(r);I.useInsertionEffect(()=>{n.current=r});const i=I.useRef(null);return I.useCallback(o=>{var s;o&&((s=t.onMount)==null||s.call(t,o));const c=n.current;if(typeof c=="function")if(o){const f=c(o);typeof f=="function"&&(i.current=f)}else i.current?(i.current(),i.current=null):c(o);else c&&(c.current=o);e&&(o?e.mount(o):e.unmount())},[e])}const lwe=I.createContext({});function gw(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Ytt(t,e,r,n,i,o){var B,V;const{visualElement:c}=I.useContext(q3),s=I.useContext(rwe),f=I.useContext(B3),p=I.useContext(wH),y=p.reducedMotion,_=p.skipAnimations,T=I.useRef(null),E=I.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:y,skipAnimations:_,isSVG:o}),E.current&&T.current&&(T.current.manuallyAnimateOnMount=!0));const k=T.current,P=I.useContext(lwe);k&&!k.projection&&i&&(k.type==="html"||k.type==="svg")&&Ztt(T.current,r,i,P);const R=I.useRef(!1);I.useInsertionEffect(()=>{k&&R.current&&k.update(r,f)});const D=r[pbe],M=I.useRef(!!D&&typeof window<"u"&&!((B=window.MotionHandoffIsComplete)!=null&&B.call(window,D))&&((V=window.MotionHasOptimisedAnimation)==null?void 0:V.call(window,D)));return jve(()=>{E.current=!0,k&&(R.current=!0,window.MotionIsMounted=!0,k.updateFeatures(),k.scheduleRenderMicrotask(),M.current&&k.animationState&&k.animationState.animateChanges())}),I.useEffect(()=>{k&&(!M.current&&k.animationState&&k.animationState.animateChanges(),M.current&&(queueMicrotask(()=>{var G;(G=window.MotionHandoffMarkAsComplete)==null||G.call(window,D)}),M.current=!1),k.enteringChildren=void 0)}),k}function Ztt(t,e,r,n){const{layoutId:i,layout:o,drag:c,dragConstraints:s,layoutScroll:f,layoutRoot:p,layoutAnchor:y,layoutCrossfade:_}=e;t.projection=new r(t.latestValues,e["data-framer-portal-id"]?void 0:cwe(t.parent)),t.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!c||s&&gw(s),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:_,layoutScroll:f,layoutRoot:p,layoutAnchor:y})}function cwe(t){if(t)return t.options.allowProjection!==!1?t.projection:cwe(t.parent)}function Vz(t,{forwardMotionProps:e=!1,type:r}={},n,i){n&&Ntt(n);const o=r?r==="svg":TH(t),c=o?Htt:Gtt;function s(p,y){let _;const T={...I.useContext(wH),...p,layoutId:Xtt(p)},{isStatic:E}=T,k=Mtt(p),P=c(p,E);if(!E&&typeof window<"u"){Qtt();const R=Jtt(T);_=R.MeasureLayout,k.visualElement=Ytt(t,P,T,i,R.ProjectionNode,o)}return a.jsxs(q3.Provider,{value:k,children:[_&&k.visualElement?a.jsx(_,{visualElement:k.visualElement,...T}):null,Utt(t,p,Ktt(P,k.visualElement,y),P,E,e,o)]})}s.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const f=I.forwardRef(s);return f[Wtt]=t,f}function Xtt({layoutId:t}){const e=I.useContext(X7).id;return e&&t!==void 0?e+"-"+t:t}function Qtt(t,e){I.useContext(rwe).strict}function Jtt(t){const e=nwe(),{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 ert(t,e){if(typeof Proxy>"u")return Vz;const r=new Map,n=(o,c)=>Vz(o,c,t,e),i=(o,c)=>n(o,c);return new Proxy(i,{get:(o,c)=>c==="create"?n:(r.has(c)||r.set(c,Vz(c,void 0,t,e)),r.get(c))})}const trt=(t,e)=>e.isSVG??TH(t)?new Net(e):new Eet(e,{allowProjection:t!==I.Fragment});class rrt extends Sx{constructor(e){super(e),e.animationState||(e.animationState=Met(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();U3(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 nrt=0;class irt extends Sx{constructor(){super(...arguments),this.id=nrt++,this.isExitComplete=!1}update(){var o;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=C_(this.node,c,s);if(f){const{transition:p,transitionEnd:y,..._}=f;for(const T in _)(o=this.node.getValue(T))==null||o.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 srt={animation:{Feature:rrt},exit:{Feature:irt}};function jC(t){return{point:{x:t.pageX,y:t.pageY}}}const art=t=>e=>gH(e)&&t(e,jC(e));function HA(t,e,r,n){return Kj(t,e,art(r),n)}const uwe=({current:t})=>t?t.ownerDocument.defaultView:null,Yne=(t,e)=>Math.abs(t-e);function ort(t,e){const r=Yne(t.x,e.x),n=Yne(t.y,e.y);return Math.sqrt(r**2+n**2)}const Zne=new Set(["auto","scroll"]);class dwe{constructor(e,r,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:o=!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=QP(this.lastRawMoveEventInfo,this.transformPagePoint));const E=qz(this.lastMoveEventInfo,this.history),k=this.startEvent!==null,P=ort(E.offset,{x:0,y:0})>=this.distanceThreshold;if(!k&&!P)return;const{point:R}=E,{timestamp:D}=ql;this.history.push({...R,timestamp:D});const{onStart:M,onMove:B}=this.handlers;k||(M&&M(this.lastMoveEvent,E),this.startEvent=this.lastMoveEvent),B&&B(this.lastMoveEvent,E)},this.handlePointerMove=(E,k)=>{this.lastMoveEvent=E,this.lastRawMoveEventInfo=k,this.lastMoveEventInfo=QP(k,this.transformPagePoint),na.update(this.updatePoint,!0)},this.handlePointerUp=(E,k)=>{this.end();const{onEnd:P,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const M=qz(E.type==="pointercancel"?this.lastMoveEventInfo:QP(k,this.transformPagePoint),this.history);this.startEvent&&P&&P(E,M),R&&R(E,M)},!gH(e))return;this.dragSnapToOrigin=o,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=c,this.contextWindow=i||window;const f=jC(e),p=QP(f,this.transformPagePoint),{point:y}=p,{timestamp:_}=ql;this.history=[{...y,timestamp:_}];const{onSessionStart:T}=r;T&&T(e,qz(p,this.history)),this.removeListeners=TC(HA(this.contextWindow,"pointermove",this.handlePointerMove),HA(this.contextWindow,"pointerup",this.handlePointerUp),HA(this.contextWindow,"pointercancel",this.handlePointerUp)),s&&this.startScrollTracking(s)}startScrollTracking(e){let r=e.parentElement;for(;r;){const n=getComputedStyle(r);(Zne.has(n.overflowX)||Zne.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},o={x:i.x-r.x,y:i.y-r.y};o.x===0&&o.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=o.x,this.lastMoveEventInfo.point.y+=o.y):this.history.length>0&&(this.history[0].x-=o.x,this.history[0].y-=o.y),this.scrollPositions.set(e,i),na.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),sx(this.updatePoint)}}function QP(t,e){return e?{point:e(t.point)}:t}function Xne(t,e){return{x:t.x-e.x,y:t.y-e.y}}function qz({point:t},e){return{point:t,delta:Xne(t,hwe(e)),offset:Xne(t,lrt(e)),velocity:crt(e,.1)}}function lrt(t){return t[0]}function hwe(t){return t[t.length-1]}function crt(t,e){if(t.length<2)return{x:0,y:0};let r=t.length-1,n=null;const i=hwe(t);for(;r>=0&&(n=t[r],!(i.timestamp-n.timestamp>Pu(e)));)r--;if(!n)return{x:0,y:0};n===t[0]&&t.length>2&&i.timestamp-n.timestamp>Pu(e)*2&&(n=t[1]);const o=Xd(i.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const c={x:(i.x-n.x)/o,y:(i.y-n.y)/o};return c.x===1/0&&(c.x=0),c.y===1/0&&(c.y=0),c}function urt(t,{min:e,max:r},n){return e!==void 0&&tr&&(t=n?Pa(r,t,n.max):Math.min(t,r)),t}function Qne(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 drt(t,{top:e,left:r,bottom:n,right:i}){return{x:Qne(t.x,r,i),y:Qne(t.y,e,n)}}function Jne(t,e){let r=e.min-t.min,n=e.max-t.max;return e.max-e.minn?r=Gj(e.min,e.max-n,t.min):n>i&&(r=Gj(t.min,t.max-i,e.min)),mm(0,1,r)}function mrt(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 JV=.35;function prt(t=JV){return t===!1?t=0:t===!0&&(t=JV),{x:eie(t,"left","right"),y:eie(t,"top","bottom")}}function eie(t,e,r){return{min:tie(t,e),max:tie(t,r)}}function tie(t,e){return typeof t=="number"?t:t[e]||0}const grt=new WeakMap;class yrt{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=il(),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 o=_=>{r&&this.snapToCursor(jC(_).point),this.stopAnimation()},c=(_,T)=>{const{drag:E,dragPropagation:k,onDragStart:P}=this.getProps();if(E&&!k&&(this.openDragLock&&this.openDragLock(),this.openDragLock=UJe(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),zf(D=>{let M=this.getAxisMotionValue(D).get()||0;if(am.test(M)){const{projection:B}=this.visualElement;if(B&&B.layout){const V=B.layout.layoutBox[D];V&&(M=Yc(V)*(parseFloat(M)/100))}}this.originPoint[D]=M}),P&&na.update(()=>P(_,T),!1,!0),qV(this.visualElement,"transform");const{animationState:R}=this.visualElement;R&&R.setActive("whileDrag",!0)},s=(_,T)=>{this.latestPointerEvent=_,this.latestPanInfo=T;const{dragPropagation:E,dragDirectionLock:k,onDirectionLock:P,onDrag:R}=this.getProps();if(!E&&!this.openDragLock)return;const{offset:D}=T;if(k&&this.currentDirection===null){this.currentDirection=_rt(D),this.currentDirection!==null&&P&&P(this.currentDirection);return}this.updateAxis("x",T.point,D),this.updateAxis("y",T.point,D),this.visualElement.render(),R&&na.update(()=>R(_,T),!1,!0)},f=(_,T)=>{this.latestPointerEvent=_,this.latestPanInfo=T,this.stop(_,T),this.latestPointerEvent=null,this.latestPanInfo=null},p=()=>{const{dragSnapToOrigin:_}=this.getProps();(_||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:y}=this.getProps();this.panSession=new dwe(e,{onSessionStart:o,onStart:c,onMove:s,onSessionEnd:f,resumeAnimation:p},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:n,contextWindow:uwe(this.visualElement),element:this.visualElement.current})}stop(e,r){const n=e||this.latestPointerEvent,i=r||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!i||!n)return;const{velocity:c}=i;this.startAnimation(c);const{onDragEnd:s}=this.getProps();s&&na.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||!JP(e,i,this.currentDirection))return;const o=this.getAxisMotionValue(e);let c=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(c=urt(c,this.constraints[e],this.elastic[e])),o.set(c)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:r}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,i=this.constraints;e&&gw(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=drt(n.layoutBox,e):this.constraints=!1,this.elastic=prt(r),i!==this.constraints&&!gw(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&zf(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=mrt(n.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:r}=this.getProps();if(!e||!gw(e))return!1;const n=e.current;H1(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 o=xet(n,i.root,this.visualElement.getTransformPagePoint());let c=hrt(i.layout.layoutBox,o);if(r){const s=r(pet(c));this.hasMutatedConstraints=!!s,s&&(c=Pbe(s))}return c}startAnimation(e){const{drag:r,dragMomentum:n,dragElastic:i,dragTransition:o,dragSnapToOrigin:c,onDragTransitionEnd:s}=this.getProps(),f=this.constraints||{},p=zf(y=>{if(!JP(y,r,this.currentDirection))return;let _=f&&f[y]||{};(c===!0||c===y)&&(_={min:0,max:0});const T=i?200:1e6,E=i?40:1e7,k={type:"inertia",velocity:n?e[y]:0,bounceStiffness:T,bounceDamping:E,timeConstant:750,restDelta:1,restSpeed:10,...o,..._};return this.startAxisValueAnimation(y,k)});return Promise.all(p).then(s)}startAxisValueAnimation(e,r){const n=this.getAxisMotionValue(e);return qV(this.visualElement,e),n.start(dH(e,n,0,r,this.visualElement,!1))}stopAnimation(){zf(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){zf(r=>{const{drag:n}=this.getProps();if(!JP(r,n,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(r);if(i&&i.layout){const{min:c,max:s}=i.layout.layoutBox[r],f=o.get()||0;o.set(e[r]-Pa(c,s,.5)+f)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!gw(r)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};zf(c=>{const s=this.getAxisMotionValue(c);if(s&&this.constraints!==!1){const f=s.get();i[c]=frt({min:f,max:f},this.constraints[c])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),zf(c=>{if(!JP(c,e,null))return;const s=this.getAxisMotionValue(c),{min:f,max:p}=this.constraints[c];s.set(Pa(f,p,i[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;grt.set(this.visualElement,this);const e=this.visualElement.current,r=HA(e,"pointerdown",p=>{const{drag:y,dragListener:_=!0}=this.getProps(),T=p.target,E=T!==e&&KJe(T);y&&_&&!E&&this.start(p)});let n;const i=()=>{const{dragConstraints:p}=this.getProps();gw(p)&&p.current&&(this.constraints=this.resolveRefConstraints(),n||(n=xrt(e,p.current,()=>this.scalePositionWithinConstraints())))},{projection:o}=this.visualElement,c=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),na.read(i);const s=Kj(window,"resize",()=>this.scalePositionWithinConstraints()),f=o.addEventListener("didUpdate",({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(zf(_=>{const T=this.getAxisMotionValue(_);T&&(this.originPoint[_]+=p[_].translate,T.set(T.get()+p[_].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:o=!1,dragElastic:c=JV,dragMomentum:s=!0}=e;return{...e,drag:r,dragDirectionLock:n,dragPropagation:i,dragConstraints:o,dragElastic:c,dragMomentum:s}}}function rie(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function xrt(t,e,r){const n=cne(t,rie(r)),i=cne(e,rie(r));return()=>{n(),i()}}function JP(t,e,r){return(e===!0||e===t)&&(r===null||r===t)}function _rt(t,e=10){let r=null;return Math.abs(t.y)>e?r="y":Math.abs(t.x)>e&&(r="x"),r}class vrt extends Sx{constructor(e){super(e),this.removeGroupControls=rh,this.removeListeners=rh,this.controls=new yrt(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||rh}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 Gz=t=>(e,r)=>{t&&na.update(()=>t(e,r),!1,!0)};class brt extends Sx{constructor(){super(...arguments),this.removePointerDownListener=rh}onPointerDown(e){this.session=new dwe(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:uwe(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:r,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:Gz(e),onStart:Gz(r),onMove:Gz(n),onEnd:(o,c)=>{delete this.session,i&&na.postRender(()=>i(o,c))}}}mount(){this.removePointerDownListener=HA(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 Hz=!1;class wrt extends I.Component{componentDidMount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n,layoutId:i}=this.props,{projection:o}=e;o&&(r.group&&r.group.add(o),n&&n.register&&i&&n.register(o),Hz&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),_L.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:r,visualElement:n,drag:i,isPresent:o}=this.props,{projection:c}=n;return c&&(c.isPresent=o,e.layoutDependency!==r&&c.setOptions({...c.options,layoutDependency:r}),Hz=!0,i||e.layoutDependency!==r||r===void 0||e.isPresent!==o?c.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?c.promote():c.relegate()||na.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(),pH.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:i}=e;Hz=!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 fwe(t){const[e,r]=ewe(),n=I.useContext(X7);return a.jsx(wrt,{...t,layoutGroup:n,switchLayoutGroup:I.useContext(lwe),isPresent:e,safeToRemove:r})}const Srt={pan:{Feature:brt},drag:{Feature:vrt,ProjectionNode:Jbe,MeasureLayout:fwe}};function nie(t,e,r){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",r==="Start");const i="onHover"+r,o=n[i];o&&na.postRender(()=>o(e,jC(e)))}class Trt extends Sx{mount(){const{current:e}=this.node;e&&(this.unmount=qJe(e,(r,n)=>(nie(this.node,n,"Start"),i=>nie(this.node,i,"End"))))}unmount(){}}class Ert extends Sx{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=TC(Kj(this.node.current,"focus",()=>this.onFocus()),Kj(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function iie(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),o=n[i];o&&na.postRender(()=>o(e,jC(e)))}class Art extends Sx{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=ZJe(e,(i,o)=>(iie(this.node,o,"Start"),(c,{success:s})=>iie(this.node,c,s?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const e8=new WeakMap,Wz=new WeakMap,jrt=t=>{const e=e8.get(t.target);e&&e(t)},krt=t=>{t.forEach(jrt)};function Crt({root:t,...e}){const r=t||document;Wz.has(r)||Wz.set(r,{});const n=Wz.get(r),i=JSON.stringify(e);return n[i]||(n[i]=new IntersectionObserver(krt,{root:t,...e})),n[i]}function Irt(t,e,r){const n=Crt(e);return e8.set(t,r),n.observe(t),()=>{e8.delete(t),n.unobserve(t)}}const Nrt={some:0,all:1};class Prt extends Sx{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:o}=e,c={root:r?r.current:void 0,rootMargin:n,threshold:typeof i=="number"?i:Nrt[i]},s=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,o&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",y);const{onViewportEnter:_,onViewportLeave:T}=this.node.getProps(),E=y?_:T;E&&E(p)};this.stopObserver=Irt(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(Rrt(e,r))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Rrt({viewport:t={}},{viewport:e={}}={}){return r=>t[r]!==e[r]}const Lrt={inView:{Feature:Prt},tap:{Feature:Art},focus:{Feature:Ert},hover:{Feature:Trt}},Drt={layout:{ProjectionNode:Jbe,MeasureLayout:fwe}},Mrt={...srt,...Lrt,...Srt,...Drt},fr=ert(Mrt,trt);function Ort(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 sie(t){return t.visitor_intent==="buying"&&!t.has_agent}function Frt({token:t}={}){var E;const e=bm(),r=t||e.token,{data:n,isLoading:i,isError:o}=MXe(r);Nr();const c=(E=n==null?void 0:n.open_houses)==null?void 0:E.id,{data:s}=gr({queryKey:["cohost-visitors",r,c],queryFn:async()=>{const{data:k,error:P}=await Re.rpc("get_cohost_visitors",{_token:r});if(P)throw P;return k||[]},enabled:!!r&&!!c,refetchInterval:15e3});if(i)return a.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:a.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(o||!n)return a.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:a.jsxs("div",{className:"text-center text-white",children:[a.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),a.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,p=(s==null?void 0:s.length)||0,y=(s==null?void 0:s.filter(k=>k.visitor_intent==="buying").length)||0,_=(s==null?void 0:s.filter(sie).length)||0,T=k=>{if(!k)return"";const[P,R]=k.split(":"),D=parseInt(P);return`${D>12?D-12:D||12}:${R} ${D>=12?"PM":"AM"}`};return a.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[a.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:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),a.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),a.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:f.property_address})]}),a.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(ul,{className:"h-4 w-4"}),a.jsx("span",{className:"font-bold text-white",children:p})]}),a.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[a.jsx(Lfe,{className:"h-4 w-4"}),a.jsx("span",{className:"font-bold text-white",children:_})]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(La,{className:"h-4 w-4"}),a.jsx("span",{className:"font-bold text-white",children:y})]})]})]}),a.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:[a.jsx("span",{children:Ni(new Date(f.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),f.start_time&&a.jsxs("span",{children:[T(f.start_time),f.end_time?` – ${T(f.end_time)}`:""]})]}),a.jsx(Sm,{className:"flex-1 p-4 sm:p-6",children:s!=null&&s.length?a.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:a.jsx(twe,{children:s.map((k,P)=>{var M;const R=Ort(k.visitor_intent),D=sie(k);return a.jsxs(fr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:P*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${D?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[a.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=k.first_name[0])==null?void 0:M.toUpperCase()}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("span",{className:"font-semibold text-white truncate",children:[k.first_name," ",k.last_name||""]}),D&&a.jsx(us,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),k.has_agent&&a.jsx(us,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[a.jsxs(us,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${R.color}`,children:[R.emoji," ",R.label]}),a.jsx("span",{className:"text-white/30 text-xs",children:Ni(new Date(k.created_at),"h:mm a")})]})]})]},k.id)})})}):a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[a.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:a.jsx(zfe,{className:"h-10 w-10 text-white/20"})}),a.jsx("h2",{className:"text-xl font-bold text-white/60 mb-1",children:"Waiting for visitors..."}),a.jsx("p",{className:"text-white/30 text-sm",children:"New sign-ins will appear here in real-time"})]})})]})}function Brt(){const e=Bi().pathname.slice(1);if(I.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),e.startsWith("live/")){const r=e.slice(5);if(r)return a.jsx(Frt,{token:r})}if(e.startsWith("rsvp/")){const r=e.slice(5);if(r)return a.jsx(Ave,{slug:r})}return!e||e===""?a.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:a.jsxs("div",{className:"text-center text-white",children:[a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),a.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),a.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):a.jsx(Eve,{slug:e})}function zrt({dealData:t,agentProfile:e,welcomeMessage:r,isWon:n,branding:i}){var p;const o=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 a.jsxs("div",{className:"relative overflow-hidden",children:[a.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[s&&a.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${s})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),a.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%))"}}),a.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"}}),a.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&a.jsx(fr.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:a.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:a.jsx("img",{src:c,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),e&&a.jsxs(fr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[e.avatar_url?a.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:a.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:a.jsx("img",{src:e.avatar_url,alt:e.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):a.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:((p=e.name)==null?void 0:p.charAt(0))||"?"}),a.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:e.name}),a.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:f})]}),a.jsxs(fr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[a.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:[a.jsx(La,{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&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),a.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"}),a.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),o&&a.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[a.jsx(qs,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),a.jsx("span",{children:o})]}),r&&a.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&&a.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:a.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:a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.phone&&a.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:[a.jsx(ai,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),e.email&&a.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:[a.jsx(Ti,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),e.phone&&a.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:[a.jsx(R1,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function mwe({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=L7e(i,new Date);if(V1(i)&&!th(i))return null;const s=th(i),f=s?"0":String(Math.max(0,c)),p=Math.max(4,Math.min(100,(60-Math.min(60,c))/60*100));return a.jsxs("div",{className:"portal-tile p-8 text-center",children:[a.jsx("p",{className:"portal-eyebrow mb-4",children:s?"The Moment Has Arrived":"Countdown to Closing"}),s?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),a.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","."]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[a.jsx(fr.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}),a.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:c===1?"day":"days"})]}),a.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),a.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),a.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:a.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:a.jsx(fr.div,{initial:{width:0},animate:{width:`${p}%`},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 pwe({journeyStages:t,currentIndex:e}){return t.length===0?null:a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),a.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),a.jsx("div",{className:"relative",children:t.map((r,n)=>{const i=ne;return a.jsxs(fr.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(o.includes("youtube.com/watch")){const f=new URL(o).searchParams.get("v");return f?`https://www.youtube.com/embed/${f}`:null}if(o.includes("youtu.be/")){const f=(c=o.split("youtu.be/")[1])==null?void 0:c.split("?")[0];return f?`https://www.youtube.com/embed/${f}`:null}if(o.includes("loom.com/share/")){const f=(s=o.split("loom.com/share/")[1])==null?void 0:s.split("?")[0];return f?`https://www.loom.com/embed/${f}`:null}return o};return a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),a.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:t.label}),a.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:t.description}),e&&a.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:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),a.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",e,"”"]})]}),r&&a.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:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),a.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:r})]}),n&&a.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:a.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 Y1(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 Bqt(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,o,c;if(r[0].length===4)[c,i,o]=n,i=i-1;else if([i,o,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,o);if(!(s.getFullYear()!==c||s.getMonth()!==i||s.getDate()!==o))return s}const $rt=[{key:"contract_date",label:"Contract Accepted",icon:hU},{key:"earnest_money_due_date",label:"Earnest Money",icon:jp},{key:"inspection_date",label:"Inspection",icon:hd},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:cm},{key:"appraisal_date",label:"Appraisal",icon:La},{key:"loan_approval_date",label:"Loan Approval",icon:IO},{key:"title_docs_due_date",label:"Title & Disclosures",icon:cm},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:tDe},{key:"target_close_date",label:"Target Close",icon:yo}];function Urt(t,e){const r=Ni(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 Vrt(t,e){const r=Ni(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 ywe({deal:t,portal:e,targetCloseDate:r,contractDate:n,inspectionDate:i,appraisalDate:o,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)??o??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,p=Array.isArray(t==null?void 0:t.completed_key_dates)?t.completed_key_dates:[],y=$rt.map(E=>E.key==="target_close_date"&&f?{...E,label:"Closed",date:f,done:!0}:{...E,date:s[E.key],done:p.includes(E.key)}).filter(E=>!!E.date);if(y.length===0)return null;const _=(E,k,P)=>{const R=Y1(k);if(P==="google")window.open(Urt(E,R),"_blank");else{const D=Vrt(E,R),M=document.createElement("a");M.href=D,M.download=`${E.replace(/\s+/g,"-").toLowerCase()}.ics`,M.click()}},T=y.filter(E=>E.done).length;return a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),a.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[a.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),a.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[T," of ",y.length," complete"]})]}),a.jsxs("div",{className:"space-y-4 relative",children:[a.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),y.map(({label:E,date:k,done:P,icon:R})=>{const D=Y1(k),M=V1(D)&&!th(D),B=th(D),V=!M&&!B,G=P?"Completed":B?"Today":M?"In progress":"Upcoming";return a.jsxs("div",{className:"flex items-start gap-3 relative",children:[a.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:P?"hsl(var(--portal-gold))":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:P?a.jsx(ko,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):a.jsx(R,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:E}),a.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:P?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Ni(D,"MMM d, yyyy")}),a.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:P||B?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${P||B?.5:.18})`},children:G})]}),V&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx("button",{onClick:()=>_(E,k,"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:a.jsx(Nfe,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>_(E,k,"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 xwe({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 Re.storage.from("deal-files").createSignedUrl(n.storage_path,300);i!=null&&i.signedUrl&&window.open(i.signedUrl,"_blank")};return a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),a.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),a.jsx("div",{className:"space-y-2",children:t.map(n=>a.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:[a.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:a.jsx(cm,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n.file_name}),a.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:e(n.file_size)})]}),a.jsx(rc,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},n.id))})]})}function _we({slug:t,wrapper:e}){const r=Gs(),[n,i]=I.useState(null),{data:o=[]}=gr({queryKey:["portal-signature-requests",t],enabled:!!t,queryFn:async()=>{const{data:y,error:_}=await Re.functions.invoke("forms-portal-public",{body:{action:"list",slug:t}});return _?[]:(y==null?void 0:y.envelopes)||[]}}),c=o.filter(y=>y.my_turn),s=o.filter(y=>!y.my_turn&&y.status!=="completed");if(!c.length&&!s.length)return null;const f=async y=>{i(y);try{const{data:_,error:T}=await Re.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:t,envelope_id:y}});if(T||_!=null&&_.error)throw new Error((_==null?void 0:_.error)||"Could not open the document");r(_.path)}catch(_){Gt.error((_==null?void 0:_.message)||"Could not open the document")}finally{i(null)}},p=a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),a.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),a.jsxs("div",{className:"space-y-2",children:[c.map(y=>a.jsxs("button",{onClick:()=>f(y.id),disabled:n===y.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:[a.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===y.id?a.jsx(Ru,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):a.jsx(hDe,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:y.title}),a.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},y.id)),s.map(y=>a.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:[a.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:y.my_status==="signed"?a.jsx(ic,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):a.jsx(Rl,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:y.title}),a.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:y.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},y.id))]})]});return e?e(p):p}function vwe({updates:t}){const e=r=>{var n,i;if(r.includes("youtube.com/watch")){const o=new URL(r).searchParams.get("v");return o?`https://www.youtube.com/embed/${o}`:null}if(r.includes("youtu.be/")){const o=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return o?`https://www.youtube.com/embed/${o}`:null}if(r.includes("loom.com/share/")){const o=(i=r.split("loom.com/share/")[1])==null?void 0:i.split("?")[0];return o?`https://www.loom.com/embed/${o}`:null}return r};return a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),a.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),a.jsx("div",{className:"space-y-6",children:t.map((r,n)=>a.jsx("div",{className:n>0?"pt-6":"",style:n>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.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?a.jsx(ULe,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):a.jsx(Qk,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[a.jsx("h3",{className:"portal-serif",style:{fontSize:n===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:r.title}),a.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ni(new Date(r.created_at),"MMM d")})]}),r.content&&a.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&&a.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:a.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 qrt=[{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 aie(t){var r,n;const e=(r=t.custom_category)==null?void 0:r.trim();return e||((n=qrt.find(i=>i.value===t.category))==null?void 0:n.label)||t.category}function oie(t){var r;const e=(r=t.custom_category)==null?void 0:r.trim();return e?`custom:${e.toLowerCase()}`:t.category}const zqt=[{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 $qt(t){return gr({queryKey:["vendors","brokerage",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.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 Uqt(){const t=Gi(),{brokerageId:e}=Gn();return gr({queryKey:["vendors","library",t,e],queryFn:async()=>{if(!t)return{vendors:[],selections:[]};let r=Re.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:o,error:c}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Re.from("agent_vendor_selections").select("*").eq("agent_user_id",t)]);if(i)throw i;if(c)throw c;return{vendors:n||[],selections:o||[]}},enabled:!!t})}function Vqt(){const t=Nr();return kr({mutationFn:async e=>{if(e.id){const{id:r,created_at:n,...i}=e,{data:o,error:c}=await Re.from("vendors").update(i).eq("id",r).select().single();if(c)throw c;return o}else{const{data:r,error:n}=await Re.from("vendors").insert(e).select().single();if(n)throw n;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function qqt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("vendors").delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function Gqt(){const t=Gi(),e=Nr();return kr({mutationFn:async({vendorId:r,isVisible:n})=>{if(!t)throw new Error("No user");const{data:i}=await Re.from("agent_vendor_selections").select("id").eq("agent_user_id",t).eq("vendor_id",r).maybeSingle();if(i){const{error:o}=await Re.from("agent_vendor_selections").update({is_visible:n}).eq("id",i.id);if(o)throw o}else{const{error:o}=await Re.from("agent_vendor_selections").insert({agent_user_id:t,vendor_id:r,is_visible:n});if(o)throw o}},onSuccess:()=>e.invalidateQueries({queryKey:["vendors"]})})}function bwe(t){return gr({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 Re.from("profiles").select("brokerage_id").eq("id",e).maybeSingle(),n=r==null?void 0:r.brokerage_id,i=Re.from("vendors").select("*").eq("is_active",!0),o=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:p}]=await Promise.all([o.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Re.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",e),Re.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",t.id)]);if(s)throw s;const y=new Map;(f||[]).forEach(E=>y.set(E.vendor_id,{display_order:E.display_order,is_visible:E.is_visible}));const _=new Map;return(p||[]).forEach(E=>_.set(E.vendor_id,E.is_visible)),(c||[]).filter(E=>{if(_.get(E.id)===!1)return!1;const k=y.get(E.id);return!(k&&k.is_visible===!1&&!E.is_required)}).map(E=>{var k;return{...E,display_order:((k=y.get(E.id))==null?void 0:k.display_order)??E.sort_order??0}}).sort((E,k)=>(E.display_order||0)-(k.display_order||0))},enabled:!!(t!=null&&t.id)&&!!(t!=null&&t.owner_user_id)})}async function lie(t){try{await Re.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 Hqt(t,e){return gr({queryKey:["vendor-clicks",t,e],queryFn:async()=>{if(!e)return{};const{data:r}=await Re.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 Re.from("vendor_clicks").select("vendor_id").in("vendor_id",n),o={};return(i||[]).forEach(c=>{o[c.vendor_id]=(o[c.vendor_id]||0)+1}),o},enabled:!!e})}function wwe({portalId:t,ownerUserId:e,currentStage:r,brandingColor:n,layout:i="list"}){const{data:o=[],isLoading:c}=bwe({id:t,owner_user_id:e});if(c||o.length===0)return null;const s=o.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",p=(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}},y=D=>{const M=p(D,D.action_type);lie({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=p(D,D.action_type);return[{action:"website",label:"Website",icon:a.jsx(P1,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:a.jsx(Ti,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:a.jsx(ai,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:a.jsx(yo,{className:"w-3.5 h-3.5"})}].filter(V=>V.action!==D.action_type).map(V=>{const G=p(D,V.action);return!G||G===M?null:a.jsxs("button",{onClick:()=>{lie({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,a.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 a.jsx(yo,{className:"w-3.5 h-3.5"});case"call":return a.jsx(ai,{className:"w-3.5 h-3.5"});case"email":case"quote":return a.jsx(Ti,{className:"w-3.5 h-3.5"});case"website":return a.jsx(P1,{className:"w-3.5 h-3.5"})}},k=a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${f}15`,color:f},children:a.jsx(xs,{className:"w-4 h-4"})}),a.jsxs("div",{children:[a.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),a.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),P=s.some(D=>D.disclosure_text)&&a.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:s.filter(D=>D.disclosure_text).map(D=>a.jsxs("p",{className:"text-[10px] text-slate-400",children:[a.jsxs("span",{className:"font-medium",children:[D.company||D.name,":"]})," ",D.disclosure_text]},D.id))});if(i==="grid")return a.jsxs(Wn,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[k,a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:s.map(D=>a.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:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.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?a.jsx("img",{src:D.logo_url,alt:D.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-base font-semibold text-slate-500",children:(D.company||D.name).charAt(0)})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:D.company||D.name}),D.company&&D.name&&a.jsx("p",{className:"text-xs text-slate-500 truncate",children:D.name}),a.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:aie(D)})]})]}),D.description&&a.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:D.description}),a.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[a.jsxs(zt,{size:"sm",onClick:()=>y(D),style:{backgroundColor:f},className:"text-white hover:opacity-90 w-full",children:[E(D),a.jsx("span",{className:"ml-1.5 text-xs",children:T(D)})]}),_(D).length>0&&a.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:_(D)})]})]},D.id))}),P]});const R=s.reduce((D,M)=>((D[oie(M)]=D[oie(M)]||[]).push(M),D),{});return a.jsxs(Wn,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[k,a.jsx("div",{className:"space-y-4",children:Object.entries(R).map(([D,M])=>a.jsxs("div",{children:[a.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:aie(M[0])}),a.jsx("div",{className:"space-y-2",children:M.map(B=>a.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[a.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?a.jsx("img",{src:B.logo_url,alt:B.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-sm font-semibold text-slate-500",children:B.name.charAt(0)})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:B.company||B.name}),B.company&&B.name&&a.jsx("p",{className:"text-xs text-slate-500 truncate",children:B.name}),B.description&&a.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:B.description})]}),a.jsxs(zt,{size:"sm",onClick:()=>y(B),style:{backgroundColor:f},className:"text-white hover:opacity-90 shrink-0",children:[E(B),a.jsx("span",{className:"ml-1.5 text-xs",children:T(B)})]})]},B.id))})]},D))}),P]})}function Grt(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 Hrt(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 Swe({portalId:t,portalSlug:e,ownerUserId:r,rewardText:n,ctaHeadline:i,agentName:o,clientName:c,reviewUrl:s,hubVideoUrl:f}){const[p,y]=I.useState(!1),_=I.useRef(!1),T=Grt(e);I.useEffect(()=>{_.current||(_.current=!0,Re.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 Re.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:W,user_agent:navigator.userAgent.slice(0,500)})},k=()=>`${c?`Hey, it's ${c}!`:"Hey!"} I just had an amazing experience working with ${o||"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}`,P=async()=>{await navigator.clipboard.writeText(T),y(!0),E("copy_link"),setTimeout(()=>y(!1),2e3)},R=()=>{E("share_sms");const W=encodeURIComponent(k());window.location.href=`sms:?&body=${W}`},D=()=>{E("share_email");const W=encodeURIComponent("A referral you'll thank me for"),Z=encodeURIComponent(k());window.location.href=`mailto:?subject=${W}&body=${Z}`},M=()=>{E("open_form"),window.open(T,"_blank")},B=i||"Know someone buying or selling?",V=f?Hrt(f):null,G=V==null?void 0:V.match(/\.(mp4|webm|mov)(\?|$)/i);return a.jsxs("div",{className:"space-y-4",children:[a.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:[a.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),a.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",c?`, ${c.split(" ")[0]}`:"","!"]}),a.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&&a.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[a.jsx("div",{className:"px-4 pt-4 pb-2",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xs,{className:"w-4 h-4 text-[#406E71]"}),a.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",o||"your agent"]})]})}),a.jsx("div",{className:"aspect-video bg-slate-900",children:G?a.jsx("video",{src:V,controls:!0,className:"w-full h-full",playsInline:!0}):a.jsx("iframe",{src:V,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),a.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[a.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),a.jsxs("div",{className:"relative p-6",children:[a.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:[a.jsx(rf,{className:"w-3 h-3"}),"Referral Program"]}),a.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:B}),n&&a.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[a.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),a.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",o||"us"," is sending a friend or family member."]}),a.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",a.jsx(ra,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[a.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:[a.jsx(R1,{className:"w-3.5 h-3.5"}),"Text"]}),a.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:[a.jsx(Ti,{className:"w-3.5 h-3.5"}),"Email"]}),a.jsxs("button",{onClick:P,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[p?a.jsx(ko,{className:"w-3.5 h-3.5"}):a.jsx(fU,{className:"w-3.5 h-3.5"}),p?"Copied":"Copy"]})]})]})]}),s&&a.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:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"text-2xl",children:"⭐"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),a.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),a.jsx(ra,{className:"w-4 h-4 text-slate-400"})]})})]})}function Wrt(t){return gr({queryKey:["portal-messages",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("portal_messages").select("*").eq("portal_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t,refetchInterval:3e4})}function Krt(){const t=Nr();return kr({mutationFn:async({portalId:e,senderType:r,senderName:n,body:i,deviceFingerprint:o,portalUrl:c})=>{const{data:s,error:f}=await Re.from("portal_messages").insert({portal_id:e,sender_type:r,sender_name:n||null,body:i.trim(),device_fingerprint:o||null,...r==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(f)throw f;try{await Re.functions.invoke("portal-message-notify",{body:{message_id:s.id,portal_url:c}})}catch(p){console.error("portal-message-notify failed",p)}return s},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r.portalId]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function Wqt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.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 Kqt(){const t=Gi();return gr({queryKey:["portal-conversations",t],queryFn:async()=>{const{data:e,error:r}=await Re.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=[],o=100,c=1e3;for(let f=0;f{const p=s.get(f.id)||[];return{portalId:f.id,slug:f.slug,clientName:f.client_name,clientEmail:f.client_email,lastMessage:p.length?p[p.length-1]:null,unreadCount:p.filter(y=>y.sender_type==="client"&&!y.read_at).length,messageCount:p.length}}).sort((f,p)=>{var T,E;const y=((T=f.lastMessage)==null?void 0:T.created_at)||"",_=((E=p.lastMessage)==null?void 0:E.created_at)||"";return y===_?(f.clientName||"").localeCompare(p.clientName||""):_.localeCompare(y)})},enabled:!!t,refetchInterval:3e4})}function Twe({portalId:t,clientName:e,agentName:r,agentAvatar:n,deviceFingerprint:i}){const{data:o,isLoading:c}=Wrt(t),s=Krt(),[f,p]=I.useState(""),y=`portal_msg_name_${t}`,[_,T]=I.useState(()=>localStorage.getItem(y)||e||""),E=I.useRef(null);I.useEffect(()=>{var R;(R=E.current)==null||R.scrollIntoView({block:"nearest"})},[o==null?void 0:o.length]);const k=async()=>{const R=f.trim();if(!R)return;const D=(_||e||"").trim();if(!D){Gt.error("Please add your name first");return}try{localStorage.setItem(y,D),await s.mutateAsync({portalId:t,senderType:"client",senderName:D,body:R,deviceFingerprint:i,portalUrl:window.location.href}),p(""),Gt.success("Message sent")}catch(M){Gt.error((M==null?void 0:M.message)||"Could not send your message")}},P="hsl(var(--portal-gold))";return a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx(of,{className:"w-4 h-4",style:{color:P}}),a.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),a.jsx("div",{className:"portal-hairline mb-4"}),a.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[c&&a.jsx("div",{className:"flex justify-center py-6",children:a.jsx(Ru,{className:"w-4 h-4 animate-spin",style:{color:P}})}),!c&&(!o||o.length===0)&&a.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."]}),o==null?void 0:o.map(R=>{const D=R.sender_type==="agent";return a.jsx("div",{className:`flex ${D?"justify-start":"justify-end"}`,children:a.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:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D&&n&&a.jsx("img",{src:n,alt:r||"Agent",className:"w-5 h-5 rounded-full object-cover"}),a.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"," ·"," ",Ni(new Date(R.created_at),"MMM d, h:mm a")]})]}),a.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:R.body})]})},R.id)}),a.jsx("div",{ref:E})]}),a.jsxs("div",{className:"mt-4 space-y-2",children:[!e&&a.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))"}}),a.jsx("textarea",{value:f,onChange:R=>p(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))"}}),a.jsxs("button",{onClick:k,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:P},children:[s.isPending?a.jsx(Ru,{className:"w-4 h-4 animate-spin"}):a.jsx(lD,{className:"w-4 h-4"}),"Send message"]})]})]})}function Yrt(t){return t==="buy-side"?"Home Search in Progress":t==="listing"?"Your Home Is On The Market":"Active Phase"}function Zrt(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 Xrt={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. 🎉"}},Ewe=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Awe(t){return Ewe.map(e=>{if(e==="Active")return{key:"Active",label:Yrt(t),description:Zrt(t)};const r=Xrt[e];return{key:e,label:r.label,description:r.description}})}function ZD(t){if(!t)return 0;const e=Ewe.indexOf(t);return e>=0?e:0}function Qrt({portal:t,linkedPortal:e,activePortal:r,activeTab:n,onTabChange:i,agentProfile:o,branding:c,updates:s,documents:f}){var Me,Ae,be;const p=(c==null?void 0:c.cover_photo_url)||null,y=(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,k=E==null?void 0:E.is_won_stage,P=T==null?void 0:T.deal_type,R=r==null?void 0:r.stage_mapping;let D=Awe(P);R&&R.length>0&&(D=R.map((me,Pe)=>{var Ie,Se;return{key:`custom-${Pe}`,label:me.label||((Ie=D[Pe])==null?void 0:Ie.label)||`Stage ${Pe+1}`,description:me.description||((Se=D[Pe])==null?void 0:Se.description)||"",video_url:me.video_url||void 0}}));const M=R&&R.length>0?Math.min(ZD(E==null?void 0:E.name),D.length-1):ZD(E==null?void 0:E.name),B=D[M],V=B==null?void 0:B.video_url,G=k&&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,Z=!!e,Q=(Me=t==null?void 0:t.deal_pipeline)==null?void 0:Me.deal_type,re=(Ae=e==null?void 0:e.deal_pipeline)==null?void 0:Ae.deal_type,se=me=>me==="listing"?"Your Sale":me==="buy-side"?"Your Purchase":"Transaction",ue=D.length>1?Math.round((M+1)/D.length*100):0,{data:_e=[]}=bwe({id:r==null?void 0:r.id,owner_user_id:r==null?void 0:r.owner_user_id}),we=_e.some(me=>!me.stage_filter||me.stage_filter.length===0||!(E!=null&&E.name)?!0:me.stage_filter.includes(E.name)),Ce=()=>{var me;(me=document.getElementById("trusted-vendors"))==null||me.scrollIntoView({behavior:"smooth",block:"start"})};return a.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[a.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%)"}}),a.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[a.jsxs(fr.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[y?a.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:a.jsx("img",{src:y,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):a.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:"✦"}),a.jsxs("div",{children:[a.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[a.jsx(Tj,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),a.jsxs(fr.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:[p?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${p})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),a.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):a.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),a.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)"}}),a.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[a.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[a.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:[a.jsx(La,{className:"w-3 h-3"}),P==="listing"?"Sale":P==="buy-side"?"Purchase":"Transaction",k&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),a.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"}),a.jsx("div",{className:"portal-hairline w-32 mb-5"}),W&&a.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[a.jsx(qs,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),a.jsx("span",{className:"text-base",children:W})]}),(r==null?void 0:r.welcome_message)&&a.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,"”"]})]}),a.jsxs("div",{className:"flex flex-col items-center justify-center",children:[a.jsx(Jrt,{pct:ue}),a.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),a.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]})]})]}),a.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),Z&&a.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(me=>{const Pe=me==="primary"?Q:re,Ie=n===me;return a.jsx("button",{onClick:()=>i(me),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(Pe)},me)})}),a.jsxs(fr.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[a.jsx("aside",{className:"col-span-3 space-y-5",children:a.jsxs("div",{className:"sticky top-6 space-y-5",children:[a.jsxs(Df,{children:[a.jsxs("div",{className:"text-center pt-2 pb-1",children:[o!=null&&o.avatar_url?a.jsx("div",{className:"w-24 h-24 mx-auto relative",children:a.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:a.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):a.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:((be=o==null?void 0:o.name)==null?void 0:be.charAt(0))||"?"}),a.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:o==null?void 0:o.name}),a.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),a.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:_})]}),a.jsxs("div",{className:"mt-5 space-y-2",children:[(o==null?void 0:o.phone)&&a.jsx(Kz,{href:`tel:${o.phone}`,icon:ai,label:"Call",sub:o.phone}),(o==null?void 0:o.phone)&&a.jsx(Kz,{href:`sms:${o.phone}`,icon:R1,label:"Text message"}),(o==null?void 0:o.email)&&a.jsx(Kz,{href:`mailto:${o.email}`,icon:Ti,label:"Email",sub:o.email})]})]}),a.jsxs(Df,{children:[a.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),a.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.target_close_date)&&a.jsx(Yz,{icon:yo,label:"Target close",value:cie(T.target_close_date)}),(T==null?void 0:T.contract_date)&&a.jsx(Yz,{icon:Rl,label:"Under contract",value:cie(T.contract_date)}),a.jsx(Yz,{icon:wc,label:"Progress",value:`${ue}%`})]})]})]})}),a.jsxs("main",{className:"col-span-6 space-y-5",children:[G&&a.jsx(Swe,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:o==null?void 0:o.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),a.jsx(mwe,{targetCloseDate:T==null?void 0:T.target_close_date,actualCloseDate:T==null?void 0:T.actual_close_date,clientName:r.client_name}),B&&a.jsx(Df,{children:a.jsx(gwe,{currentStage:B,nextStepText:r.next_step_text,nextStepVideoUrl:V||r.next_step_video_url})}),a.jsx(Df,{children:a.jsx(pwe,{journeyStages:D,currentIndex:M})}),s&&s.length>0&&a.jsx(Df,{children:a.jsx(vwe,{updates:s})}),(r==null?void 0:r.id)&&a.jsx(Df,{children:a.jsx(Twe,{portalId:r.id,clientName:r.client_name,agentName:o==null?void 0:o.name,agentAvatar:o==null?void 0:o.avatar_url})})]}),a.jsxs("aside",{className:"col-span-3 space-y-5",children:[a.jsx(Df,{children:a.jsx(ywe,{deal:T,portal:r})}),(r==null?void 0:r.slug)&&a.jsx(_we,{slug:r.slug,wrapper:me=>a.jsx(Df,{children:me})}),f&&f.length>0&&a.jsx(Df,{children:a.jsx(xwe,{documents:f})}),we&&a.jsx(Df,{children:a.jsxs("button",{onClick:Ce,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:me=>{me.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:me=>{me.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[a.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:a.jsx(Ufe,{className:"w-4 h-4"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),a.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),a.jsx(wc,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),a.jsxs("div",{className:"text-center pt-2 space-y-2",children:[a.jsx("div",{className:"portal-hairline w-12 mx-auto"}),a.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)&&a.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:a.jsx(wwe,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:E==null?void 0:E.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function Df({children:t}){return a.jsx(fr.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 Kz({href:t,icon:e,label:r,sub:n}){return a.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:[a.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:a.jsx(e,{className:"w-4 h-4"})}),a.jsxs("div",{className:"min-w-0 text-left",children:[a.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r}),n&&a.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:n})]})]})}function Yz({icon:t,label:e,value:r}){return a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(t,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:e}),a.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:r})]})]})}function Jrt({pct:t}){const i=2*Math.PI*78,o=i-t/100*i;return a.jsxs("div",{className:"relative",style:{width:170,height:170},children:[a.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[a.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),a.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),a.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),a.jsx(fr.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:o},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:i,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.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}),a.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 cie(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)}var EH="Progress",AH=100,[ent,Yqt]=Yo(EH),[tnt,rnt]=ent(EH),jwe=I.forwardRef((t,e)=>{const{__scopeProgress:r,value:n=null,max:i,getValueLabel:o=nnt,...c}=t;(i||i===0)&&!uie(i)&&console.error(int(`${i}`,"Progress"));const s=uie(i)?i:AH;n!==null&&!die(n,s)&&console.error(snt(`${n}`,"Progress"));const f=die(n,s)?n:null,p=XD(f)?o(f,s):void 0;return a.jsx(tnt,{scope:r,value:f,max:s,children:a.jsx(rn.div,{"aria-valuemax":s,"aria-valuemin":0,"aria-valuenow":XD(f)?f:void 0,"aria-valuetext":p,role:"progressbar","data-state":Iwe(f,s),"data-value":f??void 0,"data-max":s,...c,ref:e})})});jwe.displayName=EH;var kwe="ProgressIndicator",Cwe=I.forwardRef((t,e)=>{const{__scopeProgress:r,...n}=t,i=rnt(kwe,r);return a.jsx(rn.div,{"data-state":Iwe(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...n,ref:e})});Cwe.displayName=kwe;function nnt(t,e){return`${Math.round(t/e*100)}%`}function Iwe(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function XD(t){return typeof t=="number"}function uie(t){return XD(t)&&!isNaN(t)&&t>0}function die(t,e){return XD(t)&&!isNaN(t)&&t<=e&&t>=0}function int(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${AH}\`.`}function snt(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 ${AH} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var Nwe=jwe,ant=Cwe;const WA=I.forwardRef(({className:t,value:e,...r},n)=>a.jsx(Nwe,{ref:n,className:sr("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...r,children:a.jsx(ant,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));WA.displayName=Nwe.displayName;const vA=[{key:"application",label:"Application completed",short:"Application"},{key:"disclosures",label:"Disclosures & docs collected",short:"Docs"},{key:"appraisal_ordered",label:"Appraisal ordered",short:"Appraisal ordered"},{key:"appraisal_value",label:"Appraisal in at value",short:"Appraised"},{key:"conditional_approval",label:"Conditional approval",short:"Approved"},{key:"clear_to_close",label:"Clear to close",short:"Clear to close"}],ont={appraisal_value:"appraisal_date",clear_to_close:"loan_approval_date"};function lnt(t){const e=vA.filter(n=>{var i;return!!((i=t==null?void 0:t[n.key])!=null&&i.done_at)}).length,r=vA.find(n=>{var i;return!((i=t==null?void 0:t[n.key])!=null&&i.done_at)})??null;return{done:e,total:vA.length,pct:Math.round(e/vA.length*100),next:r}}function Zqt(t,e,r,n,i="agent"){return{...t||{},[e]:r?{done_at:n,by:i}:null}}function Xqt(t,e,r){const n=ont[e];return!n||!r||t.includes(n)?t:[...t,n]}const Qqt=["Conventional","FHA","VA","USDA","Jumbo","Cash","Other"],Jqt={sent:"Sent",contacted:"Contacted",application:"Application in",preapproved:"Pre-approved",nurture:"Nurture",closed:"Closed",declined:"Declined",accepted:"Accepted"};function eGt(t,e=typeof window<"u"?window.location.origin:""){return`${e}/lender/${t}`}function cnt({portalId:t}){const{data:e}=gr({queryKey:["portal-lender",t],queryFn:async()=>{const{data:n,error:i}=await Re.rpc("get_portal_lender",{_portal_id:t});if(i)throw i;return n}});if(!e)return null;const r=lnt(e.milestones);return a.jsxs("section",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[e.photo_url?a.jsx("img",{src:e.photo_url,alt:e.name,className:"h-12 w-12 rounded-full object-cover"}):a.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary",children:a.jsx(IO,{className:"h-5 w-5"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Your financing partner"}),a.jsx("p",{className:"font-semibold",children:e.name}),a.jsx("p",{className:"text-xs text-muted-foreground",children:[e.company,e.nmls&&`NMLS ${e.nmls}`,e.loan_type].filter(Boolean).join(" · ")})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex justify-between text-xs",children:[a.jsx("span",{children:"Loan progress"}),a.jsx("span",{children:r.next?`Next: ${r.next.short}`:"Clear to close! 🎉"})]}),a.jsx(WA,{value:r.pct,className:"h-2"}),a.jsx("div",{className:"grid gap-1 sm:grid-cols-2",children:vA.map(n=>{var o,c;const i=!!((c=(o=e.milestones)==null?void 0:o[n.key])!=null&&c.done_at);return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i?a.jsx(ic,{className:"h-4 w-4 text-primary"}):a.jsx(F_,{className:"h-4 w-4 text-muted-foreground"}),a.jsx("span",{className:i?"":"text-muted-foreground",children:n.label})]},n.key)})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.phone&&a.jsx(zt,{asChild:!0,size:"sm",variant:"outline",children:a.jsxs("a",{href:`tel:${e.phone}`,children:[a.jsx(ai,{className:"mr-1.5 h-3.5 w-3.5"}),"Call"]})}),e.email&&a.jsx(zt,{asChild:!0,size:"sm",variant:"outline",children:a.jsxs("a",{href:`mailto:${e.email}`,children:[a.jsx(Ti,{className:"mr-1.5 h-3.5 w-3.5"}),"Email"]})}),e.apply_url&&a.jsx(zt,{asChild:!0,size:"sm",children:a.jsxs("a",{href:e.apply_url,target:"_blank",rel:"noopener noreferrer",children:[a.jsx(iv,{className:"mr-1.5 h-3.5 w-3.5"}),"Loan application"]})})]})]})}function unt({portal:t,dealData:e,agentProfile:r,customQuestions:n,deviceFingerprint:i,onComplete:o}){var R,D;const[c,s]=I.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,p]=I.useState({}),[y,_]=I.useState(!1),T=kr({mutationFn:async()=>{const{error:M}=await Re.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:y&&c.spouse_first_name||null,spouse_last_name:y&&c.spouse_last_name||null,spouse_email:y&&c.spouse_email||null,spouse_phone:y&&c.spouse_phone||null});if(M)throw M},onSuccess:o,onError:M=>{console.error("[PortalOnboarding] Submit failed:",M),Gt.error("Something went wrong. Please try again.")}}),E=e!=null&&e.property_address?`${e.property_address}, ${e.city||""}, ${e.state||""}`:null,k="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",P="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return a.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:a.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[a.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&a.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"}),a.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),E&&a.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[a.jsx(qs,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:E.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),a.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),a.jsxs("form",{onSubmit:M=>{M.preventDefault(),T.mutate()},className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),a.jsx($r,{required:!0,value:c.first_name,onChange:M=>s(B=>({...B,first_name:M.target.value})),className:k,placeholder:"John"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),a.jsx($r,{value:c.last_name,onChange:M=>s(B=>({...B,last_name:M.target.value})),className:k,placeholder:"Doe"})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),a.jsx($r,{type:"email",value:c.email,onChange:M=>s(B=>({...B,email:M.target.value})),className:k,placeholder:"john@example.com"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),a.jsx($r,{type:"tel",value:c.phone,onChange:M=>s(B=>({...B,phone:M.target.value})),className:k,placeholder:"(555) 123-4567"})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),a.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(M=>a.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))})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),a.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(M=>a.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=>a.jsxs("div",{children:[a.jsxs(Mr,{className:"text-xs font-medium text-slate-700",children:[M.question_text," ",M.is_required&&"*"]}),M.field_type==="text"&&a.jsx($r,{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:k}),M.field_type==="textarea"&&a.jsx("textarea",{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:`${P} min-h-[80px]`}),M.field_type==="dropdown"&&a.jsxs("select",{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:`${P} h-10`,children:[a.jsx("option",{value:"",children:"Select..."}),(M.options||[]).map(B=>a.jsx("option",{value:B,children:B},B))]}),M.field_type==="toggle"&&a.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(B=>a.jsx("button",{type:"button",onClick:()=>p(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)),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),a.jsx("textarea",{value:c.notes,onChange:M=>s(B=>({...B,notes:M.target.value})),className:`${P} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),t.allow_spouse&&a.jsxs("div",{children:[a.jsx("button",{type:"button",onClick:()=>_(!y),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:y?"− Remove spouse/partner":"+ Add spouse/partner"}),y&&a.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name"}),a.jsx($r,{value:c.spouse_first_name,onChange:M=>s(B=>({...B,spouse_first_name:M.target.value})),className:k})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),a.jsx($r,{value:c.spouse_last_name,onChange:M=>s(B=>({...B,spouse_last_name:M.target.value})),className:k})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),a.jsx($r,{type:"email",value:c.spouse_email,onChange:M=>s(B=>({...B,spouse_email:M.target.value})),className:k})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),a.jsx($r,{type:"tel",value:c.spouse_phone,onChange:M=>s(B=>({...B,spouse_phone:M.target.value})),className:k})]})]})]}),a.jsx(zt,{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 dnt(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 tGt(){const t=Gi();return gr({queryKey:["agent-portal-branding",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_portal_branding").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function hnt(t){return gr({queryKey:["agent-portal-branding-public",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.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 rGt(){const t=Gi(),e=Nr();return kr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.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 nGt(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:o}=await Re.storage.from("portal-branding").upload(i,e,{upsert:!0,cacheControl:"3600"});if(o)throw o;const{data:c}=Re.storage.from("portal-branding").getPublicUrl(i);return c.publicUrl}function fnt(t,e){return gr({queryKey:["client-portal-public",t],queryFn:async()=>{if(!t)return null;const{data:r,error:n}=await Re.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 mnt(t){return gr({queryKey:["client-portal-by-id",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.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 pnt({slug:t}){var me,Pe,Ie,Se,ve,We;const[e,r]=I.useState(!1),[n,i]=I.useState("primary"),[o]=I.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});I.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:c,isLoading:s,error:f}=fnt(t,!0),p=c==null?void 0:c.linked_portal_id,{data:y}=mnt(p),_=(me=c==null?void 0:c.deal_pipeline)==null?void 0:me.owner_user_id;gr({queryKey:["portal-stages",_],queryFn:async()=>{const{data:rt,error:at}=await Re.from("deal_pipeline_stages").select("*").eq("owner_user_id",_).order("sort_order",{ascending:!0});if(at)throw at;return rt},enabled:!!_});const{data:T}=gr({queryKey:["portal-agent",_],queryFn:async()=>{const{data:rt,error:at}=await Re.from("profiles").select("id, name, avatar_url, phone, email").eq("id",_).single();if(at)throw at;return rt},enabled:!!_}),{data:E}=hnt(_),k=n==="linked"&&y?y:c,P=k==null?void 0:k.id,R=dnt(E,k==null?void 0:k.branding_override),D=R.portal_theme==="azure"?"azure":"noir";I.useEffect(()=>{const rt=`portal-theme-${D}`;return document.body.classList.add(rt),()=>document.body.classList.remove(rt)},[D]);const{data:M}=gr({queryKey:["portal-updates-public",P],queryFn:async()=>{const{data:rt,error:at}=await Re.from("portal_updates").select("*").eq("portal_id",P).order("created_at",{ascending:!1});if(at)throw at;return rt},enabled:!!P}),B=(Pe=k==null?void 0:k.deal_pipeline)==null?void 0:Pe.id,{data:V}=gr({queryKey:["portal-documents",B],queryFn:async()=>{const{data:rt,error:at}=await Re.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}_${o}`:null,Z=W?localStorage.getItem(W)==="1":!1,{data:Q,isLoading:re}=gr({queryKey:["portal-onboarding-check",G,o],queryFn:async()=>{const{data:rt,error:at}=await Re.from("portal_onboarding_submissions").select("id").eq("portal_id",G).eq("device_fingerprint",o).maybeSingle();if(at)throw at;return rt&&W&&localStorage.setItem(W,"1"),rt},enabled:!!G&&!!(c!=null&&c.require_onboarding)&&!Z,staleTime:5*60*1e3}),se=!!(c!=null&&c.require_onboarding)&&!Z&&!Q&&!e,{data:ue}=gr({queryKey:["portal-custom-questions-public",_],queryFn:async()=>{const{data:rt,error:at}=await Re.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=Z||!!Q||e||!(c!=null&&c.require_onboarding);if(s||c!=null&&c.require_onboarding&&!Z&&re)return a.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:a.jsx(Ru,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(f||!c)return a.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:a.jsxs("div",{className:"text-center max-w-md",children:[a.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:a.jsx(Tj,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),a.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),a.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),a.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 a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:a.jsx(unt,{portal:c,dealData:rt,agentProfile:T,customQuestions:ue||[],deviceFingerprint:o,onComplete:()=>{W&&localStorage.setItem(W,"1"),r(!0)}})})}const we=(Ie=c==null?void 0:c.deal_pipeline)==null?void 0:Ie.deal_type,Ce=(Se=y==null?void 0:y.deal_pipeline)==null?void 0:Se.deal_type,Me=!!y,Ae=rt=>rt==="listing"?"Your Sale":rt==="buy-side"?"Your Purchase":"Transaction",be=rt=>rt==="listing"?a.jsx(La,{className:"w-3.5 h-3.5"}):a.jsx(Mfe,{className:"w-3.5 h-3.5"});return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"hidden lg:block",children:a.jsx(Qrt,{portal:c,linkedPortal:y,activePortal:k,activeTab:n,onTabChange:i,agentProfile:T,branding:R,updates:M,documents:V})}),a.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[a.jsx(zrt,{dealData:k==null?void 0:k.deal_pipeline,agentProfile:T,welcomeMessage:(k==null?void 0:k.welcome_message)||R.welcome_message,isWon:(We=(ve=k==null?void 0:k.deal_pipeline)==null?void 0:ve.deal_pipeline_stages)==null?void 0:We.is_won_stage,branding:R}),a.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Me&&a.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"?we:Ce;return a.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:[be(Et),a.jsx("span",{style:{fontSize:"1rem"},children:Ae(Et)})]},rt)})}),a.jsx(gnt,{portal:k,updates:M,documents:V,agentProfile:T}),P&&a.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:a.jsx(Twe,{portalId:P,clientName:k==null?void 0:k.client_name,agentName:T==null?void 0:T.name,agentAvatar:T==null?void 0:T.avatar_url,deviceFingerprint:o})}),a.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[a.jsx("div",{className:"portal-hairline w-16 mx-auto"}),a.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[a.jsx(Tj,{className:"w-3 h-3"}),a.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),T&&a.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",a.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:T.name})]})]})]})]})]})}function gnt({portal:t,updates:e,documents:r,agentProfile:n}){const i=t,o=i==null?void 0:i.deal_pipeline,c=o==null?void 0:o.deal_pipeline_stages,s=c==null?void 0:c.is_won_stage,f=o==null?void 0:o.deal_type,p=t.stage_mapping;let y=Awe(f);p&&p.length>0&&(y=p.map((P,R)=>{var D,M;return{key:`custom-${R}`,label:P.label||((D=y[R])==null?void 0:D.label)||`Stage ${R+1}`,description:P.description||((M=y[R])==null?void 0:M.description)||"",video_url:P.video_url||void 0}}));const _=p&&p.length>0?Math.min(ZD(c==null?void 0:c.name),y.length-1):ZD(c==null?void 0:c.name),T=y[_],E=T==null?void 0:T.video_url,k=s&&t.show_post_close_tips!==!1&&t.referral_enabled!==!1;return a.jsxs(a.Fragment,{children:[k&&a.jsx(Swe,{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}),a.jsx(mwe,{targetCloseDate:o==null?void 0:o.target_close_date,actualCloseDate:o==null?void 0:o.actual_close_date,clientName:t.client_name}),a.jsx(pwe,{journeyStages:y,currentIndex:_}),T&&a.jsx(gwe,{currentStage:T,nextStepText:t.next_step_text,nextStepVideoUrl:E||t.next_step_video_url}),a.jsx(ywe,{deal:o,portal:t}),(t==null?void 0:t.id)&&a.jsx(cnt,{portalId:t.id}),(t==null?void 0:t.slug)&&a.jsx(_we,{slug:t.slug}),r&&r.length>0&&a.jsx(xwe,{documents:r}),(t==null?void 0:t.id)&&(t==null?void 0:t.owner_user_id)&&a.jsx(wwe,{portalId:t.id,ownerUserId:t.owner_user_id,currentStage:c==null?void 0:c.name}),e&&e.length>0&&a.jsx(vwe,{updates:e})]})}function Pwe({slug:t}){const e=bm(),r=t||e.slug,[n,i]=I.useState(!1),[o,c]=I.useState(!1),[s,f]=I.useState(""),[p,y]=I.useState(""),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(""),[D,M]=I.useState("buying"),[B,V]=I.useState("");I.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:G,isLoading:W,error:Z}=gr({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:se,error:ue}=await Re.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}=gr({queryKey:["portal-referral-agent",G==null?void 0:G.owner_user_id],queryFn:async()=>{const{data:se}=await Re.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()){Gt.error("Please enter your friend's name");return}if(!E.trim()&&!P.trim()){Gt.error("Please add at least an email or phone for your friend");return}i(!0);try{const{error:ue}=await Re.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:p.trim()||null,friend_name:_.trim(),friend_email:E.trim()||null,friend_phone:P.trim()||null,friend_interest:D,friend_message:B.trim()||null});if(ue)throw ue;c(!0)}catch(ue){Gt.error(ue.message||"Could not submit referral")}finally{i(!1)}};return W?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:a.jsx(dl,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):Z||!G||!G.referral_enabled?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:a.jsx("span",{className:"text-2xl",children:"🔒"})}),a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),a.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):o?a.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:a.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[a.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:a.jsx(ko,{className:"w-8 h-8 text-emerald-600"})}),a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),a.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"," ",a.jsx("span",{className:"font-semibold text-slate-800",children:_})," personally and treat them like family."]}),a.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[a.jsx(Yy,{className:"w-4 h-4"}),"Back to your portal"]})]})}):a.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[a.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:[a.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),a.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[Q!=null&&Q.avatar_url?a.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"}):a.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:a.jsx(rf,{className:"w-7 h-7 text-white/70"})}),a.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:[a.jsx(rf,{className:"w-3 h-3"})," Referral"]}),a.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:G.referral_cta_headline||"Refer a Friend"}),a.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&&a.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",a.jsx("span",{className:"text-white font-medium",children:G.referral_reward_text})," when they close."]})]})]}),a.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:a.jsxs("form",{onSubmit:re,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsxs(Mr,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",a.jsx("span",{className:"text-red-500",children:"*"})]}),a.jsx($r,{id:"friend_name",value:_,onChange:se=>T(se.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),a.jsx($r,{id:"friend_email",type:"email",value:E,onChange:se=>k(se.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),a.jsx($r,{id:"friend_phone",type:"tel",value:P,onChange:se=>R(se.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),a.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-sm",children:"They're interested in..."}),a.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=>a.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))})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),a.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"})]})]})]}),a.jsxs("div",{className:"border-t pt-4",children:[a.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),a.jsx($r,{id:"referrer_name",value:s,onChange:se=>f(se.target.value),placeholder:G.client_name||"Your name",className:"mt-1"})]}),a.jsxs("div",{children:[a.jsx(Mr,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),a.jsx($r,{id:"referrer_email",type:"email",value:p,onChange:se=>y(se.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),a.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?a.jsx(Ru,{className:"w-4 h-4 animate-spin"}):a.jsx(rf,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),a.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}const ynt=Object.freeze(Object.defineProperty({__proto__:null,default:Pwe},Symbol.toStringTag,{value:"Module"}));function xnt(){const e=Bi().pathname.slice(1).replace(/\/$/,"");if(I.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!e)return a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),a.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=e.match(/^([^/]+)\/refer$/);return r?a.jsx(Pwe,{slug:r[1]}):e.includes("/")?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),a.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):a.jsx(pnt,{slug:e})}function _nt(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),o=i.searchParams.get("u");o&&/\/functions\/v1\/trestle-media/i.test(i.pathname)&&r(o)}catch{}}return e}function t8({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 o=I.useMemo(()=>_nt(Array.isArray(t)?t:[]),[t]),[c,s]=I.useState(0);return I.useEffect(()=>{s(0)},[o.join("|")]),!o.length||c>=o.length?a.jsx("div",{className:`${r} bg-muted flex items-center justify-center text-muted-foreground`,children:a.jsx(La,{className:`${i} opacity-40`})}):a.jsx("div",{className:`${r} overflow-hidden bg-muted`,children:a.jsx("img",{src:o[c],alt:e,className:n,onError:()=>s(f=>f+1)})})}function vnt({comp:t,open:e,onClose:r}){var p;const[n,i]=I.useState(0);if(!t)return null;const o=Array.isArray(t.photos)?t.photos.filter(Boolean):[],c=t.soldPrice||t.price,s=t.sqft&&c?Math.round(c/t.sqft):null,f=y=>{if(!y)return null;const[_,T,E]=y.split(/[-/T]/);return _?`${T}/${E}/${_}`:null};return a.jsx(io,{open:e,onOpenChange:y=>{y||r()},children:a.jsxs(Ua,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[a.jsxs(ml,{className:"px-6 pt-6 pb-2",children:[a.jsx(Ko,{className:"text-xl",children:t.address}),a.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[a.jsx(qs,{className:"w-3.5 h-3.5"}),t.city,", ",t.state," ",t.zip]})]}),o.length>0?a.jsxs("div",{className:"px-6",children:[a.jsx(t8,{photos:o.slice(n),className:"rounded-lg aspect-[16/10]"}),o.length>1&&a.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:o.slice(0,24).map((y,_)=>a.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:a.jsx(t8,{photos:[y],iconClassName:"w-5 h-5"})},_))})]}):a.jsx("div",{className:"px-6",children:a.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:a.jsx(La,{className:"w-12 h-12 opacity-40"})})}),a.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[a.jsx(jp,{className:"w-6 h-6 text-muted-foreground"}),(c||0).toLocaleString()]}),s&&a.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",s,"/sqft"]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1",children:[a.jsx(us,{variant:"outline",children:t.status}),t.daysOnMarket!=null&&a.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.daysOnMarket," DOM"]})]})]}),(t.listDate||t.statusChangeDate||t.soldDate)&&a.jsxs("div",{className:"px-6 pt-4",children:[a.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[a.jsx(Zz,{label:"Active",date:f(t.listDate),active:!0}),a.jsx(Zz,{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||""))}),a.jsx(Zz,{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||""))})]})]}),a.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[a.jsx(eR,{icon:a.jsx(CS,{className:"w-4 h-4"}),label:"Beds",value:t.bedrooms??"—"}),a.jsx(eR,{icon:a.jsx(nv,{className:"w-4 h-4"}),label:"Baths",value:t.bathrooms??"—"}),a.jsx(eR,{icon:a.jsx(RO,{className:"w-4 h-4"}),label:"SqFt",value:((p=t.sqft)==null?void 0:p.toLocaleString())??"—"}),a.jsx(eR,{icon:a.jsx(yo,{className:"w-4 h-4"}),label:"Year Built",value:t.yearBuilt??"—"})]}),a.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[a.jsx(Fc,{label:"MLS #",value:t.mlsNumber}),a.jsx(Fc,{label:"Property Type",value:t.propertySubType||t.propertyType}),a.jsx(Fc,{label:"Lot Size",value:t.lotSize}),a.jsx(Fc,{label:"Garage",value:t.garageSpaces}),a.jsx(Fc,{label:"Stories",value:t.stories}),a.jsx(Fc,{label:"HOA",value:t.hoaFee?`$${t.hoaFee}/${(t.hoaFrequency||"mo").toLowerCase()}`:null}),a.jsx(Fc,{label:"Tax (annual)",value:t.taxAmount?`$${t.taxAmount.toLocaleString()}`:null}),a.jsx(Fc,{label:"Heating",value:t.heating}),a.jsx(Fc,{label:"Cooling",value:t.cooling}),a.jsx(Fc,{label:"Parking",value:t.parking}),a.jsx(Fc,{label:"Elementary",value:t.elementarySchool}),a.jsx(Fc,{label:"Middle",value:t.middleSchool}),a.jsx(Fc,{label:"High",value:t.highSchool}),a.jsx(Fc,{label:"Listed By",value:t.listAgentFullName}),a.jsx(Fc,{label:"Office",value:t.listOfficeName})]}),t.description&&a.jsxs("div",{className:"px-6 pt-4",children:[a.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),a.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:t.description})]}),a.jsx("div",{className:"px-6 py-4"})]})})}function eR({icon:t,label:e,value:r}){return a.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t,e]}),a.jsx("div",{className:"text-lg font-semibold mt-0.5",children:r})]})}function Fc({label:t,value:e}){return e==null||e===""||e===0?null:a.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[a.jsx("span",{className:"text-muted-foreground",children:t}),a.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(e)})]})}function Zz({label:t,date:e,active:r}){return a.jsxs("div",{className:`rounded-lg border p-2 text-center ${r?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),a.jsx("div",{className:`text-sm font-medium mt-0.5 ${e?"":"text-muted-foreground/60"}`,children:e||"—"})]})}function tR({to:t,durationMs:e=1400,prefix:r="",suffix:n="",className:i,delayMs:o=0}){const[c,s]=I.useState(0),f=I.useRef(null);return I.useEffect(()=>{if(!Number.isFinite(t))return;let p=0;const y=0,_=E=>1-Math.pow(1-E,3),T=setTimeout(()=>{const E=k=>{p||(p=k);const P=k-p,R=Math.min(1,P/e);s(Math.round(y+(t-y)*_(R))),R<1&&(f.current=requestAnimationFrame(E))};f.current=requestAnimationFrame(E)},o);return()=>{clearTimeout(T),f.current&&cancelAnimationFrame(f.current)}},[t,e,o]),a.jsxs("span",{className:i,children:[r,c.toLocaleString(),n]})}function bnt({low:t,likely:e,high:r,defaultMortgage:n=0,defaultCommissionPct:i=6,defaultClosingPct:o=1}){const[c,s]=I.useState(e),[f,p]=I.useState(n),[y,_]=I.useState(i),[T,E]=I.useState(o),{commission:k,closing:P,net:R}=I.useMemo(()=>{const B=Math.round(c*y/100),V=Math.round(c*T/100);return{commission:B,closing:V,net:Math.max(0,c-B-V-(f||0))}},[c,y,T,f]),D=B=>`$${B.toLocaleString()}`,M=r>t?(c-t)/(r-t)*100:50;return a.jsxs(Wn,{className:"overflow-hidden border-primary/20",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(NS,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),a.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),a.jsxs(si,{className:"p-6 space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-end justify-between mb-3",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),a.jsx("span",{className:"text-3xl font-bold tabular-nums",children:D(c)})]}),a.jsxs("div",{className:"relative",children:[a.jsx(UA,{value:[c],min:t,max:r,step:1e3,onValueChange:([B])=>s(B)}),a.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[a.jsx("span",{children:D(t)}),a.jsxs("span",{children:["Suggested ",D(e)]}),a.jsx("span",{children:D(r)})]})]}),a.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:a.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))}%`}})})]}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Mortgage payoff"}),a.jsx($r,{type:"number",inputMode:"numeric",value:f||"",placeholder:"$0",onChange:B=>p(Number(B.target.value)||0)})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Commission %"}),a.jsx($r,{type:"number",step:"0.25",value:y,onChange:B=>_(Number(B.target.value)||0)})]}),a.jsxs("div",{children:[a.jsx(Mr,{className:"text-xs",children:"Closing costs %"}),a.jsx($r,{type:"number",step:"0.25",value:T,onChange:B=>E(Number(B.target.value)||0)})]})]}),a.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[a.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[a.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),a.jsx("span",{className:"text-right tabular-nums font-medium",children:D(c)}),a.jsxs("span",{className:"text-muted-foreground",children:["Commission (",y,"%)"]}),a.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(k)]}),a.jsxs("span",{className:"text-muted-foreground",children:["Closing (",T,"%)"]}),a.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(P)]}),f>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),a.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(f)]})]})]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(c9,{className:"w-5 h-5 text-emerald-600"}),a.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),a.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:D(R)})]})]}),a.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 Rwe({tokenOverride:t}={}){var Nt,er,vt,or,Sr,nn,cr,xr,tr,_n,lt,At;const e=bm(),r=t??e.token,[n,i]=I.useState(null),[o,c]=I.useState(null),[s,f]=I.useState([]),[p,y]=I.useState(!0),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(""),[D,M]=I.useState(!1),[B,V]=I.useState(!1),[G,W]=I.useState(null),[Z,Q]=I.useState(null),[re,se]=I.useState(!1),{toast:ue}=Jhe();I.useEffect(()=>{r&&(async()=>{const{data:Mt}=await Re.from("cmas").select("*").eq("share_token",r).eq("status","shared").maybeSingle();if(!Mt){y(!1);return}i(Mt);const[{data:dr},{data:ur}]=await Promise.all([Re.from("cma_comps").select("*").eq("cma_id",Mt.id).order("position"),Re.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Mt.agent_id).maybeSingle()]);f((dr||[]).filter(Xt=>Xt.selected)),c(ur);const hr=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",hr),await Re.from("cma_views").insert({cma_id:Mt.id,visitor_token:hr,user_agent:navigator.userAgent}),y(!1)})()},[r]);const _e=async Mt=>{if(!n)return;const dr=localStorage.getItem("cma_visitor_token")||"";await Re.from("cma_views").insert({cma_id:n.id,visitor_token:dr,reactions:{[Mt]:!0}}),Re.functions.invoke("cma-reply-notify",{body:{shareToken:r,reaction:Mt,visitorToken:dr}}).catch(()=>{}),ue({title:"Thanks — your agent just got notified ✨"})},we=!(n!=null&&n.contact_id),Ce=async()=>{if(!n||!_.trim())return;if(we&&(!E.trim()||!P.trim())){ue({title:"Please add your name and email",variant:"destructive"});return}M(!0);const Mt=localStorage.getItem("cma_visitor_token")||"",{data:dr,error:ur}=await Re.functions.invoke("cma-reply-notify",{body:{shareToken:r,message:_,visitorToken:Mt,viewerName:E.trim()||void 0,viewerEmail:P.trim()||void 0}});if(M(!1),ur||!(dr!=null&&dr.success)){ue({title:"Could not send",description:(ur==null?void 0:ur.message)||(dr==null?void 0:dr.error),variant:"destructive"});return}T(""),V(!0),ue({title:"Message sent to your agent"})},Me=I.useMemo(()=>{const Mt=s.map(dr=>{const ur=dr.snapshot,hr=(ur==null?void 0:ur.soldPrice)||(ur==null?void 0:ur.price);return hr&&(ur!=null&&ur.sqft)?hr/ur.sqft:null}).filter(dr=>!!dr).sort((dr,ur)=>dr-ur);return Mt.length?Math.round(Mt[Math.floor(Mt.length/2)]):null},[s]);if(p)return a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:a.jsx(Ru,{className:"w-8 h-8 animate-spin"})});if(!n)return a.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:a.jsxs("div",{children:[a.jsx(La,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),a.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),a.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Ae=n.subject||{},be=(Nt=n.settings)==null?void 0:Nt.personalVideo,me=(er=Ae.photos)==null?void 0:er[0],Pe=n.contact_first_name?n.contact_first_name:null,Ie=((o==null?void 0:o.name)||"A").split(" ").map(Mt=>Mt[0]).slice(0,2).join("").toUpperCase(),Se=o!=null&&o.phone?`tel:${String(o.phone).replace(/[^\d+]/g,"")}`:null,ve=o!=null&&o.email?`mailto:${o.email}`:null,We=o!=null&&o.phone?`sms:${String(o.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,pt=Vt&&Me?Math.round((Vt-Me)/Me*100):null;return a.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[o&&a.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:a.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[o.avatar_url?a.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):a.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}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:o.name}),(o.title||o.brokerage_name)&&a.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[o.brokerage_name&&a.jsx(go,{className:"w-3 h-3 shrink-0"}),a.jsx("span",{className:"truncate",children:[o.title,o.brokerage_name].filter(Boolean).join(" · ")})]})]}),a.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[Se&&a.jsx(zt,{variant:"outline",size:"sm",asChild:!0,children:a.jsxs("a",{href:Se,children:[a.jsx(ai,{className:"w-4 h-4 mr-1"}),"Call"]})}),ve&&a.jsx(zt,{variant:"outline",size:"sm",asChild:!0,children:a.jsxs("a",{href:ve,children:[a.jsx(Ti,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),a.jsxs("div",{className:"relative overflow-hidden",children:[me?a.jsxs("div",{className:"absolute inset-0",children:[a.jsx("img",{src:me,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"}}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):a.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),a.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),a.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:a.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[a.jsxs("div",{className:`${be!=null&&be.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[a.jsxs(us,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[a.jsx(xs,{className:"w-3 h-3 mr-1"}),Pe?`Prepared for ${Pe}`:n.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),a.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Ae.address}),a.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[a.jsx(qs,{className:"w-4 h-4"}),Ae.city,", ",Ae.state," ",Ae.zip]}),_t&&a.jsxs("div",{className:"mt-8 md:mt-10",children:[a.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),a.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:a.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:a.jsx(tR,{to:at,prefix:"$",durationMs:1600,delayMs:250})})}),a.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[a.jsxs("div",{children:[a.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),a.jsx("span",{className:"tabular-nums font-medium",children:a.jsx(tR,{to:rt,prefix:"$",delayMs:500})})]}),a.jsx("div",{className:"h-8 w-px bg-white/20"}),a.jsxs("div",{children:[a.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),a.jsx("span",{className:"tabular-nums font-medium",children:a.jsx(tR,{to:at,prefix:"$",delayMs:650})})]}),a.jsx("div",{className:"h-8 w-px bg-white/20"}),a.jsxs("div",{children:[a.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),a.jsx("span",{className:"tabular-nums font-medium",children:a.jsx(tR,{to:Et,prefix:"$",delayMs:800})})]})]})]})]}),(be==null?void 0:be.url)&&a.jsx("div",{className:"md:col-span-2 animate-scale-in",children:a.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:[be.thumb?a.jsx("img",{src:be.thumb,alt:"",className:"w-full h-full object-cover"}):a.jsx("video",{src:be.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[a.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:a.jsx(gDe,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),a.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((vt=o==null?void 0:o.name)==null?void 0:vt.split(" ")[0])||"your agent"]})]})]})})]})})]}),re&&(be==null?void 0:be.url)&&a.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:a.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Mt=>Mt.stopPropagation(),children:[a.jsx("video",{src:be.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),a.jsx(zt,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>se(!1),children:"Close"})]})}),a.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:[a.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((Mt,dr)=>a.jsx(Wn,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${dr*80}ms`},children:a.jsxs(si,{className:"p-4 md:p-6 text-center",children:[a.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Mt.value}),a.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Mt.label})]})},dr))}),((nn=(Sr=n.settings)==null?void 0:Sr.priceOverride)==null?void 0:nn.enabled)&&((xr=(cr=n.settings)==null?void 0:cr.priceOverride)==null?void 0:xr.note)&&a.jsx(Wn,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:a.jsxs(si,{className:"p-6 md:p-8",children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),a.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:n.settings.priceOverride.note})]})}),_t&&a.jsx(bnt,{low:rt,likely:at,high:Et}),Me&&Vt&&a.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[a.jsx(Wn,{className:"md:col-span-2",children:a.jsxs(si,{className:"p-6 md:p-8",children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),a.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),a.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",a.jsxs("strong",{className:"text-foreground",children:[s.length," comparable ",s.length===1?"home":"homes"]})," in ",Ae.city,", the median sale rate is ",a.jsxs("strong",{className:"text-foreground",children:["$",Me,"/sqft"]}),". Applied to your home's ",(tr=Ae.sqft)==null?void 0:tr.toLocaleString()," sqft, the comps support a value near ",a.jsxs("strong",{className:"text-foreground",children:["$",(Me*(Ae.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),a.jsx(Wn,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:a.jsxs(si,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),a.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Vt,a.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),a.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",a.jsxs("span",{className:"font-medium text-foreground",children:["$",Me,"/sqft"]})]}),pt!==null&&pt!==0&&a.jsxs("p",{className:`text-sm font-medium mt-1 ${pt>0?"text-emerald-600":"text-rose-600"}`,children:[pt>0?"▲":"▼"," ",Math.abs(pt),"% ",pt>0?"above":"below"," the median"]})]})})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),a.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),a.jsxs(us,{variant:"outline",className:"text-xs",children:[s.length," comps"]})]}),a.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map((Mt,dr)=>{var Xt;const ur=Mt.snapshot,hr=ur.soldPrice||ur.price;return a.jsxs(Wn,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${Z===dr?"ring-2 ring-primary":""}`,style:{animationDelay:`${dr*60}ms`},onClick:()=>W(dr),onMouseEnter:()=>Q(dr),onMouseLeave:()=>Q(null),children:[a.jsxs("div",{className:"relative",children:[a.jsx(t8,{photos:ur.photos,className:"w-full h-44"}),a.jsxs(us,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",dr+1]}),a.jsx(us,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:ur.status})]}),a.jsxs(si,{className:"p-4",children:[a.jsx("div",{className:"font-semibold leading-tight truncate",children:ur.address}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[ur.city,", ",ur.state]}),a.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:a.jsxs("span",{className:"text-muted-foreground",children:[ur.bedrooms??"?","bd · ",ur.bathrooms??"?","ba · ",((Xt=ur.sqft)==null?void 0:Xt.toLocaleString())??"?"," sqft"]})}),a.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[a.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",hr==null?void 0:hr.toLocaleString()]}),ur.sqft&&hr?a.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(hr/ur.sqft),"/sqft"]}):null]})]})]},dr)})})]}),a.jsx(vnt,{comp:G!==null?(_n=s[G])==null?void 0:_n.snapshot:null,open:G!==null,onClose:()=>W(null)}),a.jsx(Wn,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:a.jsxs(si,{className:"p-6 md:p-8 space-y-5",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),a.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",Pe?`, ${Pe}`:"","?"]}),a.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((lt=o==null?void 0:o.name)==null?void 0:lt.split(" ")[0])||"Your agent"," hears you instantly."]})]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:um,label:"I love this price"},{kind:"fair",icon:jDe,label:"Seems fair"},{kind:"lower",icon:qfe,label:"I'd price lower"},{kind:"higher",icon:NS,label:"I'd price higher"},{kind:"ready_to_list",icon:mU,label:"Ready to list"},{kind:"want_walkthrough",icon:CO,label:"Want a walkthrough"},{kind:"need_time",icon:yo,label:"Need more time"},{kind:"have_questions",icon:WLe,label:"I have questions"}].map(({kind:Mt,icon:dr,label:ur})=>a.jsxs(zt,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>_e(Mt),children:[a.jsx(dr,{className:"w-4 h-4 mr-2"}),ur]},Mt))}),a.jsxs("div",{className:"pt-4 border-t",children:[a.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[a.jsx(R1,{className:"w-4 h-4"}),"Ask your agent a question"]}),B?a.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=o==null?void 0:o.name)==null?void 0:At.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):a.jsxs(a.Fragment,{children:[we&&a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:E,onChange:Mt=>k(Mt.target.value)}),a.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:P,onChange:Mt=>R(Mt.target.value)})]}),a.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:Mt=>T(Mt.target.value)}),a.jsx(zt,{onClick:Ce,disabled:!_.trim()||D,className:"mt-2",children:D?"Sending…":"Send to agent"})]})]})]})}),o&&a.jsx(Wn,{className:"overflow-hidden border-primary/20",children:a.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:a.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[o.avatar_url?a.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):a.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}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),a.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:o.name}),(o.title||o.brokerage_name)&&a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[o.title,o.brokerage_name].filter(Boolean).join(" · ")}),o.bio&&a.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:o.bio}),a.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[Se&&a.jsx(zt,{asChild:!0,children:a.jsxs("a",{href:Se,children:[a.jsx(ai,{className:"w-4 h-4 mr-2"}),o.phone]})}),ve&&a.jsx(zt,{variant:"outline",asChild:!0,children:a.jsxs("a",{href:ve,children:[a.jsx(Ti,{className:"w-4 h-4 mr-2"}),"Email"]})}),o.website_url&&a.jsx(zt,{variant:"outline",asChild:!0,children:a.jsxs("a",{href:o.website_url,target:"_blank",rel:"noreferrer",children:[a.jsx(P1,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),o&&(Se||We||ve)&&a.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:[Se&&a.jsx(zt,{className:"flex-1",asChild:!0,children:a.jsxs("a",{href:Se,children:[a.jsx(ai,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),We&&a.jsx(zt,{variant:"outline",className:"flex-1",asChild:!0,children:a.jsxs("a",{href:We,children:[a.jsx(R1,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ve&&a.jsx(zt,{variant:"outline",className:"flex-1",asChild:!0,children:a.jsxs("a",{href:ve,children:[a.jsx(Ti,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}const wnt=Object.freeze(Object.defineProperty({__proto__:null,default:Rwe},Symbol.toStringTag,{value:"Module"}));function Snt(){const e=Bi().pathname.slice(1).replace(/\/$/,"");return!e||e.includes("/")?a.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),a.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):a.jsx(Rwe,{tokenOverride:e})}const r8="levelup_affiliate_ref",Tnt=30,Ent=()=>{const[t]=px();I.useEffect(()=>{const e=t.get("ref");if(e){const r={code:e.toUpperCase(),timestamp:Date.now()};localStorage.setItem(r8,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",e)}},[t])},Ant=()=>{try{const t=localStorage.getItem(r8);if(!t)return null;const e=JSON.parse(t),r=Tnt*24*60*60*1e3;return Date.now()-e.timestamp>r?(localStorage.removeItem(r8),console.log("[Affiliate] Referral code expired"),null):e.code}catch{return null}},hie="/assets/levelup-logo-header-_ZX7DvlA.png",jnt="/assets/scale-your-team-ku4MPatU.png";function knt({open:t,onOpenChange:e}){return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[a.jsx(ml,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:a.jsx(go,{className:"h-5 w-5 text-[#4a6b6d]"})}),a.jsxs("div",{children:[a.jsx(Ko,{children:"Schedule a Brokerage Interest Meeting"}),a.jsx(gd,{children:"Learn how LevelUp can empower your entire team"})]})]})}),t&&a.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 Lwe="/assets/mission_control-BJ-Kz8rX.png",Cnt="/assets/crm-CsLftmB2.png",Int="/assets/deal_pipeline-XYgypvwv.png",Nnt="/assets/staging_studio-5iLDjnv0.png",Pnt="/assets/coaching-CSQEA81I.png",Rnt="/assets/marketing_studio-Brx1ZOnN.png",Lnt=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Lwe},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:Cnt},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:Int},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:Nnt},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:Pnt},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:Rnt}];function Dnt({slot:t}){return a.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[a.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),a.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?a.jsx("img",{src:t.src,alt:`LevelUp ${t.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):a.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[a.jsx(xs,{className:"h-8 w-8 text-white/40"}),a.jsx("p",{className:"text-sm font-medium text-white/60",children:t.label}),a.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),a.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[a.jsx("span",{className:"font-semibold text-white",children:t.label})," — ",t.caption]})]})}const Fd={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}},Mnt=[{icon:n9,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:PO,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yo,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:R1,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:cm,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:rf,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Ont=[{category:"Marketing Studio",icon:Jk,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:l9,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:aDe,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:IDe,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:Sj,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:go,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],Fnt=[{icon:ul,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:xs,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ai,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:GLe,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:qs,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:wj,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:um,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:dD,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],Bnt=[{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."}],znt=()=>{const{user:t,loading:e}=Gn(),r=Gs(),[n]=px();I.useEffect(()=>{const Z=window.location.host==="listings.relevelup.com",Q=window.location.pathname==="/";if(Z&&Q){r("/public/listings",{replace:!0});return}},[r]);const[i,o]=I.useState(null),[c,s]=I.useState(null),[f,p]=I.useState(!1),[y,_]=I.useState(""),[T,E]=I.useState(""),[k,P]=I.useState(""),[R,D]=I.useState(!1),[M,B]=I.useState(!1),V=(Z,Q=!1)=>{s({tier:Z,skipTrial:Q}),p(!0)};Ent(),I.useEffect(()=>{const Z=window.location.host==="listings.relevelup.com",Q=location.pathname.startsWith("/public/");!e&&t&&!Z&&!Q&&r("/dashboard")},[t,e,r,location.pathname]),I.useEffect(()=>{n.get("canceled")==="true"&&Gt.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const G=async(Z,Q=!1)=>{if(!y){Gt.error("Please enter your email address");return}if(!T.trim()){Gt.error("Please enter your full name");return}D(!0),o(Z+(Q?"_direct":""));const re=Ant();try{const{data:se,error:ue}=await Re.functions.invoke("create-checkout",{body:{tier:Z,email:y,name:T.trim(),couponCode:k.trim()||void 0,skipTrial:Q,referralCode:re}});if(ue)throw ue;if(se!=null&&se.url)window.open(se.url,"_blank","noopener,noreferrer"),Gt.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(se){console.error("Checkout error:",se),Gt.error(se.message||"Failed to start checkout. Please try again.")}finally{D(!1),o(null),p(!1),s(null)}},W=()=>{c&&G(c.tier,c.skipTrial)};return e?a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):a.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[a.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:a.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[a.jsx("div",{className:"flex items-center",children:a.jsx("img",{src:hie,alt:"LevelUp",className:"h-8 md:h-10"})}),a.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[a.jsx(zt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Z;return(Z=document.getElementById("features"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},children:"Features"}),a.jsx(zt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),a.jsx(zt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/brokerage-solutions"),children:"For Brokerages"}),a.jsx(zt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/blog"),children:"Blog"}),a.jsx(zt,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),a.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[a.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; } } `}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),a.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]"}),a.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),a.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),a.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)]"}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),a.jsxs("div",{className:"container mx-auto px-4 relative",children:[a.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[a.jsx("div",{className:"flex justify-center animate-fade-in",children:a.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:[a.jsx(xs,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),a.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",a.jsx("br",{className:"hidden sm:block"})," to get it done.",a.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."})]}),a.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."}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[a.jsxs(zt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("free-trial"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",a.jsx(ra,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),a.jsx(zt,{size:"lg",variant:"outline",onClick:()=>{var Z;return(Z=document.getElementById("features"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),a.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:[a.jsxs("span",{className:"inline-flex items-center gap-2",children:[a.jsx(ru,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),a.jsxs("span",{className:"inline-flex items-center gap-2",children:[a.jsx(dD,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),a.jsxs("span",{className:"inline-flex items-center gap-2",children:[a.jsx(Tj,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),a.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[a.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}),a.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),a.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),a.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),a.jsx("img",{src:Lwe,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),a.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:[a.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:a.jsx(NS,{className:"h-5 w-5 text-[#7fd4cc]"})}),a.jsxs("span",{children:[a.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),a.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),a.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:[a.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:a.jsx(n9,{className:"h-5 w-5 text-[#e6c878]"})}),a.jsxs("span",{children:[a.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),a.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),a.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:[a.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:a.jsx(yo,{className:"h-5 w-5 text-white/80"})}),a.jsxs("span",{children:[a.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),a.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),a.jsx("section",{className:"py-20 bg-background",children:a.jsx("div",{className:"container mx-auto px-4",children:a.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[a.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."}),a.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[a.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),a.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),a.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),a.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[a.jsxs(zt,{size:"lg",variant:"outline",onClick:()=>{var Z;return(Z=document.getElementById("brokerage"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[a.jsx(go,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),a.jsxs(zt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[a.jsx(vc,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),a.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:a.jsxs("div",{className:"container mx-auto px-4",children:[a.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[a.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:[a.jsx(rDe,{className:"w-4 h-4"}),"40+ tools & counting"]}),a.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),a.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Mnt.map((Z,Q)=>a.jsxs(Wn,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[a.jsxs(id,{children:[a.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:a.jsx(Z.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),a.jsx(sd,{className:"text-xl font-sans",children:Z.title})]}),a.jsx(si,{children:a.jsx("p",{className:"text-muted-foreground leading-relaxed",children:Z.description})})]},Q))}),a.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:[a.jsx("div",{className:"absolute inset-0 opacity-10",children:a.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),a.jsxs("div",{className:"relative",children:[a.jsxs("div",{className:"text-center mb-10",children:[a.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),a.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:Ont.map(Z=>a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[a.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:a.jsx(Z.icon,{className:"h-4 w-4 text-white"})}),a.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:Z.category})]}),a.jsx("ul",{className:"space-y-2.5",children:Z.items.map(Q=>a.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[a.jsx(ko,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),Q]},Q))})]},Z.category))}),a.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[a.jsx(xs,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),a.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 opacity-10",children:a.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),a.jsxs("div",{className:"container mx-auto px-4 relative",children:[a.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[a.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),a.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"}),a.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),a.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:Lnt.map(Z=>a.jsx(Dnt,{slot:Z},Z.key))})]})]}),a.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 opacity-10",children:a.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),a.jsxs("div",{className:"container mx-auto px-4 relative",children:[a.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[a.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:[a.jsx(xs,{className:"w-4 h-4"}),"Included with Membership"]}),a.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",a.jsx("span",{className:"italic",children:"Agent OS"})]}),a.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."})]}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:Fnt.map((Z,Q)=>a.jsxs(Wn,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[a.jsxs(id,{className:"pb-3",children:[a.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:a.jsx(Z.icon,{className:"w-6 h-6 text-white"})}),a.jsx(sd,{className:"text-lg font-semibold text-white",children:Z.title})]}),a.jsx(si,{children:a.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:Z.description})})]},Q))}),a.jsx("div",{className:"text-center mt-12",children:a.jsxs(zt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",a.jsx(ra,{className:"ml-2 w-5 h-5"})]})})]})]}),a.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:a.jsx("div",{className:"container mx-auto px-4",children:a.jsx("div",{className:"max-w-6xl mx-auto",children:a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[a.jsxs("div",{className:"space-y-6",children:[a.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:[a.jsx(go,{className:"w-4 h-4"}),"For Brokerages"]}),a.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",a.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),a.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."}),a.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((Z,Q)=>a.jsxs("li",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:a.jsx(ko,{className:"w-4 h-4 text-[#4a6b6d]"})}),a.jsx("span",{className:"text-foreground",children:Z})]},Q))}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[a.jsxs(zt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",a.jsx(vd,{className:"ml-2 w-5 h-5"})]}),a.jsxs(zt,{size:"lg",variant:"outline",onClick:()=>B(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[a.jsx(yo,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),a.jsx("div",{className:"relative hidden md:block",children:a.jsx("img",{src:jnt,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),a.jsx("section",{className:"py-20 bg-background",children:a.jsxs("div",{className:"container mx-auto px-4",children:[a.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[a.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",a.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),a.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Bnt.map((Z,Q)=>a.jsx(Wn,{className:"bg-muted/30 border-0",children:a.jsxs(si,{className:"pt-8",children:[a.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(re=>a.jsx(ru,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},re))}),a.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',Z.quote,'"']}),a.jsxs("div",{children:[a.jsx("p",{className:"font-semibold",children:Z.name}),a.jsx("p",{className:"text-sm text-muted-foreground",children:Z.role})]})]})},Q))})]})}),a.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 opacity-10",children:a.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),a.jsx("div",{className:"container mx-auto px-4 relative",children:a.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[a.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",a.jsx("span",{className:"italic",children:"Today"})]}),a.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."}),a.jsx("div",{className:"pt-4",children:a.jsxs(zt,{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",a.jsx(ra,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),a.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:a.jsxs("div",{className:"container mx-auto px-4",children:[a.jsxs("div",{className:"text-center mb-16",children:[a.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",a.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),a.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."})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[a.jsxs(Wn,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[a.jsxs(id,{className:"pb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:a.jsx(vc,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.jsx(sd,{className:"text-xl font-sans",children:Fd.individual_agent.name})]}),a.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[a.jsx("span",{className:"text-5xl font-bold",children:Fd.individual_agent.price}),a.jsx("span",{className:"text-muted-foreground text-lg",children:Fd.individual_agent.period})]}),a.jsx(Mj,{className:"text-base mt-2",children:Fd.individual_agent.description}),a.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:[a.jsx(Rl,{className:"w-4 h-4"}),Fd.individual_agent.trial]})]}),a.jsx(si,{className:"flex-1 pt-0",children:a.jsx("ul",{className:"space-y-3",children:Fd.individual_agent.features.map((Z,Q)=>a.jsxs("li",{className:"flex items-center gap-3",children:[a.jsx(ko,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),a.jsx("span",{children:Z})]},Q))})}),a.jsxs(oV,{className:"flex flex-col gap-3 pt-4",children:[a.jsx(zt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("individual_agent"),children:"Start Free Trial"}),a.jsx(zt,{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"})]})]}),a.jsxs(Wn,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl bg-background",children:[a.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"}),a.jsxs(id,{className:"pb-4 pt-8",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:a.jsx(go,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.jsxs("div",{children:[a.jsx(sd,{className:"text-xl font-sans",children:Fd.brokerage_over_25.name}),a.jsx("span",{className:"text-sm text-muted-foreground",children:Fd.brokerage_over_25.subtitle})]})]}),a.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[a.jsx("span",{className:"text-5xl font-bold",children:Fd.brokerage_over_25.price}),a.jsx("span",{className:"text-muted-foreground text-lg",children:Fd.brokerage_over_25.period})]}),a.jsx(Mj,{className:"text-base mt-2",children:Fd.brokerage_over_25.description})]}),a.jsx(si,{className:"flex-1 pt-0",children:a.jsx("ul",{className:"space-y-3",children:Fd.brokerage_over_25.features.map((Z,Q)=>a.jsxs("li",{className:"flex items-center gap-3",children:[a.jsx(ko,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),a.jsx("span",{children:Z})]},Q))})}),a.jsxs(oV,{className:"pt-4 flex flex-col gap-3",children:[a.jsx(zt,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("brokerage_over_25"),children:"Get Started"}),a.jsxs(zt,{variant:"link",className:"text-[#4a6b6d]",onClick:()=>r("/brokerage-solutions"),children:["Explore all brokerage management tools ",a.jsx(ra,{className:"ml-1 w-4 h-4"})]})]})]})]})]})}),a.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:a.jsx("div",{className:"container mx-auto px-4",children:a.jsxs("div",{className:"max-w-4xl mx-auto",children:[a.jsxs("div",{className:"text-center mb-12",children:[a.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:[a.jsx(Tj,{className:"w-4 h-4"}),"Our Commitment"]}),a.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",a.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),a.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."})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(Wn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:a.jsxs(si,{className:"p-6 flex items-start gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:a.jsx(go,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),a.jsx(Wn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:a.jsxs(si,{className:"p-6 flex items-start gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:a.jsx(Zy,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),a.jsx(Wn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:a.jsxs(si,{className:"p-6 flex items-start gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:a.jsx(xU,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),a.jsx(Wn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:a.jsxs(si,{className:"p-6 flex items-start gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:a.jsx(cm,{className:"w-5 h-5 text-[#4a6b6d]"})}),a.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."})]})})]})]})})}),a.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 opacity-10",children:a.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),a.jsx("div",{className:"container mx-auto px-4 relative",children:a.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[a.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),a.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."}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[a.jsxs(zt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",a.jsx(ra,{className:"ml-2 w-5 h-5"})]}),a.jsx(zt,{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"})]})]})})]}),a.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:a.jsx("div",{className:"container mx-auto px-4",children:a.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[a.jsx("img",{src:hie,alt:"LevelUp",className:"h-8"}),a.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsx("a",{href:"/brokerage-solutions",className:"text-white/60 hover:text-white transition-colors text-sm",children:"For Brokerages"}),a.jsx("a",{href:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),a.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),a.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),a.jsx(knt,{open:M,onOpenChange:B}),a.jsx(io,{open:f,onOpenChange:p,children:a.jsxs(Ua,{className:"sm:max-w-md",children:[a.jsxs(ml,{children:[a.jsx(Ko,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),a.jsx(gd,{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"})]}),a.jsxs("div",{className:"space-y-4 py-4",children:[a.jsxs("div",{children:[a.jsxs(Mr,{htmlFor:"dialog-name",children:["Full Name ",a.jsx("span",{className:"text-red-500",children:"*"})]}),a.jsx($r,{id:"dialog-name",type:"text",placeholder:"John Smith",value:T,onChange:Z=>E(Z.target.value),className:"mt-1",required:!0})]}),a.jsxs("div",{children:[a.jsxs(Mr,{htmlFor:"dialog-email",children:["Email Address ",a.jsx("span",{className:"text-red-500",children:"*"})]}),a.jsx($r,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:y,onChange:Z=>_(Z.target.value),className:"mt-1",required:!0})]}),a.jsxs("div",{children:[a.jsxs(Mr,{htmlFor:"dialog-coupon",children:["Discount Code ",a.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),a.jsx($r,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:k,onChange:Z=>P(Z.target.value),className:"mt-1"})]})]}),a.jsx(zt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:W,disabled:R,children:R?"Loading...":"Continue to Checkout"})]})})]})},$nt="/__l5e/assets-v1/68014836-514e-4076-834c-9b66112cd2a0/levelup-logo-horizontal.png",Unt=_x({email:Ji().email("Invalid email address"),password:Ji().min(6,"Password must be at least 6 characters")}),Dwe="https://dashboard.relevelup.com",rR="/oauth-connect",Vnt=`${Dwe}/profile?reset=true`,vL="levelupOAuthRouteHistory";function fie(t){return t.startsWith("/")&&!t.startsWith("//")&&!t.includes("://")}function qnt(t){const e=Date.now(),r=15e3;try{const o=[...JSON.parse(sessionStorage.getItem(vL)??"[]").filter(s=>e-s.ats.route));return o.length>=6&&c.has("auth")&&c.has("consent")}catch{return sessionStorage.setItem(vL,JSON.stringify([{route:t,at:e}])),!1}}function Gnt(){sessionStorage.removeItem(vL)}const mie=()=>{const{signIn:t,user:e,loading:r}=Gn(),n=(e==null?void 0:e.id)??null,i=Gs(),[o]=px(),c=o.get("authorization_id")??"",s=o.get("next")??"",[f,p]=I.useState(!1),[y,_]=I.useState({}),[T,E]=I.useState(""),[k,P]=I.useState(!1),[R,D]=I.useState(!1),[M,B]=I.useState(null),[V,G]=I.useState(null),[W,Z]=I.useState(!1),[Q,re]=I.useState(!1),[se,ue]=I.useState(()=>{if(o.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=I.useRef(!1);I.useEffect(()=>{if(c&&/(\.lovable\.app|\.lovableproject\.com)$/.test(window.location.hostname)){const Ae=new URL("/auth",Dwe);Ae.searchParams.set("next",`${rR}?authorization_id=${encodeURIComponent(c)}`),window.location.replace(Ae.toString());return}if(c){const Ae=`${rR}?authorization_id=${encodeURIComponent(c)}`;sessionStorage.setItem("redirectAfterLogin",Ae);return}s&&fie(s)&&sessionStorage.setItem("redirectAfterLogin",s)},[c,s]),I.useEffect(()=>{if(r||!n||_e.current)return;const Ae=c?`${rR}?authorization_id=${encodeURIComponent(c)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!fie(Ae)){sessionStorage.removeItem("redirectAfterLogin"),_e.current=!0,i("/dashboard",{replace:!0});return}const be=Ae.startsWith(rR)||Ae.startsWith("/oauth/consent")||Ae.startsWith("/.lovable/oauth/consent");if(be&&qnt("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,be||(Gnt(),sessionStorage.removeItem("redirectAfterLogin")),i(Ae,{replace:!0})},[c,r,i,n]);const we=async Ae=>{Ae.preventDefault(),_({}),ue(null),G(null),Z(!1),p(!0);const be=new FormData(Ae.currentTarget),me=be.get("email"),Pe=be.get("password");try{Unt.parse({email:me,password:Pe}),await t(me,Pe)}catch(Ie){if(Ie instanceof DGe){const Se={};Ie.issues.forEach(ve=>{ve.path[0]&&(Se[ve.path[0]]=ve.message)}),_(Se)}else if(Ie instanceof Error&&Ie.name==="AccountPaused")ue(Ie.message);else if(me)try{const{data:Se}=await Re.functions.invoke("account-activation-status",{body:{email:me}});Se!=null&&Se.needsActivation&&G(me)}catch{}}finally{p(!1)}},Ce=async()=>{if(V){re(!0);try{const{data:Ae,error:be}=await Re.functions.invoke("send-password-reset",{body:{email:V,variant:"activation"}});if(be)throw be;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.");Z(!0),Gt.success("Activation email sent! Check your inbox.")}catch(Ae){Gt.error(Ae instanceof Error?Ae.message:"Failed to send activation email")}finally{re(!1)}}},Me=async()=>{if(!T){Gt.error("Please enter your email address");return}P(!0);try{const{data:Ae,error:be}=await Re.functions.invoke("send-password-reset",{body:{email:T.trim().toLowerCase(),redirectTo:Vnt}});if(be)throw be;if((Ae==null?void 0:Ae.sent)===!1){Gt.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}Gt.success("Password reset email sent! Check your inbox."),D(!1),E("")}catch(Ae){Gt.error(Ae instanceof Error?Ae.message:"Failed to send reset email")}finally{P(!1)}};return a.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:a.jsxs("div",{className:"absolute inset-0 opacity-30",children:[a.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),a.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),a.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"}})]})}),a.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[a.jsx("header",{className:"p-6",children:a.jsxs(mn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[a.jsx(Yy,{className:"h-4 w-4"}),"Back to Home"]})}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:a.jsxs("div",{className:"w-full max-w-md",children:[a.jsx("div",{className:"flex justify-center mb-8",children:a.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:a.jsx("img",{src:$nt,alt:"LevelUp",className:"h-12 w-auto"})})}),a.jsxs(Wn,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[a.jsxs(id,{className:"space-y-1 text-center pb-4",children:[a.jsx(sd,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),a.jsx(Mj,{className:"text-gray-600",children:M||"Sign in to access your dashboard"})]}),a.jsxs(si,{children:[se&&a.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[a.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),a.jsx("p",{className:"mt-1 text-sm text-amber-800",children:se}),a.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),V&&a.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[a.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),a.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&&a.jsx(zt,{type:"button",onClick:Ce,disabled:Q,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:Q?"Sending...":"Email me a set-password link"})]}),a.jsxs("form",{onSubmit:we,className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mr,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),a.jsx($r,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),y.email&&a.jsx("p",{className:"text-sm text-red-600",children:y.email})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mr,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),a.jsx($r,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),y.password&&a.jsx("p",{className:"text-sm text-red-600",children:y.password})]}),a.jsx(zt,{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"}),a.jsxs(io,{open:R,onOpenChange:D,children:[a.jsx(Bye,{asChild:!0,children:a.jsx(zt,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),a.jsxs(Ua,{className:"bg-white",children:[a.jsxs(ml,{children:[a.jsx(Ko,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),a.jsx(gd,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),a.jsxs("div",{className:"space-y-4 pt-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mr,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),a.jsx($r,{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]"})]}),a.jsx(zt,{onClick:Me,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:k,children:k?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),a.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",a.jsx(mn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},jH=()=>gr({queryKey:["lead-sources"],queryFn:async()=>{const{data:t,error:e}=await Re.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(e)throw e;return t}}),Hnt=()=>{const t=Nr(),{user:e}=Gn();return kr({mutationFn:async r=>{const{data:n}=await Re.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:o,error:c}=await Re.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 o},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Gt.success("Lead source added")},onError:r=>{Gt.error("Failed to add lead source"),console.error(r)}})},iGt=()=>{const t=Nr();return kr({mutationFn:async({id:e,name:r})=>{const{error:n}=await Re.from("lead_sources").update({name:r}).eq("id",e);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Gt.success("Lead source updated")},onError:e=>{Gt.error(e.message||"Failed to update lead source")}})},sGt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("lead_sources").update({is_active:!1}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Gt.success("Lead source removed")},onError:e=>{Gt.error(e.message||"Failed to remove lead source")}})},Mwe=(t,e)=>{const{user:r,isAdmin:n}=Gn(),i=n&&e?e:r==null?void 0:r.id;return gr({queryKey:["scorecard-transactions",t,i],queryFn:async()=>{let o=Re.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&&(o=o.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:c,error:s}=await o;if(s)throw s;return c},enabled:!!i})},Wnt=t=>{const{user:e,isAdmin:r}=Gn(),n=r&&t?t:e==null?void 0:e.id;return gr({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:i,error:o}=await Re.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(o)throw o;return i},enabled:!!n})},kH=()=>{const t=Nr(),{user:e}=Gn();return kr({mutationFn:async r=>{const{data:n,error:i}=await Re.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"]}),Gt.success("Transaction added")},onError:r=>{Gt.error("Failed to add transaction"),console.error(r)}})},Knt=()=>{const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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"]}),Gt.success("Transaction updated")},onError:e=>{Gt.error("Failed to update transaction"),console.error(e)}})},Ynt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("scorecard_transactions").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Gt.success("Transaction deleted")},onError:e=>{Gt.error("Failed to delete transaction"),console.error(e)}})},Znt=(t,e)=>{const{user:r,isAdmin:n}=Gn(),i=n&&e?e:r==null?void 0:r.id;return gr({queryKey:["scorecard-goals",t,i],queryFn:async()=>{const{data:o,error:c}=await Re.from("scorecard_goals").select("*").eq("owner_user_id",i).eq("year",t).maybeSingle();if(c)throw c;return o},enabled:!!i})},Xnt=()=>{const t=Nr(),{user:e}=Gn();return kr({mutationFn:async r=>{const{data:n,error:i}=await Re.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]}),Gt.success("Goals saved")},onError:r=>{Gt.error("Failed to save goals"),console.error(r)}})},G3=()=>{const{user:t}=Gn();return gr({queryKey:["scorecard-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Re.from("scorecard_settings").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e},enabled:!!(t!=null&&t.id)})},Qnt=()=>{const t=Nr(),{user:e}=Gn();return kr({mutationFn:async r=>{const{data:n,error:i}=await Re.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"]}),Gt.success("Settings saved")},onError:r=>{Gt.error("Failed to save settings"),console.error(r)}})},Jnt=(t,e)=>{const{data:r,isLoading:n}=Mwe(t,e),{data:i,isLoading:o}=Wnt(e),{data:c}=G3(),s=(c==null?void 0:c.show_commission)??!0,f=p=>{if(!p||p.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const y=p.filter(G=>G.transaction_type==="buyer").length,_=p.filter(G=>G.transaction_type==="seller").length,T=p.reduce((G,W)=>G+Number(W.sale_price),0),E=p.reduce((G,W)=>G+(Number(W.commission_amount)||0),0),k=p.reduce((G,W)=>{const Z=Number(W.commission_amount)||0;if(!Z)return G;let Q=Z;return W.brokerage_split_pct&&(Q-=Z*(W.brokerage_split_pct/100)),W.team_split_pct&&(Q-=Z*(W.team_split_pct/100)),W.franchise_fee_pct&&(Q-=Z*(W.franchise_fee_pct/100)),W.referral_fee_pct&&(Q-=Z*(W.referral_fee_pct/100)),W.transaction_fee&&(Q-=W.transaction_fee),G+Math.max(0,Q)},0),P={};p.forEach(G=>{var Z;const W=((Z=G.lead_source)==null?void 0:Z.name)||"Unknown";P[W]=(P[W]||0)+1});const R=Object.entries(P).map(([G,W])=>({name:G,count:W})).sort((G,W)=>W.count-G.count),D=R[0]||null,M={};p.forEach(G=>{const W=Y1(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:p.length,buyerCount:y,sellerCount:_,totalVolume:T,averagePrice:p.length>0?T/p.length:0,totalCommission:s?E:0,totalNetToAgent:s?k:0,topLeadSource:D,transactionsByMonth:V,leadSourceBreakdown:R}};return{yearStats:f(r),lifetimeStats:f(i),isLoading:n||o,showCommission:s}},aGt=()=>{const{isAdmin:t}=Gn();return gr({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:e,error:r}=await Re.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:o}=await Re.from("profiles").select("id, name, email").in("id",n);if(o)throw o;return i},enabled:t})},CH=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{className:"relative w-full overflow-auto",children:a.jsx("table",{ref:r,className:sr("w-full caption-bottom text-sm",t),...e})}));CH.displayName="Table";const IH=I.forwardRef(({className:t,...e},r)=>a.jsx("thead",{ref:r,className:sr("[&_tr]:border-b",t),...e}));IH.displayName="TableHeader";const NH=I.forwardRef(({className:t,...e},r)=>a.jsx("tbody",{ref:r,className:sr("[&_tr:last-child]:border-0",t),...e}));NH.displayName="TableBody";const eit=I.forwardRef(({className:t,...e},r)=>a.jsx("tfoot",{ref:r,className:sr("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...e}));eit.displayName="TableFooter";const Yj=I.forwardRef(({className:t,...e},r)=>a.jsx("tr",{ref:r,className:sr("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...e}));Yj.displayName="TableRow";const Hl=I.forwardRef(({className:t,...e},r)=>a.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}));Hl.displayName="TableHead";const Wl=I.forwardRef(({className:t,...e},r)=>a.jsx("td",{ref:r,className:sr("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...e}));Wl.displayName="TableCell";const tit=I.forwardRef(({className:t,...e},r)=>a.jsx("caption",{ref:r,className:sr("mt-4 text-sm text-muted-foreground",t),...e}));tit.displayName="TableCaption";const n8="boost";function Tx(t,e){typeof window>"u"||window.dispatchEvent(new CustomEvent(n8,{detail:{type:t,requestId:e}}))}function oGt(t){const e=r=>{const n=r.detail;t(typeof n=="string"?{type:n}:n)};return window.addEventListener(n8,e),()=>window.removeEventListener(n8,e)}const lGt=["Idle","Thinking","Listening","Working","Success","Alert","Celebration","Pointing","Wave","Sleeping"],cGt=new Set(["Idle","Thinking","Listening","Working","Sleeping"]),uGt={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}},pie={hidden:!1,paused:!1,reduceMotion:!1,muteAnnouncements:!1},Owe=new Map,Fwe=t=>`boost:prefs:${t}`;function dGt(t){try{const e=window.localStorage.getItem(Fwe(t));if(e)return{...pie,...JSON.parse(e)}}catch{}return Owe.get(t)??pie}function hGt(t,e){Owe.set(t,e);try{window.localStorage.setItem(Fwe(t),JSON.stringify(e))}catch{}}let W2=null;function fGt(){var t;if(W2!==null)return W2;try{const e=document.createElement("canvas"),r=e.getContext("webgl2")||e.getContext("webgl");W2=!!r,(t=r==null?void 0:r.getExtension("WEBGL_lose_context"))==null||t.loseContext()}catch{W2=!1}return W2}const PH=()=>gr({queryKey:["relationship-types"],queryFn:async()=>{const{data:t,error:e}=await Re.from("relationship_types").select("*").order("sort_order");if(e)throw e;return t}}),mGt=()=>{const t=Gi(),e=1e3;return gr({queryKey:["innercircle-contacts-lite",t],queryFn:async()=>{const r=[];let n=0;for(;;){const{data:i,error:o}=await Re.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(o)throw o;const c=i??[];if(r.push(...c),c.length{const e=Gi(),r=1e3,n=async i=>{const o=[];let c=0;for(;;){const{data:s,error:f}=await i.range(c,c+r-1);if(f)throw f;const p=s??[];if(o.push(...p),p.length{let i=Re.from("innercircle_contacts").select("*").eq("owner_user_id",e).order("created_at",{ascending:!1}).order("first_name");const o=await n(i);if(o.length===0)return o;const c=o.map(E=>E.id),s=Array.from(new Set(o.map(E=>E.lead_source_id).filter(E=>!!E))),f=(E,k=250)=>{const P=[];for(let R=0;R{const{data:k,error:P}=await Re.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",E);if(P)throw P;return k??[]})),Promise.all(f(s).map(async E=>{const{data:k,error:P}=await Re.from("lead_sources").select("id, name").in("id",E);if(P)throw P;return k??[]}))]),_=new Map;p.flat().forEach(E=>{const k=_.get(E.contact_id)??[];k.push(E),_.set(E.contact_id,k)});const T=new Map(y.flat().map(E=>[E.id,E]));return o.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})},pGt=t=>gr({queryKey:["innercircle-contact",t],queryFn:async()=>{const{data:e,error:r}=await Re.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}),gGt=()=>{const t=Gi();return gr({queryKey:["innercircle-contact-counts",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 o;(o=i.tags)==null||o.forEach(c=>{n[c.relationship_type_id]=(n[c.relationship_type_id]||0)+1})}),n},enabled:!!t})},rit=()=>{const t=Nr(),e=Gi();return kr({mutationFn:async r=>{const{tagIds:n,...i}=r,o={...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 Re.from("innercircle_contacts").insert(o).select().single();if(s)throw s;if(n&&n.length>0){const{error:f}=await Re.from("innercircle_contact_tags").insert(n.map(p=>({contact_id:c.id,relationship_type_id:p})));if(f)throw f}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Tx("contact_created"),Ts({title:"Contact created successfully"})},onError:r=>{Ts({title:"Error creating contact",description:r.message,variant:"destructive"})}})},yGt=()=>{const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{tagIds:n,tags:i,...o}=r,c=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],s={...o};for(const y of Object.keys(s)){const _=s[y];(_===""||typeof _=="string"&&c.includes(y)&&_.trim()==="")&&(s[y]=null)}const{data:f,error:p}=await Re.from("innercircle_contacts").update(s).eq("id",e).select().single();if(p)throw p;if(n!==void 0&&(await Re.from("innercircle_contact_tags").delete().eq("contact_id",e),n.length>0)){const{error:y}=await Re.from("innercircle_contact_tags").insert(n.map(_=>({contact_id:e,relationship_type_id:_})));if(y)throw y}return f},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Tx("contact_created"),Ts({title:"Contact updated successfully"})},onError:e=>{Ts({title:"Error updating contact",description:e.message,variant:"destructive"})}})},xGt=()=>{const t=Nr();return kr({mutationFn:async({contactId:e,spouseContactId:r})=>{if(r){const{error:n}=await Re.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",e);if(n)throw n;const{error:i}=await Re.from("innercircle_contacts").update({spouse_contact_id:e}).eq("id",r);if(i)throw i}else{const{data:n}=await Re.from("innercircle_contacts").select("spouse_contact_id").eq("id",e).single(),i=n==null?void 0:n.spouse_contact_id,{error:o}=await Re.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",e);if(o)throw o;if(i){const{error:c}=await Re.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"})}})},_Gt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.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"})}})},vGt=()=>{const t=Nr();return kr({mutationFn:async({ids:e,onProgress:r})=>{let i=0;for(let o=0;o{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),t.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},nit=()=>gr({queryKey:["action-types"],queryFn:async()=>{const{data:t,error:e}=await Re.from("action_types").select("*").order("sort_order");if(e)throw e;return t}}),bGt=t=>gr({queryKey:["action-scripts",t],queryFn:async()=>{let e=Re.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await e;if(n)throw n;return r}}),wGt=()=>gr({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:t,error:e}=await Re.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(e)throw e;return t}}),SGt=()=>{const t=Nr(),e=Gi();return kr({mutationFn:async({name:r,description:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:e,active:!0,is_template:!1}).select().single();if(o)throw o;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"})}})},TGt=()=>{const t=Nr(),e=Gi();return kr({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(o)throw o;if(!i)throw new Error("Source plan not found");const{data:c,error:s}=await Re.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(y=>({plan_id:c.id,month_number:y.month_number,action_type_id:y.action_type_id,default_script_id:y.default_script_id,notes:y.notes})),{error:p}=await Re.from("touchpoint_plan_items").insert(f);if(p)throw p}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"})}})},EGt=()=>{const t=Nr();return kr({mutationFn:async({id:e,name:r,description:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").update({name:r,description:n}).eq("id",e).select().single();if(o)throw o;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan updated successfully"})}})},AGt=()=>{const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("touchpoint_plans").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan deleted successfully"})}})},jGt=()=>{const t=Nr();return kr({mutationFn:async({planId:e,items:r})=>{if(await Re.from("touchpoint_plan_items").delete().eq("plan_id",e),r.length>0){const{error:n}=await Re.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"})}})},kGt=()=>{const t=Nr();return kr({mutationFn:async({actionTypeId:e,title:r,scriptBody:n,emailSubject:i,tone:o})=>{const{data:{user:c}}=await Re.auth.getUser(),{data:s,error:f}=await Re.from("action_scripts").insert({action_type_id:e,title:r,script_body:n,email_subject:i||null,tone:o||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"})}})},CGt=()=>{const t=Gi();return gr({queryKey:["user-plan-enrollments",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return e},enabled:!!t})},IGt=()=>{const t=Nr(),e=Gi();return kr({mutationFn:async({planId:r,relationshipTypeId:n,active:i})=>{const{data:o}=await Re.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(o){const{error:c}=await Re.from("user_plan_enrollments").update({active:i}).eq("id",o.id);if(c)throw c}else if(i){const{error:c}=await Re.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"})}})},zwe=(t=7)=>{const e=Gi();return gr({queryKey:["contact-touch-logs",e,t],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-t);const{data:n,error:i}=await Re.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})},iit=()=>{const t=Gi();return gr({queryKey:["contacts-last-touch",t],queryFn:async()=>{const{data:e,error:r}=await Re.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})},NGt=(t=90)=>{const{data:e}=Bwe(),{data:r}=iit();if(!e||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-t);const i=e.filter(o=>{const c=r[o.id];return c?new Date(c){const t=Nr(),e=Gi();return kr({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:i,notes:o,completedAt:c})=>{const{data:s,error:f}=await Re.from("contact_touch_logs").insert({owner_user_id:e,contact_id:r,action_type_id:n,script_used_id:i,notes:o,completed_at:c||new Date().toISOString()}).select().single();if(f)throw f;return s},onSuccess:async(r,n)=>{var i,o;t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts-last-touch"]}),t.invalidateQueries({queryKey:["today-actions"]}),t.invalidateQueries({queryKey:["popby-logs"]}),Tx("task_completed"),Ts({title:"Action completed!"});try{const[c,s]=await Promise.all([Re.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),Re.from("action_types").select("name").eq("id",n.actionTypeId).single()]),f=(i=c.data)==null?void 0:i.email,p=((o=s.data)==null?void 0:o.name)||"Touch";/pop[\s-]?by/i.test(p)&&Re.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&&Re.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:f,touch_type:p,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},$we="agentos_weekly_touch_goal",gie=20,ait=()=>{if(typeof window>"u")return gie;const t=localStorage.getItem($we);if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return gie},PGt=t=>{localStorage.setItem($we,t.toString())},RGt=()=>{const{data:t}=zwe(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 o=ait();return{actionsThisWeek:n,weeklyGoal:o,streak:i,progress:Math.min(n/o*100,100)}},oit=()=>{const t=Gi();return gr({queryKey:["contact-plan-cycles",t],queryFn:async()=>{const{data:e,error:r}=await Re.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})},LGt=()=>{const t=Nr();return Gi(),kr({mutationFn:async()=>{var f;const{data:e}=await Re.from("user_plan_enrollments").select("*").eq("active",!0);if(!e||e.length===0)return;const{data:r}=await Re.auth.getUser(),n=(f=r==null?void 0:r.user)==null?void 0:f.id;if(!n)return;const{data:i}=await Re.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",n);if(!i)return;const{data:o}=await Re.from("contact_plan_cycles").select("contact_id, plan_id"),c=new Set((o==null?void 0:o.map(p=>`${p.contact_id}-${p.plan_id}`))||[]),s=[];for(const p of i)for(const y of p.tags||[]){const _=e.find(T=>T.relationship_type_id===y.relationship_type_id);_&&!c.has(`${p.id}-${_.plan_id}`)&&s.push({contact_id:p.id,plan_id:_.plan_id,relationship_type_id:y.relationship_type_id})}if(s.length>0){const{error:p}=await Re.from("contact_plan_cycles").insert(s);if(p)throw p}return s.length},onSuccess:e=>{t.invalidateQueries({queryKey:["contact-plan-cycles"]}),e&&e>0&&Ts({title:`${e} contact(s) enrolled in plans`})}})},DGt=()=>{const t=Gi(),{data:e}=oit(),{data:r}=zwe(30);return gr({queryKey:["today-actions",t,e==null?void 0:e.length,r==null?void 0:r.length],queryFn:async()=>{var k;if(!e||e.length===0)return[];const{data:n}=await Re.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),i=new Set((n==null?void 0:n.map(P=>P.contact_id))||[]),o=new Date,c=[],s=new Date(o.getFullYear(),o.getMonth(),1),f=new Set((r==null?void 0:r.filter(P=>new Date(P.completed_at)>=s).map(P=>`${P.contact_id}-${P.action_type_id}`))||[]);for(const P of e){if(!((k=P.plan)!=null&&k.items)||P.plan.items.length===0||!P.contact||i.has(P.contact_id))continue;const R=new Date(P.cycle_start_date),M=Math.floor((o.getTime()-R.getTime())/(30.44*24*60*60*1e3))%12+1,B=P.plan.items.find(V=>V.month_number===M);if(B&&B.action_type){const V=`${P.contact_id}-${B.action_type_id}`;if(!f.has(V)){const{data:G}=await Re.from("relationship_types").select("name").eq("id",P.relationship_type_id).single();c.push({contact:P.contact,actionType:B.action_type,script:B.default_script||void 0,planName:P.plan.name,relationshipTypeName:(G==null?void 0:G.name)||"",monthNumber:M})}}}const p=5,y=o.getDate(),_=c.sort((P,R)=>P.contact.first_name.localeCompare(R.contact.first_name)),T=(y-1)%Math.max(1,_.length);return[..._.slice(T),..._.slice(0,T)].slice(0,p)},enabled:!!t&&!!e})};var H3="Popover",[Uwe,MGt]=Yo(H3,[mx]),kC=mx(),[lit,Ex]=Uwe(H3),Vwe=t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!1}=t,s=kC(e),f=I.useRef(null),[p,y]=I.useState(!1),[_,T]=dd({prop:n,defaultProp:i??!1,onChange:o,caller:H3});return a.jsx(qO,{...s,children:a.jsx(lit,{scope:e,contentId:Dl(),triggerRef:f,open:_,onOpenChange:T,onOpenToggle:I.useCallback(()=>T(E=>!E),[T]),hasCustomAnchor:p,onCustomAnchorAdd:I.useCallback(()=>y(!0),[]),onCustomAnchorRemove:I.useCallback(()=>y(!1),[]),modal:c,children:r})})};Vwe.displayName=H3;var qwe="PopoverAnchor",cit=I.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=Ex(qwe,r),o=kC(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:s}=i;return I.useEffect(()=>(c(),()=>s()),[c,s]),a.jsx(lC,{...o,...n,ref:e})});cit.displayName=qwe;var Gwe="PopoverTrigger",Hwe=I.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=Ex(Gwe,r),o=kC(r),c=Kn(e,i.triggerRef),s=a.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Xwe(i.open),...n,ref:c,onClick:Or(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?s:a.jsx(lC,{asChild:!0,...o,children:s})});Hwe.displayName=Gwe;var RH="PopoverPortal",[uit,dit]=Uwe(RH,{forceMount:void 0}),Wwe=t=>{const{__scopePopover:e,forceMount:r,children:n,container:i}=t,o=Ex(RH,e);return a.jsx(uit,{scope:e,forceMount:r,children:a.jsx(pl,{present:r||o.open,children:a.jsx(jS,{asChild:!0,container:i,children:n})})})};Wwe.displayName=RH;var Z1="PopoverContent",Kwe=I.forwardRef((t,e)=>{const r=dit(Z1,t.__scopePopover),{forceMount:n=r.forceMount,...i}=t,o=Ex(Z1,t.__scopePopover);return a.jsx(pl,{present:n||o.open,children:o.modal?a.jsx(fit,{...i,ref:e}):a.jsx(mit,{...i,ref:e})})});Kwe.displayName=Z1;var hit=Ky("PopoverContent.RemoveScroll"),fit=I.forwardRef((t,e)=>{const r=Ex(Z1,t.__scopePopover),n=I.useRef(null),i=Kn(e,n),o=I.useRef(!1);return I.useEffect(()=>{const c=n.current;if(c)return OO(c)},[]),a.jsx(rC,{as:hit,allowPinchZoom:!0,children:a.jsx(Ywe,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,c=>{var s;c.preventDefault(),o.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,p=s.button===2||f;o.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:Or(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})}),mit=I.forwardRef((t,e)=>{const r=Ex(Z1,t.__scopePopover),n=I.useRef(!1),i=I.useRef(!1);return a.jsx(Ywe,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var c,s;(c=t.onCloseAutoFocus)==null||c.call(t,o),o.defaultPrevented||(n.current||(s=r.triggerRef.current)==null||s.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var f,p;(f=t.onInteractOutside)==null||f.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((p=r.triggerRef.current)==null?void 0:p.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Ywe=I.forwardRef((t,e)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:c,onEscapeKeyDown:s,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,..._}=t,T=Ex(Z1,r),E=kC(r);return DO(),a.jsx(tC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a.jsx(rv,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:y,onEscapeKeyDown:s,onPointerDownOutside:f,onFocusOutside:p,onDismiss:()=>T.onOpenChange(!1),children:a.jsx(GO,{"data-state":Xwe(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)"}})})})}),Zwe="PopoverClose",pit=I.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=Ex(Zwe,r);return a.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});pit.displayName=Zwe;var git="PopoverArrow",yit=I.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=kC(r);return a.jsx(HO,{...i,...n,ref:e})});yit.displayName=git;function Xwe(t){return t?"open":"closed"}var xit=Vwe,_it=Hwe,vit=Wwe,Qwe=Kwe;const bL=xit,wL=_it,KA=I.forwardRef(({className:t,align:e="center",sideOffset:r=4,...n},i)=>a.jsx(vit,{children:a.jsx(Qwe,{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})}));KA.displayName=Qwe.displayName;const bit=_x({property_address:Ji().min(1,"Property address is required"),city:Ji().optional(),state:Ji().optional(),zip:Ji().optional(),transaction_type:x3(["buyer","seller"]),close_date:Ji().min(1,"Close date is required"),sale_price:$A().min(0,"Sale price must be positive"),commission_amount:$A().optional(),lead_source_id:Ji().optional(),client_type_id:Ji().optional(),contact_id:Ji().optional(),notes:Ji().optional(),is_win:m9e()});function Jwe({open:t,onOpenChange:e,transaction:r}){const[n,i]=I.useState(!1),[o,c]=I.useState(""),[s,f]=I.useState(!1),[p,y]=I.useState(""),_=kH(),T=Knt(),{data:E}=jH(),{data:k}=PH(),{data:P}=Bwe(),R=rit(),D=Hnt(),{data:M}=G3(),B=(M==null?void 0:M.show_commission)??!0,V=m7({resolver:p7(bit),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}});I.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(!o.trim())return;const[re,...se]=o.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))},Z=async()=>{if(!p.trim())return;const re=await D.mutateAsync(p.trim());re&&(V.setValue("lead_source_id",re.id),y(""))},Q=P==null?void 0:P.find(re=>re.id===V.watch("contact_id"));return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"max-w-lg max-h-[90vh]",children:[a.jsx(ml,{children:a.jsx(Ko,{children:r?"Edit Transaction":"Add Transaction"})}),a.jsx(Sm,{className:"max-h-[70vh] pr-4",children:a.jsx(T7,{...V,children:a.jsxs("form",{onSubmit:V.handleSubmit(G),className:"space-y-4",children:[a.jsx(sl,{control:V.control,name:"property_address",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Property Address *"}),a.jsx(Uo,{children:a.jsx($r,{placeholder:"123 Main St",...re})}),a.jsx(Qh,{})]})}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[a.jsx(sl,{control:V.control,name:"city",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"City"}),a.jsx(Uo,{children:a.jsx($r,{placeholder:"City",...re})})]})}),a.jsx(sl,{control:V.control,name:"state",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"State"}),a.jsx(Uo,{children:a.jsx($r,{placeholder:"TX",...re})})]})}),a.jsx(sl,{control:V.control,name:"zip",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Zip"}),a.jsx(Uo,{children:a.jsx($r,{placeholder:"75001",...re})})]})})]}),a.jsx(sl,{control:V.control,name:"transaction_type",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Transaction Type *"}),a.jsxs(_a,{onValueChange:re.onChange,value:re.value,children:[a.jsx(Uo,{children:a.jsx(aa,{children:a.jsx(va,{placeholder:"Select type"})})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"buyer",children:"Buyer"}),a.jsx(fn,{value:"seller",children:"Seller"})]})]}),a.jsx(Qh,{})]})}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(sl,{control:V.control,name:"close_date",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Close Date *"}),a.jsx(Uo,{children:a.jsx($r,{type:"date",...re})}),a.jsx(Qh,{})]})}),a.jsx(sl,{control:V.control,name:"sale_price",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Sale Price *"}),a.jsx(Uo,{children:a.jsx($r,{type:"number",placeholder:"0",...re,onChange:se=>re.onChange(Number(se.target.value))})}),a.jsx(Qh,{})]})})]}),B&&a.jsx(sl,{control:V.control,name:"commission_amount",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Commission"}),a.jsx(Uo,{children:a.jsx($r,{type:"number",placeholder:"0",...re,value:re.value??"",onChange:se=>re.onChange(se.target.value?Number(se.target.value):void 0)})})]})}),a.jsx(sl,{control:V.control,name:"lead_source_id",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Lead Source"}),a.jsxs(_a,{onValueChange:re.onChange,value:re.value||"",children:[a.jsx(Uo,{children:a.jsx(aa,{children:a.jsx(va,{placeholder:"Select source"})})}),a.jsx(oa,{children:E==null?void 0:E.map(se=>a.jsx(fn,{value:se.id,children:se.name},se.id))})]})]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx($r,{placeholder:"Add custom source...",value:p,onChange:re=>y(re.target.value),className:"flex-1"}),a.jsx(zt,{type:"button",variant:"outline",size:"icon",onClick:Z,disabled:!p.trim(),children:a.jsx(sm,{className:"h-4 w-4"})})]}),a.jsx(sl,{control:V.control,name:"client_type_id",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Client Type"}),a.jsxs(_a,{onValueChange:re.onChange,value:re.value||"",children:[a.jsx(Uo,{children:a.jsx(aa,{children:a.jsx(va,{placeholder:"Select client type"})})}),a.jsx(oa,{children:k==null?void 0:k.map(se=>a.jsx(fn,{value:se.id,children:se.name},se.id))})]})]})}),a.jsx(sl,{control:V.control,name:"contact_id",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Client Contact"}),a.jsxs(bL,{open:n,onOpenChange:i,children:[a.jsx(wL,{asChild:!0,children:a.jsx(Uo,{children:a.jsxs(zt,{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",a.jsx(dU,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),a.jsxs(KA,{className:"w-full p-0",align:"start",children:[a.jsxs(zj,{children:[a.jsx($j,{placeholder:"Search contacts..."}),a.jsxs(Uj,{children:[a.jsx(Vj,{children:a.jsxs("div",{className:"p-2 space-y-2",children:[a.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!s&&a.jsxs(zt,{variant:"outline",size:"sm",className:"w-full",onClick:()=>f(!0),children:[a.jsx(sm,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),a.jsx(q1,{children:P==null?void 0:P.map(se=>a.jsxs(ky,{value:`${se.first_name} ${se.last_name||""}`,onSelect:()=>{re.onChange(se.id),i(!1)},children:[a.jsx(ko,{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&&a.jsxs("div",{className:"p-2 border-t space-y-2",children:[a.jsx($r,{placeholder:"Enter contact name...",value:o,onChange:se=>c(se.target.value)}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(zt,{size:"sm",onClick:W,disabled:!o.trim()||R.isPending,children:"Add Contact"}),a.jsx(zt,{size:"sm",variant:"outline",onClick:()=>{f(!1),c("")},children:"Cancel"})]})]})]})]})]})}),a.jsx(sl,{control:V.control,name:"notes",render:({field:re})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Notes"}),a.jsx(Uo,{children:a.jsx(bd,{placeholder:"Any notes about this transaction...",...re})})]})}),a.jsx(sl,{control:V.control,name:"is_win",render:({field:re})=>a.jsxs(zo,{className:"flex items-center justify-between rounded-lg border p-3",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx($o,{children:"Mark as Win 🏆"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),a.jsx(Uo,{children:a.jsx(YS,{checked:re.value,onCheckedChange:re.onChange})})]})}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(zt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),a.jsxs(zt,{type:"submit",disabled:_.isPending||T.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}const Xz=768;function wit(){const[t,e]=I.useState(void 0);return I.useEffect(()=>{const r=window.matchMedia(`(max-width: ${Xz-1}px)`),n=()=>{e(window.innerWidthr.removeEventListener("change",n)},[]),!!t}function e1e({transactions:t,showCommission:e,isLoading:r,agentNameMap:n,readOnly:i}){const[o,c]=I.useState(null),[s,f]=I.useState(null),[p,y]=I.useState(""),[_,T]=I.useState("all"),[E,k]=I.useState("all"),[P,R]=I.useState("all"),[D,M]=I.useState(!1),B=Ynt(),V=kH(),{data:G}=jH();PH();const W=wit(),Z=se=>{const{id:ue,created_at:_e,updated_at:we,lead_source:Ce,client_type:Me,contact:Ae,...be}=se;V.mutate(be)},Q=()=>{s&&(B.mutate(s),f(null))},re=t.filter(se=>{var Ae,be,me,Pe;const ue=p===""||se.property_address.toLowerCase().includes(p.toLowerCase())||((be=(Ae=se.contact)==null?void 0:Ae.first_name)==null?void 0:be.toLowerCase().includes(p.toLowerCase()))||((Pe=(me=se.contact)==null?void 0:me.last_name)==null?void 0:Pe.toLowerCase().includes(p.toLowerCase())),_e=_==="all"||se.transaction_type===_,we=E==="all"||se.lead_source_id===E,Ce=P==="all"||se.client_type_id===P,Me=!D||se.is_win;return ue&&_e&&we&&Ce&&Me});return r?a.jsx(Wn,{children:a.jsx(si,{className:"p-6 space-y-4",children:[1,2,3].map(se=>a.jsx(dl,{className:"h-16 w-full"},se))})}):a.jsxs(a.Fragment,{children:[a.jsxs(Wn,{children:[a.jsx(id,{className:"pb-3",children:a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[a.jsxs(sd,{children:["Transactions (",re.length,")"]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"relative",children:[a.jsx(hd,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),a.jsx($r,{placeholder:"Search...",value:p,onChange:se=>y(se.target.value),className:"pl-8 w-[150px]"})]}),a.jsxs(_a,{value:_,onValueChange:T,children:[a.jsx(aa,{className:"w-[100px]",children:a.jsx(va,{placeholder:"Type"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"All Types"}),a.jsx(fn,{value:"buyer",children:"Buyer"}),a.jsx(fn,{value:"seller",children:"Seller"})]})]}),a.jsxs(_a,{value:E,onValueChange:k,children:[a.jsx(aa,{className:"w-[130px]",children:a.jsx(va,{placeholder:"Lead Source"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"All Sources"}),G==null?void 0:G.map(se=>a.jsx(fn,{value:se.id,children:se.name},se.id))]})]}),a.jsxs(zt,{variant:D?"default":"outline",size:"sm",onClick:()=>M(!D),children:[a.jsx(Ww,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),a.jsx(si,{children:re.length===0?a.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):W?a.jsx("div",{className:"space-y-3",children:re.map(se=>a.jsxs(Wn,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("span",{className:"font-medium truncate",children:se.property_address}),se.is_win&&a.jsx(Ww,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),a.jsxs("div",{className:"text-sm text-muted-foreground",children:[se.city,se.state?`, ${se.state}`:""]})]}),a.jsx(us,{variant:se.transaction_type==="buyer"?"default":"secondary",children:se.transaction_type})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),See(se.close_date)]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Ba(se.sale_price)]}),e&&se.commission_amount&&a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Ba(se.commission_amount)]}),se.lead_source&&a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Source: "}),se.lead_source.name]}),se.contact&&a.jsxs("div",{className:"col-span-2",children:[a.jsx("span",{className:"text-muted-foreground",children:"Client: "}),se.contact.first_name," ",se.contact.last_name]}),n&&a.jsxs("div",{className:"col-span-2",children:[a.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[se.owner_user_id]||"Unknown"]})]}),!i&&a.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[a.jsx(zt,{variant:"ghost",size:"sm",onClick:()=>c(se),children:a.jsx(gU,{className:"h-4 w-4"})}),a.jsx(zt,{variant:"ghost",size:"sm",onClick:()=>Z(se),children:a.jsx(fU,{className:"h-4 w-4"})}),a.jsx(zt,{variant:"ghost",size:"sm",onClick:()=>f(se.id),children:a.jsx(cD,{className:"h-4 w-4 text-destructive"})})]})]},se.id))}):a.jsx("div",{className:"overflow-x-auto",children:a.jsxs(CH,{children:[a.jsx(IH,{children:a.jsxs(Yj,{children:[n&&a.jsx(Hl,{children:"Agent"}),a.jsx(Hl,{children:"Property"}),a.jsx(Hl,{children:"Type"}),a.jsx(Hl,{children:"Close Date"}),a.jsx(Hl,{children:"Sale Price"}),e&&a.jsx(Hl,{children:"Commission"}),a.jsx(Hl,{children:"Lead Source"}),a.jsx(Hl,{children:"Client"}),!i&&a.jsx(Hl,{className:"w-[50px]"})]})}),a.jsx(NH,{children:re.map(se=>{var ue;return a.jsxs(Yj,{children:[n&&a.jsx(Wl,{className:"font-medium text-sm",children:n[se.owner_user_id]||"Unknown"}),a.jsx(Wl,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[se.is_win&&a.jsx(Ww,{className:"h-4 w-4 text-yellow-500"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:se.property_address}),a.jsxs("div",{className:"text-sm text-muted-foreground",children:[se.city,se.state?`, ${se.state}`:""]})]})]})}),a.jsx(Wl,{children:a.jsx(us,{variant:se.transaction_type==="buyer"?"default":"secondary",children:se.transaction_type})}),a.jsx(Wl,{children:See(se.close_date)}),a.jsx(Wl,{children:Ba(se.sale_price)}),e&&a.jsx(Wl,{children:se.commission_amount?Ba(se.commission_amount):"-"}),a.jsx(Wl,{children:((ue=se.lead_source)==null?void 0:ue.name)||"-"}),a.jsx(Wl,{children:se.contact?`${se.contact.first_name} ${se.contact.last_name||""}`.trim():"-"}),!i&&a.jsx(Wl,{children:a.jsxs(mC,{children:[a.jsx(pC,{asChild:!0,children:a.jsx(zt,{variant:"ghost",size:"icon",children:a.jsx(KLe,{className:"h-4 w-4"})})}),a.jsxs(qS,{align:"end",children:[a.jsxs(Eu,{onClick:()=>c(se),children:[a.jsx(gU,{className:"h-4 w-4 mr-2"}),"Edit"]}),a.jsxs(Eu,{onClick:()=>Z(se),children:[a.jsx(fU,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),a.jsxs(Eu,{onClick:()=>f(se.id),className:"text-destructive",children:[a.jsx(cD,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},se.id)})})]})})})]}),a.jsx(Jwe,{open:!!o,onOpenChange:se=>!se&&c(null),transaction:o||void 0}),a.jsx(Hme,{open:!!s,onOpenChange:se=>!se&&f(null),children:a.jsxs(g9,{children:[a.jsxs(y9,{children:[a.jsx(_9,{children:"Delete Transaction?"}),a.jsx(v9,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),a.jsxs(x9,{children:[a.jsx(w9,{children:"Cancel"}),a.jsx(b9,{onClick:Q,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Sit({goals:t,stats:e,year:r,showCommission:n}){const i=new Date().getMonth()+1,o=new Date().getFullYear()===r?i:12,c=12-o,s=(T,E)=>{if(!E||E===0)return null;const k=Math.min(T/E*100,100),P=Math.max(E-T,0),R=c>0?P/c:0,D=o/12*100,M=k>=D?"ahead":k>=D*.8?"on-track":"behind";return{percent:k,remaining:P,pace:R,status:M}},f=s(e.totalTransactions,t.transactions_goal),p=s(e.totalVolume,t.volume_goal),y=n?s(e.totalCommission,t.gci_goal):null,_=T=>{switch(T){case"ahead":return a.jsxs(us,{className:"bg-green-500 text-white",children:[a.jsx(NS,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return a.jsxs(us,{variant:"secondary",children:[a.jsx(uDe,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return a.jsxs(us,{variant:"destructive",children:[a.jsx(qfe,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!t.transactions_goal&&!t.volume_goal&&!t.gci_goal?null:a.jsxs(Wn,{children:[a.jsx(id,{className:"pb-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(l9,{className:"h-5 w-5 text-primary"}),a.jsxs(sd,{children:[r," Goals Progress"]})]})}),a.jsx(si,{children:a.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[t.transactions_goal&&f&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),_(f.status)]}),a.jsx(WA,{value:f.percent,className:"h-2"}),a.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[a.jsxs("span",{children:[e.totalTransactions," of ",t.transactions_goal]}),a.jsxs("span",{children:[Math.round(f.percent),"%"]})]}),f.remaining>0&&c>0&&a.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(f.pace),"/month to hit goal"]})]}),t.volume_goal&&p&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm font-medium",children:"Volume"}),_(p.status)]}),a.jsx(WA,{value:p.percent,className:"h-2"}),a.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[a.jsxs("span",{children:[Ba(e.totalVolume,!0)," of ",Ba(t.volume_goal,!0)]}),a.jsxs("span",{children:[Math.round(p.percent),"%"]})]}),p.remaining>0&&c>0&&a.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Ba(p.pace,!0),"/month"]})]}),n&&t.gci_goal&&y&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm font-medium",children:"GCI"}),_(y.status)]}),a.jsx(WA,{value:y.percent,className:"h-2"}),a.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[a.jsxs("span",{children:[Ba(e.totalCommission,!0)," of ",Ba(t.gci_goal,!0)]}),a.jsxs("span",{children:[Math.round(y.percent),"%"]})]}),y.remaining>0&&c>0&&a.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Ba(y.pace,!0),"/month"]})]})]})})]})}var Tit=Array.isArray,Mu=Tit,Eit=typeof Ql=="object"&&Ql&&Ql.Object===Object&&Ql,t1e=Eit,Ait=t1e,jit=typeof self=="object"&&self&&self.Object===Object&&self,kit=Ait||jit||Function("return this")(),Tm=kit,Cit=Tm,Iit=Cit.Symbol,CC=Iit,yie=CC,r1e=Object.prototype,Nit=r1e.hasOwnProperty,Pit=r1e.toString,K2=yie?yie.toStringTag:void 0;function Rit(t){var e=Nit.call(t,K2),r=t[K2];try{t[K2]=void 0;var n=!0}catch{}var i=Pit.call(t);return n&&(e?t[K2]=r:delete t[K2]),i}var Lit=Rit,Dit=Object.prototype,Mit=Dit.toString;function Oit(t){return Mit.call(t)}var Fit=Oit,xie=CC,Bit=Lit,zit=Fit,$it="[object Null]",Uit="[object Undefined]",_ie=xie?xie.toStringTag:void 0;function Vit(t){return t==null?t===void 0?Uit:$it:_ie&&_ie in Object(t)?Bit(t):zit(t)}var Qp=Vit;function qit(t){return t!=null&&typeof t=="object"}var Jp=qit,Git=Qp,Hit=Jp,Wit="[object Symbol]";function Kit(t){return typeof t=="symbol"||Hit(t)&&Git(t)==Wit}var JS=Kit,Yit=Mu,Zit=JS,Xit=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Qit=/^\w*$/;function Jit(t,e){if(Yit(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||Zit(t)?!0:Qit.test(t)||!Xit.test(t)||e!=null&&t in Object(e)}var LH=Jit;function est(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Ax=est;const eT=ds(Ax);var tst=Qp,rst=Ax,nst="[object AsyncFunction]",ist="[object Function]",sst="[object GeneratorFunction]",ast="[object Proxy]";function ost(t){if(!rst(t))return!1;var e=tst(t);return e==ist||e==sst||e==nst||e==ast}var DH=ost;const _i=ds(DH);var lst=Tm,cst=lst["__core-js_shared__"],ust=cst,Qz=ust,vie=function(){var t=/[^.]+$/.exec(Qz&&Qz.keys&&Qz.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function dst(t){return!!vie&&vie in t}var hst=dst,fst=Function.prototype,mst=fst.toString;function pst(t){if(t!=null){try{return mst.call(t)}catch{}try{return t+""}catch{}}return""}var n1e=pst,gst=DH,yst=hst,xst=Ax,_st=n1e,vst=/[\\^$.*+?()[\]{}|]/g,bst=/^\[object .+?Constructor\]$/,wst=Function.prototype,Sst=Object.prototype,Tst=wst.toString,Est=Sst.hasOwnProperty,Ast=RegExp("^"+Tst.call(Est).replace(vst,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jst(t){if(!xst(t)||yst(t))return!1;var e=gst(t)?Ast:bst;return e.test(_st(t))}var kst=jst;function Cst(t,e){return t==null?void 0:t[e]}var Ist=Cst,Nst=kst,Pst=Ist;function Rst(t,e){var r=Pst(t,e);return Nst(r)?r:void 0}var uv=Rst,Lst=uv,Dst=Lst(Object,"create"),W3=Dst,bie=W3;function Mst(){this.__data__=bie?bie(null):{},this.size=0}var Ost=Mst;function Fst(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Bst=Fst,zst=W3,$st="__lodash_hash_undefined__",Ust=Object.prototype,Vst=Ust.hasOwnProperty;function qst(t){var e=this.__data__;if(zst){var r=e[t];return r===$st?void 0:r}return Vst.call(e,t)?e[t]:void 0}var Gst=qst,Hst=W3,Wst=Object.prototype,Kst=Wst.hasOwnProperty;function Yst(t){var e=this.__data__;return Hst?e[t]!==void 0:Kst.call(e,t)}var Zst=Yst,Xst=W3,Qst="__lodash_hash_undefined__";function Jst(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Xst&&e===void 0?Qst:e,this}var eat=Jst,tat=Ost,rat=Bst,nat=Gst,iat=Zst,sat=eat;function tT(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var wat=bat,Sat=K3;function Tat(t,e){var r=this.__data__,n=Sat(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var Eat=Tat,Aat=lat,jat=gat,kat=_at,Cat=wat,Iat=Eat;function rT(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e0?1:-1},h_=function(e){return H_(e)&&e.indexOf("%")===e.length-1},Wr=function(e){return Qot(e)&&!IC(e)},rlt=function(e){return Fi(e)},fl=function(e){return Wr(e)||H_(e)},nlt=0,NC=function(e){var r=++nlt;return"".concat(e||"").concat(r)},Xc=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)&&!H_(e))return n;var o;if(h_(e)){var c=e.indexOf("%");o=r*parseFloat(e.slice(0,c))/100}else o=+e;return IC(o)&&(o=n),i&&o>r&&(o=r),o},my=function(e){if(!e)return null;var r=Object.keys(e);return r&&r.length?e[r[0]]:null},ilt=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 dlt(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 s8(t){"@babel/helpers - typeof";return s8=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},s8(t)}var kie={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"},Cp=function(e){return typeof e=="string"?e:e?e.displayName||e.name||"Component":""},Cie=null,e$=null,GH=function t(e){if(e===Cie&&Array.isArray(e$))return e$;var r=[];return I.Children.forEach(e,function(n){Fi(n)||(Wot.isFragment(n)?r=r.concat(t(n.props.children)):r.push(n))}),e$=r,Cie=e,r};function nh(t,e){var r=[],n=[];return Array.isArray(e)?n=e.map(function(i){return Cp(i)}):n=[Cp(e)],GH(t).forEach(function(i){var o=ld(i,"type.displayName")||ld(i,"type.name");n.indexOf(o)!==-1&&r.push(i)}),r}function Qu(t,e){var r=nh(t,e);return r&&r[0]}var Iie=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)},hlt=["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"],flt=function(e){return e&&e.type&&H_(e.type)&&hlt.indexOf(e.type)>=0},OGt=function(e){return e&&s8(e)==="object"&&"clipDot"in e},mlt=function(e,r,n,i){var o,c=(o=Jz==null?void 0:Jz[i])!==null&&o!==void 0?o:[];return r.startsWith("data-")||!_i(e)&&(i&&c.includes(r)||olt.includes(r))||n&&qH.includes(r)},fi=function(e,r,n){if(!e||typeof e=="function"||typeof e=="boolean")return null;var i=e;if(I.isValidElement(e)&&(i=e.props),!eT(i))return null;var o={};return Object.keys(i).forEach(function(c){var s;mlt((s=i)===null||s===void 0?void 0:s[c],c,r,n)&&(o[c]=i[c])}),o},a8=function t(e,r){if(e===r)return!0;var n=I.Children.count(e);if(n!==I.Children.count(r))return!1;if(n===0)return!0;if(n===1)return Nie(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 _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}function l8(t){var e=t.children,r=t.width,n=t.height,i=t.viewBox,o=t.className,c=t.style,s=t.title,f=t.desc,p=xlt(t,ylt),y=i||{width:r,height:n,x:0,y:0},_=Oi("recharts-surface",o);return Xe.createElement("svg",o8({},fi(p,!0,"svg"),{className:_,width:r,height:n,style:c,viewBox:"".concat(y.x," ").concat(y.y," ").concat(y.width," ").concat(y.height)}),Xe.createElement("title",null,s),Xe.createElement("desc",null,f),e)}var vlt=["children","className"];function c8(){return c8=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 wlt(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 $s=Xe.forwardRef(function(t,e){var r=t.children,n=t.className,i=blt(t,vlt),o=Oi("recharts-layer",n);return Xe.createElement("g",c8({className:o},fi(i,!0),{ref:e}),r)}),sf=function(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;oi?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var o=Array(i);++n=n?t:Elt(t,e,r)}var jlt=Alt,klt="\\ud800-\\udfff",Clt="\\u0300-\\u036f",Ilt="\\ufe20-\\ufe2f",Nlt="\\u20d0-\\u20ff",Plt=Clt+Ilt+Nlt,Rlt="\\ufe0e\\ufe0f",Llt="\\u200d",Dlt=RegExp("["+Llt+klt+Plt+Rlt+"]");function Mlt(t){return Dlt.test(t)}var f1e=Mlt;function Olt(t){return t.split("")}var Flt=Olt,m1e="\\ud800-\\udfff",Blt="\\u0300-\\u036f",zlt="\\ufe20-\\ufe2f",$lt="\\u20d0-\\u20ff",Ult=Blt+zlt+$lt,Vlt="\\ufe0e\\ufe0f",qlt="["+m1e+"]",u8="["+Ult+"]",d8="\\ud83c[\\udffb-\\udfff]",Glt="(?:"+u8+"|"+d8+")",p1e="[^"+m1e+"]",g1e="(?:\\ud83c[\\udde6-\\uddff]){2}",y1e="[\\ud800-\\udbff][\\udc00-\\udfff]",Hlt="\\u200d",x1e=Glt+"?",_1e="["+Vlt+"]?",Wlt="(?:"+Hlt+"(?:"+[p1e,g1e,y1e].join("|")+")"+_1e+x1e+")*",Klt=_1e+x1e+Wlt,Ylt="(?:"+[p1e+u8+"?",u8,g1e,y1e,qlt].join("|")+")",Zlt=RegExp(d8+"(?="+d8+")|"+Ylt+Klt,"g");function Xlt(t){return t.match(Zlt)||[]}var Qlt=Xlt,Jlt=Flt,ect=f1e,tct=Qlt;function rct(t){return ect(t)?tct(t):Jlt(t)}var nct=rct,ict=jlt,sct=f1e,act=nct,oct=o1e;function lct(t){return function(e){e=oct(e);var r=sct(e)?act(e):void 0,n=r?r[0]:e.charAt(0),i=r?ict(r,1).join(""):e.slice(1);return n[t]()+i}}var cct=lct,uct=cct,dct=uct("toUpperCase"),hct=dct;const lF=ds(hct);function ga(t){return function(){return t}}const v1e=Math.cos,eM=Math.sin,hf=Math.sqrt,tM=Math.PI,cF=2*tM,h8=Math.PI,f8=2*h8,J0=1e-6,fct=f8-J0;function b1e(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return b1e;const r=10**e;return function(n){this._+=n[0];for(let i=1,o=n.length;iJ0)if(!(Math.abs(_*f-p*y)>J0)||!o)this._append`L${this._x1=e},${this._y1=r}`;else{let E=n-c,k=i-s,P=f*f+p*p,R=E*E+k*k,D=Math.sqrt(P),M=Math.sqrt(T),B=o*Math.tan((h8-Math.acos((P+T-R)/(2*D*M)))/2),V=B/M,G=B/D;Math.abs(V-1)>J0&&this._append`L${e+V*y},${r+V*_}`,this._append`A${o},${o},0,0,${+(_*E>y*k)},${this._x1=e+G*f},${this._y1=r+G*p}`}}arc(e,r,n,i,o,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),p=e+s,y=r+f,_=1^c,T=c?i-o:o-i;this._x1===null?this._append`M${p},${y}`:(Math.abs(this._x1-p)>J0||Math.abs(this._y1-y)>J0)&&this._append`L${p},${y}`,n&&(T<0&&(T=T%f8+f8),T>fct?this._append`A${n},${n},0,1,${_},${e-s},${r-f}A${n},${n},0,1,${_},${this._x1=p},${this._y1=y}`:T>J0&&this._append`A${n},${n},0,${+(T>=h8)},${_},${this._x1=e+n*Math.cos(o)},${this._y1=r+n*Math.sin(o)}`)}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 HH(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 pct(e)}function WH(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function w1e(t){this._context=t}w1e.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 uF(t){return new w1e(t)}function S1e(t){return t[0]}function T1e(t){return t[1]}function E1e(t,e){var r=ga(!0),n=null,i=uF,o=null,c=HH(s);t=typeof t=="function"?t:t===void 0?S1e:ga(t),e=typeof e=="function"?e:e===void 0?T1e:ga(e);function s(f){var p,y=(f=WH(f)).length,_,T=!1,E;for(n==null&&(o=i(E=c())),p=0;p<=y;++p)!(p=E;--k)s.point(B[k],V[k]);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 y(){return E1e().defined(i).curve(c).context(o)}return p.x=function(_){return arguments.length?(t=typeof _=="function"?_:ga(+_),n=null,p):t},p.x0=function(_){return arguments.length?(t=typeof _=="function"?_:ga(+_),p):t},p.x1=function(_){return arguments.length?(n=_==null?null:typeof _=="function"?_:ga(+_),p):n},p.y=function(_){return arguments.length?(e=typeof _=="function"?_:ga(+_),r=null,p):e},p.y0=function(_){return arguments.length?(e=typeof _=="function"?_:ga(+_),p):e},p.y1=function(_){return arguments.length?(r=_==null?null:typeof _=="function"?_:ga(+_),p):r},p.lineX0=p.lineY0=function(){return y().x(t).y(e)},p.lineY1=function(){return y().x(t).y(r)},p.lineX1=function(){return y().x(n).y(e)},p.defined=function(_){return arguments.length?(i=typeof _=="function"?_:ga(!!_),p):i},p.curve=function(_){return arguments.length?(c=_,o!=null&&(s=c(o)),p):c},p.context=function(_){return arguments.length?(_==null?o=s=null:s=c(o=_),p):o},p}class A1e{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 gct(t){return new A1e(t,!0)}function yct(t){return new A1e(t,!1)}const KH={draw(t,e){const r=hf(e/tM);t.moveTo(r,0),t.arc(0,0,r,0,cF)}},xct={draw(t,e){const r=hf(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()}},j1e=hf(1/3),_ct=j1e*2,vct={draw(t,e){const r=hf(e/_ct),n=r*j1e;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},bct={draw(t,e){const r=hf(e),n=-r/2;t.rect(n,n,r,r)}},wct=.8908130915292852,k1e=eM(tM/10)/eM(7*tM/10),Sct=eM(cF/10)*k1e,Tct=-v1e(cF/10)*k1e,Ect={draw(t,e){const r=hf(e*wct),n=Sct*r,i=Tct*r;t.moveTo(0,-r),t.lineTo(n,i);for(let o=1;o<5;++o){const c=cF*o/5,s=v1e(c),f=eM(c);t.lineTo(f*r,-s*r),t.lineTo(s*n-f*i,f*n+s*i)}t.closePath()}},t$=hf(3),Act={draw(t,e){const r=-hf(e/(t$*3));t.moveTo(0,r*2),t.lineTo(-t$*r,-r),t.lineTo(t$*r,-r),t.closePath()}},Bd=-.5,zd=hf(3)/2,m8=1/hf(12),jct=(m8/2+1)*3,kct={draw(t,e){const r=hf(e/jct),n=r/2,i=r*m8,o=n,c=r*m8+r,s=-o,f=c;t.moveTo(n,i),t.lineTo(o,c),t.lineTo(s,f),t.lineTo(Bd*n-zd*i,zd*n+Bd*i),t.lineTo(Bd*o-zd*c,zd*o+Bd*c),t.lineTo(Bd*s-zd*f,zd*s+Bd*f),t.lineTo(Bd*n+zd*i,Bd*i-zd*n),t.lineTo(Bd*o+zd*c,Bd*c-zd*o),t.lineTo(Bd*s+zd*f,Bd*f-zd*s),t.closePath()}};function Cct(t,e){let r=null,n=HH(i);t=typeof t=="function"?t:ga(t||KH),e=typeof e=="function"?e:ga(e===void 0?64:+e);function i(){let o;if(r||(r=o=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),o)return r=null,o+""||null}return i.type=function(o){return arguments.length?(t=typeof o=="function"?o:ga(o),i):t},i.size=function(o){return arguments.length?(e=typeof o=="function"?o:ga(+o),i):e},i.context=function(o){return arguments.length?(r=o??null,i):r},i}function rM(){}function nM(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 C1e(t){this._context=t}C1e.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:nM(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:nM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Ict(t){return new C1e(t)}function I1e(t){this._context=t}I1e.prototype={areaStart:rM,areaEnd:rM,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:nM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Nct(t){return new I1e(t)}function N1e(t){this._context=t}N1e.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:nM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Pct(t){return new N1e(t)}function P1e(t){this._context=t}P1e.prototype={areaStart:rM,areaEnd:rM,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 Rct(t){return new P1e(t)}function Rie(t){return t<0?-1:1}function Lie(t,e,r){var n=t._x1-t._x0,i=e-t._x1,o=(t._y1-t._y0)/(n||i<0&&-0),c=(r-t._y1)/(i||n<0&&-0),s=(o*i+c*n)/(n+i);return(Rie(o)+Rie(c))*Math.min(Math.abs(o),Math.abs(c),.5*Math.abs(s))||0}function Die(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function r$(t,e,r){var n=t._x0,i=t._y0,o=t._x1,c=t._y1,s=(o-n)/3;t._context.bezierCurveTo(n+s,i+s*e,o-s,c-s*r,o,c)}function iM(t){this._context=t}iM.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:r$(this,this._t0,Die(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,r$(this,Die(this,r=Lie(this,t,e)),r);break;default:r$(this,this._t0,r=Lie(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}};function R1e(t){this._context=new L1e(t)}(R1e.prototype=Object.create(iM.prototype)).point=function(t,e){iM.prototype.point.call(this,e,t)};function L1e(t){this._context=t}L1e.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,o){this._context.bezierCurveTo(e,t,n,r,o,i)}};function Lct(t){return new iM(t)}function Dct(t){return new R1e(t)}function D1e(t){this._context=t}D1e.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=Mie(t),i=Mie(e),o=0,c=1;c=0;--e)i[e]=(c[e]-i[e+1])/o[e];for(o[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 Oct(t){return new dF(t,.5)}function Fct(t){return new dF(t,0)}function Bct(t){return new dF(t,1)}function X1(t,e){if((c=t.length)>1)for(var r=1,n,i,o=t[e[0]],c,s=o.length;r=0;)r[e]=e;return r}function zct(t,e){return t[e]}function $ct(t){const e=[];return e.key=t,e}function Uct(){var t=ga([]),e=p8,r=X1,n=zct;function i(o){var c=Array.from(t.apply(this,arguments),$ct),s,f=c.length,p=-1,y;for(const _ of o)for(s=0,++p;s0){for(var r,n,i=0,o=t[0].length,c;i0){for(var r=0,n=t[e[0]],i,o=n.length;r0)||!((o=(i=t[e[0]]).length)>0))){for(var r=0,n=1,i,o,c;n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Xct(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 M1e={symbolCircle:KH,symbolCross:xct,symbolDiamond:vct,symbolSquare:bct,symbolStar:Ect,symbolTriangle:Act,symbolWye:kct},Qct=Math.PI/180,Jct=function(e){var r="symbol".concat(lF(e));return M1e[r]||KH},eut=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*Qct;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}},tut=function(e,r){M1e["symbol".concat(lF(e))]=r},YH=function(e){var r=e.type,n=r===void 0?"circle":r,i=e.size,o=i===void 0?64:i,c=e.sizeType,s=c===void 0?"area":c,f=Zct(e,Hct),p=Fie(Fie({},f),{},{type:n,size:o,sizeType:s}),y=function(){var R=Jct(n),D=Cct().type(R).size(eut(o,s,n));return D()},_=p.className,T=p.cx,E=p.cy,k=fi(p,!0);return T===+T&&E===+E&&o===+o?Xe.createElement("path",g8({},k,{className:Oi("recharts-symbols",_),transform:"translate(".concat(T,", ").concat(E,")"),d:y()})):null};YH.registerSymbol=tut;function Q1(t){"@babel/helpers - typeof";return Q1=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},Q1(t)}function y8(){return y8=Object.assign?Object.assign.bind():function(t){for(var e=1;e`);var M=E.inactive?p:E.color;return Xe.createElement("li",y8({className:R,style:_,key:"legend-item-".concat(k)},W_(n.props,E,k)),Xe.createElement(l8,{width:c,height:c,viewBox:y,style:T},n.renderIcon(E)),Xe.createElement("span",{className:"recharts-legend-item-text",style:{color:M}},P?P(D,E,k):D))})}},{key:"render",value:function(){var n=this.props,i=n.payload,o=n.layout,c=n.align;if(!i||!i.length)return null;var s={padding:0,margin:0,textAlign:o==="horizontal"?c:"left"};return Xe.createElement("ul",{className:"recharts-default-legend",style:s},this.renderItems())}}])}(I.PureComponent);Xj(ZH,"displayName","Legend");Xj(ZH,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var dut=Y3;function hut(){this.__data__=new dut,this.size=0}var fut=hut;function mut(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var put=mut;function gut(t){return this.__data__.get(t)}var yut=gut;function xut(t){return this.__data__.has(t)}var _ut=xut,vut=Y3,but=OH,wut=FH,Sut=200;function Tut(t,e){var r=this.__data__;if(r instanceof vut){var n=r.__data__;if(!but||n.lengths))return!1;var p=o.get(t),y=o.get(e);if(p&&y)return p==e&&y==t;var _=-1,T=!0,E=r&Hut?new Uut:void 0;for(o.set(t,e),o.set(e,t);++_-1&&t%1==0&&t-1&&t%1==0&&t<=Zdt}var eW=Xdt,Qdt=Qp,Jdt=eW,eht=Jp,tht="[object Arguments]",rht="[object Array]",nht="[object Boolean]",iht="[object Date]",sht="[object Error]",aht="[object Function]",oht="[object Map]",lht="[object Number]",cht="[object Object]",uht="[object RegExp]",dht="[object Set]",hht="[object String]",fht="[object WeakMap]",mht="[object ArrayBuffer]",pht="[object DataView]",ght="[object Float32Array]",yht="[object Float64Array]",xht="[object Int8Array]",_ht="[object Int16Array]",vht="[object Int32Array]",bht="[object Uint8Array]",wht="[object Uint8ClampedArray]",Sht="[object Uint16Array]",Tht="[object Uint32Array]",Ia={};Ia[ght]=Ia[yht]=Ia[xht]=Ia[_ht]=Ia[vht]=Ia[bht]=Ia[wht]=Ia[Sht]=Ia[Tht]=!0;Ia[tht]=Ia[rht]=Ia[mht]=Ia[nht]=Ia[pht]=Ia[iht]=Ia[sht]=Ia[aht]=Ia[oht]=Ia[lht]=Ia[cht]=Ia[uht]=Ia[dht]=Ia[hht]=Ia[fht]=!1;function Eht(t){return eht(t)&&Jdt(t.length)&&!!Ia[Qdt(t)]}var Aht=Eht;function jht(t){return function(e){return t(e)}}var W1e=jht,lM={exports:{}};lM.exports;(function(t,e){var r=t1e,n=e&&!e.nodeType&&e,i=n&&!0&&t&&!t.nodeType&&t,o=i&&i.exports===n,c=o&&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})(lM,lM.exports);var kht=lM.exports,Cht=Aht,Iht=W1e,Gie=kht,Hie=Gie&&Gie.isTypedArray,Nht=Hie?Iht(Hie):Cht,K1e=Nht,Pht=Ddt,Rht=QH,Lht=Mu,Dht=H1e,Mht=JH,Oht=K1e,Fht=Object.prototype,Bht=Fht.hasOwnProperty;function zht(t,e){var r=Lht(t),n=!r&&Rht(t),i=!r&&!n&&Dht(t),o=!r&&!n&&!i&&Oht(t),c=r||n||i||o,s=c?Pht(t.length,String):[],f=s.length;for(var p in t)(e||Bht.call(t,p))&&!(c&&(p=="length"||i&&(p=="offset"||p=="parent")||o&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||Mht(p,f)))&&s.push(p);return s}var $ht=zht,Uht=Object.prototype;function Vht(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Uht;return t===r}var qht=Vht;function Ght(t,e){return function(r){return t(e(r))}}var Y1e=Ght,Hht=Y1e,Wht=Hht(Object.keys,Object),Kht=Wht,Yht=qht,Zht=Kht,Xht=Object.prototype,Qht=Xht.hasOwnProperty;function Jht(t){if(!Yht(t))return Zht(t);var e=[];for(var r in Object(t))Qht.call(t,r)&&r!="constructor"&&e.push(r);return e}var eft=Jht,tft=DH,rft=eW;function nft(t){return t!=null&&rft(t.length)&&!tft(t)}var PC=nft,ift=$ht,sft=eft,aft=PC;function oft(t){return aft(t)?ift(t):sft(t)}var hF=oft,lft=Sdt,cft=Rdt,uft=hF;function dft(t){return lft(t,uft,cft)}var hft=dft,Wie=hft,fft=1,mft=Object.prototype,pft=mft.hasOwnProperty;function gft(t,e,r,n,i,o){var c=r&fft,s=Wie(t),f=s.length,p=Wie(e),y=p.length;if(f!=y&&!c)return!1;for(var _=f;_--;){var T=s[_];if(!(c?T in e:pft.call(e,T)))return!1}var E=o.get(t),k=o.get(e);if(E&&k)return E==e&&k==t;var P=!0;o.set(t,e),o.set(e,t);for(var R=c;++_-1}var mpt=fpt;function ppt(t,e,r){for(var n=-1,i=t==null?0:t.length;++n=Ipt){var p=e?null:kpt(t);if(p)return Cpt(p);c=!1,i=jpt,f=new Tpt}else f=e?[]:s;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Hpt(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 Wpt(t){return t.value}function Kpt(t,e){if(Xe.isValidElement(t))return Xe.cloneElement(t,e);if(typeof t=="function")return Xe.createElement(t,e);e.ref;var r=Gpt(e,Opt);return Xe.createElement(ZH,r)}var cse=1,n1=function(t){function e(){var r;Fpt(this,e);for(var n=arguments.length,i=new Array(n),o=0;ocse||Math.abs(i.height-this.lastBoundingBox.height)>cse)&&(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?ap({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,o=i.layout,c=i.align,s=i.verticalAlign,f=i.margin,p=i.chartWidth,y=i.chartHeight,_,T;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(c==="center"&&o==="vertical"){var E=this.getBBoxSnapshot();_={left:((p||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 k=this.getBBoxSnapshot();T={top:((y||0)-k.height)/2}}else T=s==="bottom"?{bottom:f&&f.bottom||0}:{top:f&&f.top||0};return ap(ap({},_),T)}},{key:"render",value:function(){var n=this,i=this.props,o=i.content,c=i.width,s=i.height,f=i.wrapperStyle,p=i.payloadUniqBy,y=i.payload,_=ap(ap({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}},Kpt(o,ap(ap({},this.props),{},{payload:rSe(y,p,Wpt)})))}}],[{key:"getWithHeight",value:function(n,i){var o=ap(ap({},this.defaultProps),n.props),c=o.layout;return c==="vertical"&&Wr(n.props.height)?{height:n.props.height}:c==="horizontal"?{width:n.props.width||i}:null}}])}(I.PureComponent);fF(n1,"displayName","Legend");fF(n1,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var use=CC,Ypt=QH,Zpt=Mu,dse=use?use.isConcatSpreadable:void 0;function Xpt(t){return Zpt(t)||Ypt(t)||!!(dse&&t&&t[dse])}var Qpt=Xpt,Jpt=q1e,egt=Qpt;function sSe(t,e,r,n,i){var o=-1,c=t.length;for(r||(r=egt),i||(i=[]);++o0&&r(s)?e>1?sSe(s,e-1,r,n,i):Jpt(i,s):n||(i[i.length]=s)}return i}var aSe=sSe;function tgt(t){return function(e,r,n){for(var i=-1,o=Object(e),c=n(e),s=c.length;s--;){var f=c[t?s:++i];if(r(o[f],f,o)===!1)break}return e}}var rgt=tgt,ngt=rgt,igt=ngt(),sgt=igt,agt=sgt,ogt=hF;function lgt(t,e){return t&&agt(t,e,ogt)}var oSe=lgt,cgt=PC;function ugt(t,e){return function(r,n){if(r==null)return r;if(!cgt(r))return t(r,n);for(var i=r.length,o=e?i:-1,c=Object(r);(e?o--:++oe||o&&c&&f&&!s&&!p||n&&c&&f||!r&&f||!i)return 1;if(!n&&!o&&!p&&t=s)return f;var p=r[n];return f*(p=="desc"?-1:1)}}return t.index-e.index}var Tgt=Sgt,a$=zH,Egt=$H,Agt=Em,jgt=lSe,kgt=_gt,Cgt=W1e,Igt=Tgt,Ngt=aT,Pgt=Mu;function Rgt(t,e,r){e.length?e=a$(e,function(o){return Pgt(o)?function(c){return Egt(c,o.length===1?o[0]:o)}:o}):e=[Ngt];var n=-1;e=a$(e,Cgt(Agt));var i=jgt(t,function(o,c,s){var f=a$(e,function(p){return p(o)});return{criteria:f,index:++n,value:o}});return kgt(i,function(o,c){return Igt(o,c,r)})}var Lgt=Rgt;function Dgt(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 Mgt=Dgt,Ogt=Mgt,fse=Math.max;function Fgt(t,e,r){return e=fse(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,o=fse(n.length-e,0),c=Array(o);++i0){if(++e>=Kgt)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var Qgt=Xgt,Jgt=Wgt,eyt=Qgt,tyt=eyt(Jgt),ryt=tyt,nyt=aT,iyt=Bgt,syt=ryt;function ayt(t,e){return syt(iyt(t,e,nyt),t+"")}var oyt=ayt,lyt=MH,cyt=PC,uyt=JH,dyt=Ax;function hyt(t,e,r){if(!dyt(r))return!1;var n=typeof e;return(n=="number"?cyt(r)&&uyt(e,r.length):n=="string"&&e in r)?lyt(r[e],t):!1}var mF=hyt,fyt=aSe,myt=Lgt,pyt=oyt,pse=mF,gyt=pyt(function(t,e){if(t==null)return[];var r=e.length;return r>1&&pse(t,e[0],e[1])?e=[]:r>2&&pse(e[0],e[1],e[2])&&(e=[e[0]]),myt(t,fyt(e,1),[])}),yyt=gyt;const nW=ds(yyt);function Qj(t){"@babel/helpers - typeof";return Qj=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},Qj(t)}function E8(){return E8=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(Y2,"-left"),Wr(r)&&e&&Wr(e.x)&&r=e.y),"".concat(Y2,"-top"),Wr(n)&&e&&Wr(e.y)&&nP?Math.max(y,f[n]):Math.max(_,f[n])}function Pyt(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 Ryt(t){var e=t.allowEscapeViewBox,r=t.coordinate,n=t.offsetTopLeft,i=t.position,o=t.reverseDirection,c=t.tooltipBox,s=t.useTranslate3d,f=t.viewBox,p,y,_;return c.height>0&&c.width>0&&r?(y=xse({allowEscapeViewBox:e,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.width,viewBox:f,viewBoxDimension:f.width}),_=xse({allowEscapeViewBox:e,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.height,viewBox:f,viewBoxDimension:f.height}),p=Pyt({translateX:y,translateY:_,useTranslate3d:s})):p=Iyt,{cssProperties:p,cssClasses:Nyt({translateX:y,translateY:_,coordinate:r})}}function eS(t){"@babel/helpers - typeof";return eS=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},eS(t)}function _se(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 vse(t){for(var e=1;ebse||Math.abs(n.height-this.state.lastBoundingBox.height)>bse)&&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,o=i.active,c=i.allowEscapeViewBox,s=i.animationDuration,f=i.animationEasing,p=i.children,y=i.coordinate,_=i.hasPayload,T=i.isAnimationActive,E=i.offset,k=i.position,P=i.reverseDirection,R=i.useTranslate3d,D=i.viewBox,M=i.wrapperStyle,B=Ryt({allowEscapeViewBox:c,coordinate:y,offsetTopLeft:E,position:k,reverseDirection:P,tooltipBox:this.state.lastBoundingBox,useTranslate3d:R,viewBox:D}),V=B.cssClasses,G=B.cssProperties,W=vse(vse({transition:T&&o?"transform ".concat(s,"ms ").concat(f):void 0},G),{},{pointerEvents:"none",visibility:!this.state.dismissed&&o&&_?"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}},p)}}])}(I.PureComponent),Vyt=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Ip={isSsr:Vyt(),get:function(e){return Ip[e]},set:function(e,r){if(typeof e=="string")Ip[e]=r;else{var n=Object.keys(e);n&&n.length&&n.forEach(function(i){Ip[i]=e[i]})}}};function tS(t){"@babel/helpers - typeof";return tS=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},tS(t)}function wse(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 Sse(t){for(var e=1;e0;return Xe.createElement(Uyt,{allowEscapeViewBox:c,animationDuration:s,animationEasing:f,isAnimationActive:T,active:o,coordinate:y,hasPayload:W,offset:E,position:R,reverseDirection:D,useTranslate3d:M,viewBox:B,wrapperStyle:V},Jyt(p,Sse(Sse({},this.props),{},{payload:G})))}}])}(I.PureComponent);iW(Vh,"displayName","Tooltip");iW(Vh,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Ip.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 ext=Tm,txt=function(){return ext.Date.now()},rxt=txt,nxt=/\s/;function ixt(t){for(var e=t.length;e--&&nxt.test(t.charAt(e)););return e}var sxt=ixt,axt=sxt,oxt=/^\s+/;function lxt(t){return t&&t.slice(0,axt(t)+1).replace(oxt,"")}var cxt=lxt,uxt=cxt,Tse=Ax,dxt=JS,Ese=NaN,hxt=/^[-+]0x[0-9a-f]+$/i,fxt=/^0b[01]+$/i,mxt=/^0o[0-7]+$/i,pxt=parseInt;function gxt(t){if(typeof t=="number")return t;if(dxt(t))return Ese;if(Tse(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Tse(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=uxt(t);var r=fxt.test(t);return r||mxt.test(t)?pxt(t.slice(2),r?2:8):hxt.test(t)?Ese:+t}var mSe=gxt,yxt=Ax,l$=rxt,Ase=mSe,xxt="Expected a function",_xt=Math.max,vxt=Math.min;function bxt(t,e,r){var n,i,o,c,s,f,p=0,y=!1,_=!1,T=!0;if(typeof t!="function")throw new TypeError(xxt);e=Ase(e)||0,yxt(r)&&(y=!!r.leading,_="maxWait"in r,o=_?_xt(Ase(r.maxWait)||0,e):o,T="trailing"in r?!!r.trailing:T);function E(W){var Z=n,Q=i;return n=i=void 0,p=W,c=t.apply(Q,Z),c}function k(W){return p=W,s=setTimeout(D,e),y?E(W):c}function P(W){var Z=W-f,Q=W-p,re=e-Z;return _?vxt(re,o-Q):re}function R(W){var Z=W-f,Q=W-p;return f===void 0||Z>=e||Z<0||_&&Q>=o}function D(){var W=l$();if(R(W))return M(W);s=setTimeout(D,P(W))}function M(W){return s=void 0,T&&n?E(W):(n=i=void 0,c)}function B(){s!==void 0&&clearTimeout(s),p=0,n=f=i=s=void 0}function V(){return s===void 0?c:M(l$())}function G(){var W=l$(),Z=R(W);if(n=arguments,i=this,f=W,Z){if(s===void 0)return k(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 wxt=bxt,Sxt=wxt,Txt=Ax,Ext="Expected a function";function Axt(t,e,r){var n=!0,i=!0;if(typeof t!="function")throw new TypeError(Ext);return Txt(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),Sxt(t,e,{leading:n,maxWait:e,trailing:i})}var jxt=Axt;const pSe=ds(jxt);function ek(t){"@babel/helpers - typeof";return ek=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},ek(t)}function jse(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 aR(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&(we=pSe(we,P,{trailing:!0,leading:!1}));var Ce=new ResizeObserver(we),Me=G.current.getBoundingClientRect(),Ae=Me.width,be=Me.height;return ue(Ae,be),Ce.observe(G.current),function(){Ce.disconnect()}},[ue,P]);var _e=I.useMemo(function(){var we=re.containerWidth,Ce=re.containerHeight;if(we<0||Ce<0)return null;sf(h_(c)||h_(f),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,c,f),sf(!r||r>0,"The aspect(%s) must be greater than zero.",r);var Me=h_(c)?we:c,Ae=h_(f)?Ce:f;r&&r>0&&(Me?Ae=Me/r:Ae&&(Me=Ae*r),T&&Ae>T&&(Ae=T)),sf(Me>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.`,Me,Ae,c,f,y,_,r);var be=!Array.isArray(E)&&Cp(E.type).endsWith("Chart");return Xe.Children.map(E,function(me){return Xe.isValidElement(me)?I.cloneElement(me,aR({width:Me,height:Ae},be?{style:aR({height:"100%",width:"100%",maxHeight:Ae,maxWidth:Me},me.props.style)}:{})):me})},[r,E,f,T,_,y,re,c]);return Xe.createElement("div",{id:R?"".concat(R):void 0,className:Oi("recharts-responsive-container",D),style:aR(aR({},V),{},{width:c,height:f,minWidth:y,minHeight:_,maxHeight:T}),ref:G},_e)}),pF=function(e){return null};pF.displayName="Cell";function tk(t){"@babel/helpers - typeof";return tk=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},tk(t)}function Cse(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 I8(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Ip.isSsr)return{width:0,height:0};var n=$xt(r),i=JSON.stringify({text:e,copyStyle:n});if(iw.widthCache[i])return iw.widthCache[i];try{var o=document.getElementById(Ise);o||(o=document.createElement("span"),o.setAttribute("id",Ise),o.setAttribute("aria-hidden","true"),document.body.appendChild(o));var c=I8(I8({},zxt),n);Object.assign(o.style,c),o.textContent="".concat(e);var s=o.getBoundingClientRect(),f={width:s.width,height:s.height};return iw.widthCache[i]=f,++iw.cacheCount>Bxt&&(iw.cacheCount=0,iw.widthCache={}),f}catch{return{width:0,height:0}}},Uxt=function(e){return{top:e.top+window.scrollY-document.documentElement.clientTop,left:e.left+window.scrollX-document.documentElement.clientLeft}};function rk(t){"@babel/helpers - typeof";return rk=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},rk(t)}function hM(t,e){return Hxt(t)||Gxt(t,e)||qxt(t,e)||Vxt()}function Vxt(){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 qxt(t,e){if(t){if(typeof t=="string")return Nse(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 Nse(t,e)}}function Nse(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 a0t(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 Ose(t,e){return u0t(t)||c0t(t,e)||l0t(t,e)||o0t()}function o0t(){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 l0t(t,e){if(t){if(typeof t=="string")return Fse(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 Fse(t,e)}}function Fse(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 Me.reduce(function(Ae,be){var me=be.word,Pe=be.width,Ie=Ae[Ae.length-1];if(Ie&&(i==null||o||Ie.width+Pe+nbe.width?Ae:be})};if(!y)return E;for(var P="…",R=function(Me){var Ae=_.slice(0,Me),be=_Se({breakAll:p,style:f,children:Ae+P}).wordsWithComputedWidth,me=T(be),Pe=me.length>c||k(me).width>Number(i);return[Pe,me]},D=0,M=_.length-1,B=0,V;D<=M&&B<=_.length-1;){var G=Math.floor((D+M)/2),W=G-1,Z=R(W),Q=Ose(Z,2),re=Q[0],se=Q[1],ue=R(G),_e=Ose(ue,1),we=_e[0];if(!re&&!we&&(D=G+1),re&&we&&(M=G-1),!re&&we){V=se;break}B++}return V||E},Bse=function(e){var r=Fi(e)?[]:e.toString().split(xSe);return[{words:r}]},h0t=function(e){var r=e.width,n=e.scaleToFit,i=e.children,o=e.style,c=e.breakAll,s=e.maxLines;if((r||n)&&!Ip.isSsr){var f,p,y=_Se({breakAll:c,children:i,style:o});if(y){var _=y.wordsWithComputedWidth,T=y.spaceWidth;f=_,p=T}else return Bse(i);return d0t({breakAll:c,children:i,maxLines:s,style:o},f,p,r,n)}return Bse(i)},zse="#808080",K_=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.lineHeight,s=c===void 0?"1em":c,f=e.capHeight,p=f===void 0?"0.71em":f,y=e.scaleToFit,_=y===void 0?!1:y,T=e.textAnchor,E=T===void 0?"start":T,k=e.verticalAnchor,P=k===void 0?"end":k,R=e.fill,D=R===void 0?zse:R,M=Mse(e,i0t),B=I.useMemo(function(){return h0t({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,Z=M.className,Q=M.breakAll,re=Mse(M,s0t);if(!fl(n)||!fl(o))return null;var se=n+(Wr(V)?V:0),ue=o+(Wr(G)?G:0),_e;switch(P){case"start":_e=c$("calc(".concat(p,")"));break;case"middle":_e=c$("calc(".concat((B.length-1)/2," * -").concat(s," + (").concat(p," / 2))"));break;default:_e=c$("calc(".concat(B.length-1," * -").concat(s,")"));break}var we=[];if(_){var Ce=B[0].width,Me=M.width;we.push("scale(".concat((Wr(Me)?Me/Ce:1)/Ce,")"))}return W&&we.push("rotate(".concat(W,", ").concat(se,", ").concat(ue,")")),we.length&&(re.transform=we.join(" ")),Xe.createElement("text",N8({},fi(re,!0),{x:se,y:ue,className:Oi("recharts-text",Z),textAnchor:E,fill:D.includes("url")?zse:D}),B.map(function(Ae,be){var me=Ae.words.join(Q?"":" ");return Xe.createElement("tspan",{x:se,dy:be===0?_e:s,key:"".concat(me,"-").concat(be)},me)}))};function Vy(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function f0t(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function sW(t){let e,r,n;t.length!==2?(e=Vy,r=(s,f)=>Vy(t(s),f),n=(s,f)=>t(s)-f):(e=t===Vy||t===f0t?t:m0t,r=t,n=t);function i(s,f,p=0,y=s.length){if(p>>1;r(s[_],f)<0?p=_+1:y=_}while(p>>1;r(s[_],f)<=0?p=_+1:y=_}while(pp&&n(s[_-1],f)>-n(s[_],f)?_-1:_}return{left:i,center:c,right:o}}function m0t(){return 0}function vSe(t){return t===null?NaN:+t}function*p0t(t,e){for(let r of t)r!=null&&(r=+r)>=r&&(yield r)}const g0t=sW(Vy),RC=g0t.right;sW(vSe).center;class $se extends Map{constructor(e,r=_0t){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(Use(this,e))}has(e){return super.has(Use(this,e))}set(e,r){return super.set(y0t(this,e),r)}delete(e){return super.delete(x0t(this,e))}}function Use({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):r}function y0t({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):(t.set(n,r),r)}function x0t({_intern:t,_key:e},r){const n=e(r);return t.has(n)&&(r=t.get(n),t.delete(n)),r}function _0t(t){return t!==null&&typeof t=="object"?t.valueOf():t}function v0t(t=Vy){if(t===Vy)return bSe;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 bSe(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const b0t=Math.sqrt(50),w0t=Math.sqrt(10),S0t=Math.sqrt(2);function fM(t,e,r){const n=(e-t)/Math.max(0,r),i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),c=o>=b0t?10:o>=w0t?5:o>=S0t?2:1;let s,f,p;return i<0?(p=Math.pow(10,-i)/c,s=Math.round(t*p),f=Math.round(e*p),s/pe&&--f,p=-p):(p=Math.pow(10,i)*c,s=Math.round(t/p),f=Math.round(e/p),s*pe&&--f),f0))return[];if(t===e)return[t];const n=e=i))return[];const s=o-i+1,f=new Array(s);if(n)if(c<0)for(let p=0;p=n)&&(r=n);return r}function qse(t,e){let r;for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function wSe(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?bSe:v0t(i);n>r;){if(n-r>600){const f=n-r+1,p=e-r+1,y=Math.log(f),_=.5*Math.exp(2*y/3),T=.5*Math.sqrt(y*_*(f-_)/f)*(p-f/2<0?-1:1),E=Math.max(r,Math.floor(e-p*_/f+T)),k=Math.min(n,Math.floor(e+(f-p)*_/f+T));wSe(t,e,E,k,i)}const o=t[e];let c=r,s=n;for(Z2(t,r,e),i(t[n],o)>0&&Z2(t,r,n);c0;)--s}i(t[r],o)===0?Z2(t,r,s):(++s,Z2(t,s,n)),s<=e&&(r=s+1),e<=s&&(n=s-1)}return t}function Z2(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function T0t(t,e,r){if(t=Float64Array.from(p0t(t)),!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return qse(t);if(e>=1)return Vse(t);var n,i=(n-1)*e,o=Math.floor(i),c=Vse(wSe(t,o).subarray(0,o+1)),s=qse(t.subarray(o+1));return c+(s-c)*(i-o)}}function E0t(t,e,r=vSe){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,o=Math.floor(i),c=+r(t[o],o,t),s=+r(t[o+1],o+1,t);return c+(s-c)*(i-o)}}function A0t(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,o=new Array(i);++n>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?lR(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?lR(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=k0t.exec(t))?new ju(e[1],e[2],e[3],1):(e=C0t.exec(t))?new ju(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=I0t.exec(t))?lR(e[1],e[2],e[3],e[4]):(e=N0t.exec(t))?lR(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=P0t.exec(t))?Xse(e[1],e[2]/100,e[3]/100,1):(e=R0t.exec(t))?Xse(e[1],e[2]/100,e[3]/100,e[4]):Gse.hasOwnProperty(t)?Kse(Gse[t]):t==="transparent"?new ju(NaN,NaN,NaN,0):null}function Kse(t){return new ju(t>>16&255,t>>8&255,t&255,1)}function lR(t,e,r,n){return n<=0&&(t=e=r=NaN),new ju(t,e,r,n)}function M0t(t){return t instanceof LC||(t=ak(t)),t?(t=t.rgb(),new ju(t.r,t.g,t.b,t.opacity)):new ju}function M8(t,e,r,n){return arguments.length===1?M0t(t):new ju(t,e,r,n??1)}function ju(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}oW(ju,M8,TSe(LC,{brighter(t){return t=t==null?mM:Math.pow(mM,t),new ju(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?ik:Math.pow(ik,t),new ju(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new ju(I_(this.r),I_(this.g),I_(this.b),pM(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:Yse,formatHex:Yse,formatHex8:O0t,formatRgb:Zse,toString:Zse}));function Yse(){return`#${f_(this.r)}${f_(this.g)}${f_(this.b)}`}function O0t(){return`#${f_(this.r)}${f_(this.g)}${f_(this.b)}${f_((isNaN(this.opacity)?1:this.opacity)*255)}`}function Zse(){const t=pM(this.opacity);return`${t===1?"rgb(":"rgba("}${I_(this.r)}, ${I_(this.g)}, ${I_(this.b)}${t===1?")":`, ${t})`}`}function pM(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function I_(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function f_(t){return t=I_(t),(t<16?"0":"")+t.toString(16)}function Xse(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new Zh(t,e,r,n)}function ESe(t){if(t instanceof Zh)return new Zh(t.h,t.s,t.l,t.opacity);if(t instanceof LC||(t=ak(t)),!t)return new Zh;if(t instanceof Zh)return t;t=t.rgb();var e=t.r/255,r=t.g/255,n=t.b/255,i=Math.min(e,r,n),o=Math.max(e,r,n),c=NaN,s=o-i,f=(o+i)/2;return s?(e===o?c=(r-n)/s+(r0&&f<1?0:c,new Zh(c,s,f,t.opacity)}function F0t(t,e,r,n){return arguments.length===1?ESe(t):new Zh(t,e,r,n??1)}function Zh(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}oW(Zh,F0t,TSe(LC,{brighter(t){return t=t==null?mM:Math.pow(mM,t),new Zh(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?ik:Math.pow(ik,t),new Zh(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 ju(u$(t>=240?t-240:t+120,i,n),u$(t,i,n),u$(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new Zh(Qse(this.h),cR(this.s),cR(this.l),pM(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=pM(this.opacity);return`${t===1?"hsl(":"hsla("}${Qse(this.h)}, ${cR(this.s)*100}%, ${cR(this.l)*100}%${t===1?")":`, ${t})`}`}}));function Qse(t){return t=(t||0)%360,t<0?t+360:t}function cR(t){return Math.max(0,Math.min(1,t||0))}function u$(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 lW=t=>()=>t;function B0t(t,e){return function(r){return t+r*e}}function z0t(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 $0t(t){return(t=+t)==1?ASe:function(e,r){return r-e?z0t(e,r,t):lW(isNaN(e)?r:e)}}function ASe(t,e){var r=e-t;return r?B0t(t,r):lW(isNaN(t)?e:t)}const Jse=function t(e){var r=$0t(e);function n(i,o){var c=r((i=M8(i)).r,(o=M8(o)).r),s=r(i.g,o.g),f=r(i.b,o.b),p=ASe(i.opacity,o.opacity);return function(y){return i.r=c(y),i.g=s(y),i.b=f(y),i.opacity=p(y),i+""}}return n.gamma=t,n}(1);function U0t(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,n=e.slice(),i;return function(o){for(i=0;ir&&(o=e.slice(r,o),s[c]?s[c]+=o:s[++c]=o),(n=n[0])===(i=i[0])?s[c]?s[c]+=i:s[++c]=i:(s[++c]=null,f.push({i:c,x:gM(n,i)})),r=d$.lastIndex;return re&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function J0t(t,e,r){var n=t[0],i=t[1],o=e[0],c=e[1];return i2?e_t:J0t,f=p=null,_}function _(T){return T==null||isNaN(T=+T)?o:(f||(f=s(t.map(n),e,r)))(n(c(T)))}return _.invert=function(T){return c(i((p||(p=s(e,t.map(n),gM)))(T)))},_.domain=function(T){return arguments.length?(t=Array.from(T,yM),y()):t.slice()},_.range=function(T){return arguments.length?(e=Array.from(T),y()):e.slice()},_.rangeRound=function(T){return e=Array.from(T),r=cW,y()},_.clamp=function(T){return arguments.length?(c=T?!0:Qc,y()):c!==Qc},_.interpolate=function(T){return arguments.length?(r=T,y()):r},_.unknown=function(T){return arguments.length?(o=T,_):o},function(T,E){return n=T,i=E,y()}}function uW(){return gF()(Qc,Qc)}function t_t(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function xM(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 rS(t){return t=xM(Math.abs(t)),t?t[1]:NaN}function r_t(t,e){return function(r,n){for(var i=r.length,o=[],c=0,s=t[0],f=0;i>0&&s>0&&(f+s+1>n&&(s=Math.max(1,n-f)),o.push(r.substring(i-=s,i+s)),!((f+=s+1)>n));)s=t[c=(c+1)%t.length];return o.reverse().join(e)}}function n_t(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var i_t=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function ok(t){if(!(e=i_t.exec(t)))throw new Error("invalid format: "+t);var e;return new dW({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=dW.prototype;function dW(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+""}dW.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 s_t(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 jSe;function a_t(t,e){var r=xM(t,e);if(!r)return t+"";var n=r[0],i=r[1],o=i-(jSe=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,c=n.length;return o===c?n:o>c?n+new Array(o-c+1).join("0"):o>0?n.slice(0,o)+"."+n.slice(o):"0."+new Array(1-o).join("0")+xM(t,Math.max(0,e+o-1))[0]}function tae(t,e){var r=xM(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 rae={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:t_t,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)=>tae(t*100,e),r:tae,s:a_t,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function nae(t){return t}var iae=Array.prototype.map,sae=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function o_t(t){var e=t.grouping===void 0||t.thousands===void 0?nae:r_t(iae.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+"",o=t.numerals===void 0?nae:n_t(iae.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 p(_){_=ok(_);var T=_.fill,E=_.align,k=_.sign,P=_.symbol,R=_.zero,D=_.width,M=_.comma,B=_.precision,V=_.trim,G=_.type;G==="n"?(M=!0,G="g"):rae[G]||(B===void 0&&(B=12),V=!0,G="g"),(R||T==="0"&&E==="=")&&(R=!0,T="0",E="=");var W=P==="$"?r:P==="#"&&/[boxX]/.test(G)?"0"+G.toLowerCase():"",Z=P==="$"?n:/[%p]/.test(G)?c:"",Q=rae[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,we=Z,Ce,Me,Ae;if(G==="c")we=Q(ue)+we,ue="";else{ue=+ue;var be=ue<0||1/ue<0;if(ue=isNaN(ue)?f:Q(Math.abs(ue),B),V&&(ue=s_t(ue)),be&&+ue==0&&k!=="+"&&(be=!1),_e=(be?k==="("?k:s:k==="-"||k==="("?"":k)+_e,we=(G==="s"?sae[8+jSe/3]:"")+we+(be&&k==="("?")":""),re){for(Ce=-1,Me=ue.length;++CeAe||Ae>57){we=(Ae===46?i+ue.slice(Ce+1):ue.slice(Ce))+we,ue=ue.slice(0,Ce);break}}}M&&!R&&(ue=e(ue,1/0));var me=_e.length+ue.length+we.length,Pe=me>1)+_e+ue+we+Pe.slice(me);break;default:ue=Pe+_e+ue+we;break}return o(ue)}return se.toString=function(){return _+""},se}function y(_,T){var E=p((_=ok(_),_.type="f",_)),k=Math.max(-8,Math.min(8,Math.floor(rS(T)/3)))*3,P=Math.pow(10,-k),R=sae[8+k/3];return function(D){return E(P*D)+R}}return{format:p,formatPrefix:y}}var uR,hW,kSe;l_t({thousands:",",grouping:[3],currency:["$",""]});function l_t(t){return uR=o_t(t),hW=uR.format,kSe=uR.formatPrefix,uR}function c_t(t){return Math.max(0,-rS(Math.abs(t)))}function u_t(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(rS(e)/3)))*3-rS(Math.abs(t)))}function d_t(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,rS(e)-rS(t))+1}function CSe(t,e,r,n){var i=L8(t,e,r),o;switch(n=ok(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(o=u_t(i,c))&&(n.precision=o),kSe(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(o=d_t(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=o-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(o=c_t(i))&&(n.precision=o-(n.type==="%")*2);break}}return hW(n)}function jx(t){var e=t.domain;return t.ticks=function(r){var n=e();return P8(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return CSe(i[0],i[i.length-1],r??10,n)},t.nice=function(r){r==null&&(r=10);var n=e(),i=0,o=n.length-1,c=n[i],s=n[o],f,p,y=10;for(s0;){if(p=R8(c,s,r),p===f)return n[i]=c,n[o]=s,e(n);if(p>0)c=Math.floor(c/p)*p,s=Math.ceil(s/p)*p;else if(p<0)c=Math.ceil(c*p)/p,s=Math.floor(s*p)/p;else break;f=p}return t},t}function _M(){var t=uW();return t.copy=function(){return DC(t,_M())},dh.apply(t,arguments),jx(t)}function ISe(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,yM),r):t.slice()},r.unknown=function(n){return arguments.length?(e=n,r):e},r.copy=function(){return ISe(t).unknown(e)},t=arguments.length?Array.from(t,yM):[0,1],jx(r)}function NSe(t,e){t=t.slice();var r=0,n=t.length-1,i=t[r],o=t[n],c;return oMath.pow(t,e)}function g_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 lae(t){return(e,r)=>-t(-e,r)}function fW(t){const e=t(aae,oae),r=e.domain;let n=10,i,o;function c(){return i=g_t(n),o=p_t(n),r()[0]<0?(i=lae(i),o=lae(o),t(h_t,f_t)):t(aae,oae),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 p=f[0],y=f[f.length-1];const _=y0){for(;T<=E;++T)for(k=1;ky)break;D.push(P)}}else for(;T<=E;++T)for(k=n-1;k>=1;--k)if(P=T>0?k/o(-T):k*o(T),!(Py)break;D.push(P)}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=hW(f)),s===1/0)return f;const p=Math.max(1,n*s/e.ticks().length);return y=>{let _=y/o(Math.round(i(y)));return _*nr(NSe(r(),{floor:s=>o(Math.floor(i(s))),ceil:s=>o(Math.ceil(i(s)))})),e}function PSe(){const t=fW(gF()).domain([1,10]);return t.copy=()=>DC(t,PSe()).base(t.base()),dh.apply(t,arguments),t}function cae(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function uae(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function mW(t){var e=1,r=t(cae(e),uae(e));return r.constant=function(n){return arguments.length?t(cae(e=+n),uae(e)):e},jx(r)}function RSe(){var t=mW(gF());return t.copy=function(){return DC(t,RSe()).constant(t.constant())},dh.apply(t,arguments)}function dae(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function y_t(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function x_t(t){return t<0?-t*t:t*t}function pW(t){var e=t(Qc,Qc),r=1;function n(){return r===1?t(Qc,Qc):r===.5?t(y_t,x_t):t(dae(r),dae(1/r))}return e.exponent=function(i){return arguments.length?(r=+i,n()):r},jx(e)}function gW(){var t=pW(gF());return t.copy=function(){return DC(t,gW()).exponent(t.exponent())},dh.apply(t,arguments),t}function __t(){return gW.apply(null,arguments).exponent(.5)}function hae(t){return Math.sign(t)*t*t}function v_t(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function LSe(){var t=uW(),e=[0,1],r=!1,n;function i(o){var c=v_t(t(o));return isNaN(c)?n:r?Math.round(c):c}return i.invert=function(o){return t.invert(hae(o))},i.domain=function(o){return arguments.length?(t.domain(o),i):t.domain()},i.range=function(o){return arguments.length?(t.range((e=Array.from(o,yM)).map(hae)),i):e.slice()},i.rangeRound=function(o){return i.range(o).round(!0)},i.round=function(o){return arguments.length?(r=!!o,i):r},i.clamp=function(o){return arguments.length?(t.clamp(o),i):t.clamp()},i.unknown=function(o){return arguments.length?(n=o,i):n},i.copy=function(){return LSe(t.domain(),e).round(r).clamp(t.clamp()).unknown(n)},dh.apply(i,arguments),jx(i)}function DSe(){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[p-1],n[p]]},c.unknown=function(f){return arguments.length&&(o=f),c},c.thresholds=function(){return n.slice()},c.copy=function(){return MSe().domain([t,e]).range(i).unknown(o)},dh.apply(jx(c),arguments)}function OSe(){var t=[.5],e=[0,1],r,n=1;function i(o){return o!=null&&o<=o?e[RC(t,o,0,n)]:r}return i.domain=function(o){return arguments.length?(t=Array.from(o),n=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(o){return arguments.length?(e=Array.from(o),n=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(o){var c=e.indexOf(o);return[t[c-1],t[c]]},i.unknown=function(o){return arguments.length?(r=o,i):r},i.copy=function(){return OSe().domain(t).range(e).unknown(r)},dh.apply(i,arguments)}const h$=new Date,f$=new Date;function gl(t,e,r,n){function i(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return i.floor=o=>(t(o=new Date(+o)),o),i.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),i.round=o=>{const c=i(o),s=i.ceil(o);return o-c(e(o=new Date(+o),c==null?1:Math.floor(c)),o),i.range=(o,c,s)=>{const f=[];if(o=i.ceil(o),s=s==null?1:Math.floor(s),!(o0))return f;let p;do f.push(p=new Date(+o)),e(o,s),t(o);while(pgl(c=>{if(c>=c)for(;t(c),!o(c);)c.setTime(c-1)},(c,s)=>{if(c>=c)if(s<0)for(;++s<=0;)for(;e(c,-1),!o(c););else for(;--s>=0;)for(;e(c,1),!o(c););}),r&&(i.count=(o,c)=>(h$.setTime(+o),f$.setTime(+c),t(h$),t(f$),Math.floor(r(h$,f$))),i.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?i.filter(n?c=>n(c)%o===0:c=>i.count(0,c)%o===0):i)),i}const vM=gl(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);vM.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?gl(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):vM);vM.range;const Sp=1e3,Qd=Sp*60,Tp=Qd*60,qp=Tp*24,yW=qp*7,fae=qp*30,m$=qp*365,m_=gl(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Sp)},(t,e)=>(e-t)/Sp,t=>t.getUTCSeconds());m_.range;const xW=gl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Sp)},(t,e)=>{t.setTime(+t+e*Qd)},(t,e)=>(e-t)/Qd,t=>t.getMinutes());xW.range;const _W=gl(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*Qd)},(t,e)=>(e-t)/Qd,t=>t.getUTCMinutes());_W.range;const vW=gl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Sp-t.getMinutes()*Qd)},(t,e)=>{t.setTime(+t+e*Tp)},(t,e)=>(e-t)/Tp,t=>t.getHours());vW.range;const bW=gl(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Tp)},(t,e)=>(e-t)/Tp,t=>t.getUTCHours());bW.range;const MC=gl(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Qd)/qp,t=>t.getDate()-1);MC.range;const yF=gl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/qp,t=>t.getUTCDate()-1);yF.range;const FSe=gl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/qp,t=>Math.floor(t/qp));FSe.range;function dv(t){return gl(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())*Qd)/yW)}const xF=dv(0),bM=dv(1),b_t=dv(2),w_t=dv(3),nS=dv(4),S_t=dv(5),T_t=dv(6);xF.range;bM.range;b_t.range;w_t.range;nS.range;S_t.range;T_t.range;function hv(t){return gl(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)/yW)}const _F=hv(0),wM=hv(1),E_t=hv(2),A_t=hv(3),iS=hv(4),j_t=hv(5),k_t=hv(6);_F.range;wM.range;E_t.range;A_t.range;iS.range;j_t.range;k_t.range;const wW=gl(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());wW.range;const SW=gl(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());SW.range;const Gp=gl(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());Gp.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:gl(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)});Gp.range;const Hp=gl(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());Hp.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:gl(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)});Hp.range;function BSe(t,e,r,n,i,o){const c=[[m_,1,Sp],[m_,5,5*Sp],[m_,15,15*Sp],[m_,30,30*Sp],[o,1,Qd],[o,5,5*Qd],[o,15,15*Qd],[o,30,30*Qd],[i,1,Tp],[i,3,3*Tp],[i,6,6*Tp],[i,12,12*Tp],[n,1,qp],[n,2,2*qp],[r,1,yW],[e,1,fae],[e,3,3*fae],[t,1,m$]];function s(p,y,_){const T=yR).right(c,T);if(E===c.length)return t.every(L8(p/m$,y/m$,_));if(E===0)return vM.every(Math.max(L8(p,y,_),1));const[k,P]=c[T/c[E-1][2]53)return null;"w"in vt||(vt.w=1),"Z"in vt?(Sr=g$(X2(vt.y,0,1)),nn=Sr.getUTCDay(),Sr=nn>4||nn===0?wM.ceil(Sr):wM(Sr),Sr=yF.offset(Sr,(vt.V-1)*7),vt.y=Sr.getUTCFullYear(),vt.m=Sr.getUTCMonth(),vt.d=Sr.getUTCDate()+(vt.w+6)%7):(Sr=p$(X2(vt.y,0,1)),nn=Sr.getDay(),Sr=nn>4||nn===0?bM.ceil(Sr):bM(Sr),Sr=MC.offset(Sr,(vt.V-1)*7),vt.y=Sr.getFullYear(),vt.m=Sr.getMonth(),vt.d=Sr.getDate()+(vt.w+6)%7)}else("W"in vt||"U"in vt)&&("w"in vt||(vt.w="u"in vt?vt.u%7:"W"in vt?1:0),nn="Z"in vt?g$(X2(vt.y,0,1)).getUTCDay():p$(X2(vt.y,0,1)).getDay(),vt.m=0,vt.d="W"in vt?(vt.w+6)%7+vt.W*7-(nn+5)%7:vt.w+vt.U*7-(nn+6)%7);return"Z"in vt?(vt.H+=vt.Z/100|0,vt.M+=vt.Z%100,g$(vt)):p$(vt)}}function Q(pt,Nt,er,vt){for(var or=0,Sr=Nt.length,nn=er.length,cr,xr;or=nn)return-1;if(cr=Nt.charCodeAt(or++),cr===37){if(cr=Nt.charAt(or++),xr=G[cr in mae?Nt.charAt(or++):cr],!xr||(vt=xr(pt,er,vt))<0)return-1}else if(cr!=er.charCodeAt(vt++))return-1}return vt}function re(pt,Nt,er){var vt=p.exec(Nt.slice(er));return vt?(pt.p=y.get(vt[0].toLowerCase()),er+vt[0].length):-1}function se(pt,Nt,er){var vt=E.exec(Nt.slice(er));return vt?(pt.w=k.get(vt[0].toLowerCase()),er+vt[0].length):-1}function ue(pt,Nt,er){var vt=_.exec(Nt.slice(er));return vt?(pt.w=T.get(vt[0].toLowerCase()),er+vt[0].length):-1}function _e(pt,Nt,er){var vt=D.exec(Nt.slice(er));return vt?(pt.m=M.get(vt[0].toLowerCase()),er+vt[0].length):-1}function we(pt,Nt,er){var vt=P.exec(Nt.slice(er));return vt?(pt.m=R.get(vt[0].toLowerCase()),er+vt[0].length):-1}function Ce(pt,Nt,er){return Q(pt,e,Nt,er)}function Me(pt,Nt,er){return Q(pt,r,Nt,er)}function Ae(pt,Nt,er){return Q(pt,n,Nt,er)}function be(pt){return c[pt.getDay()]}function me(pt){return o[pt.getDay()]}function Pe(pt){return f[pt.getMonth()]}function Ie(pt){return s[pt.getMonth()]}function Se(pt){return i[+(pt.getHours()>=12)]}function ve(pt){return 1+~~(pt.getMonth()/3)}function We(pt){return c[pt.getUTCDay()]}function rt(pt){return o[pt.getUTCDay()]}function at(pt){return f[pt.getUTCMonth()]}function Et(pt){return s[pt.getUTCMonth()]}function _t(pt){return i[+(pt.getUTCHours()>=12)]}function Vt(pt){return 1+~~(pt.getUTCMonth()/3)}return{format:function(pt){var Nt=W(pt+="",B);return Nt.toString=function(){return pt},Nt},parse:function(pt){var Nt=Z(pt+="",!1);return Nt.toString=function(){return pt},Nt},utcFormat:function(pt){var Nt=W(pt+="",V);return Nt.toString=function(){return pt},Nt},utcParse:function(pt){var Nt=Z(pt+="",!0);return Nt.toString=function(){return pt},Nt}}}var mae={"-":"",_:" ",0:"0"},Ml=/^\s*\d+/,L_t=/^%/,D_t=/[\\^$*+?|[\]().{}]/g;function _s(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",o=i.length;return n+(o[e.toLowerCase(),r]))}function O_t(t,e,r){var n=Ml.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function F_t(t,e,r){var n=Ml.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function B_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function z_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function $_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function pae(t,e,r){var n=Ml.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function gae(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function U_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 V_t(t,e,r){var n=Ml.exec(e.slice(r,r+1));return n?(t.q=n[0]*3-3,r+n[0].length):-1}function q_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function yae(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function G_t(t,e,r){var n=Ml.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function xae(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function H_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function W_t(t,e,r){var n=Ml.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function K_t(t,e,r){var n=Ml.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function Y_t(t,e,r){var n=Ml.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=L_t.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function X_t(t,e,r){var n=Ml.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function Q_t(t,e,r){var n=Ml.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function _ae(t,e){return _s(t.getDate(),e,2)}function J_t(t,e){return _s(t.getHours(),e,2)}function evt(t,e){return _s(t.getHours()%12||12,e,2)}function tvt(t,e){return _s(1+MC.count(Gp(t),t),e,3)}function zSe(t,e){return _s(t.getMilliseconds(),e,3)}function rvt(t,e){return zSe(t,e)+"000"}function nvt(t,e){return _s(t.getMonth()+1,e,2)}function ivt(t,e){return _s(t.getMinutes(),e,2)}function svt(t,e){return _s(t.getSeconds(),e,2)}function avt(t){var e=t.getDay();return e===0?7:e}function ovt(t,e){return _s(xF.count(Gp(t)-1,t),e,2)}function $Se(t){var e=t.getDay();return e>=4||e===0?nS(t):nS.ceil(t)}function lvt(t,e){return t=$Se(t),_s(nS.count(Gp(t),t)+(Gp(t).getDay()===4),e,2)}function cvt(t){return t.getDay()}function uvt(t,e){return _s(bM.count(Gp(t)-1,t),e,2)}function dvt(t,e){return _s(t.getFullYear()%100,e,2)}function hvt(t,e){return t=$Se(t),_s(t.getFullYear()%100,e,2)}function fvt(t,e){return _s(t.getFullYear()%1e4,e,4)}function mvt(t,e){var r=t.getDay();return t=r>=4||r===0?nS(t):nS.ceil(t),_s(t.getFullYear()%1e4,e,4)}function pvt(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+_s(e/60|0,"0",2)+_s(e%60,"0",2)}function vae(t,e){return _s(t.getUTCDate(),e,2)}function gvt(t,e){return _s(t.getUTCHours(),e,2)}function yvt(t,e){return _s(t.getUTCHours()%12||12,e,2)}function xvt(t,e){return _s(1+yF.count(Hp(t),t),e,3)}function USe(t,e){return _s(t.getUTCMilliseconds(),e,3)}function _vt(t,e){return USe(t,e)+"000"}function vvt(t,e){return _s(t.getUTCMonth()+1,e,2)}function bvt(t,e){return _s(t.getUTCMinutes(),e,2)}function wvt(t,e){return _s(t.getUTCSeconds(),e,2)}function Svt(t){var e=t.getUTCDay();return e===0?7:e}function Tvt(t,e){return _s(_F.count(Hp(t)-1,t),e,2)}function VSe(t){var e=t.getUTCDay();return e>=4||e===0?iS(t):iS.ceil(t)}function Evt(t,e){return t=VSe(t),_s(iS.count(Hp(t),t)+(Hp(t).getUTCDay()===4),e,2)}function Avt(t){return t.getUTCDay()}function jvt(t,e){return _s(wM.count(Hp(t)-1,t),e,2)}function kvt(t,e){return _s(t.getUTCFullYear()%100,e,2)}function Cvt(t,e){return t=VSe(t),_s(t.getUTCFullYear()%100,e,2)}function Ivt(t,e){return _s(t.getUTCFullYear()%1e4,e,4)}function Nvt(t,e){var r=t.getUTCDay();return t=r>=4||r===0?iS(t):iS.ceil(t),_s(t.getUTCFullYear()%1e4,e,4)}function Pvt(){return"+0000"}function bae(){return"%"}function wae(t){return+t}function Sae(t){return Math.floor(+t/1e3)}var sw,qSe,GSe;Rvt({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 Rvt(t){return sw=R_t(t),qSe=sw.format,sw.parse,GSe=sw.utcFormat,sw.utcParse,sw}function Lvt(t){return new Date(t)}function Dvt(t){return t instanceof Date?+t:+new Date(+t)}function TW(t,e,r,n,i,o,c,s,f,p){var y=uW(),_=y.invert,T=y.domain,E=p(".%L"),k=p(":%S"),P=p("%I:%M"),R=p("%I %p"),D=p("%a %d"),M=p("%b %d"),B=p("%B"),V=p("%Y");function G(W){return(f(W)e(i/(t.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,o)=>T0t(t,o/n))},r.copy=function(){return YSe(e).domain(t)},eg.apply(r,arguments)}function bF(){var t=0,e=.5,r=1,n=1,i,o,c,s,f,p=Qc,y,_=!1,T;function E(P){return isNaN(P=+P)?T:(P=.5+((P=+y(P))-o)*(n*Pe}var JSe=Uvt,Vvt=wF,qvt=JSe,Gvt=aT;function Hvt(t){return t&&t.length?Vvt(t,Gvt,qvt):void 0}var Wvt=Hvt;const SF=ds(Wvt);function Kvt(t,e){return tt.e^o.s<0?1:-1;for(n=o.d.length,i=t.d.length,e=0,r=nt.d[e]^o.s<0?1:-1;return n===i?0:n>i^o.s<0?1:-1};jn.decimalPlaces=jn.dp=function(){var t=this,e=t.d.length-1,r=(e-t.e)*Na;if(e=t.d[e],e)for(;e%10==0;e/=10)r--;return r<0?0:r};jn.dividedBy=jn.div=function(t){return Np(this,new this.constructor(t))};jn.dividedToIntegerBy=jn.idiv=function(t){var e=this,r=e.constructor;return ia(Np(e,new r(t),0,1),r.precision)};jn.equals=jn.eq=function(t){return!this.cmp(t)};jn.exponent=function(){return Ho(this)};jn.greaterThan=jn.gt=function(t){return this.cmp(t)>0};jn.greaterThanOrEqualTo=jn.gte=function(t){return this.cmp(t)>=0};jn.isInteger=jn.isint=function(){return this.e>this.d.length-2};jn.isNegative=jn.isneg=function(){return this.s<0};jn.isPositive=jn.ispos=function(){return this.s>0};jn.isZero=function(){return this.s===0};jn.lessThan=jn.lt=function(t){return this.cmp(t)<0};jn.lessThanOrEqualTo=jn.lte=function(t){return this.cmp(t)<1};jn.logarithm=jn.log=function(t){var e,r=this,n=r.constructor,i=n.precision,o=i+5;if(t===void 0)t=new n(10);else if(t=new n(t),t.s<1||t.eq(rd))throw Error(ah+"NaN");if(r.s<1)throw Error(ah+(r.s?"NaN":"-Infinity"));return r.eq(rd)?new n(0):($a=!1,e=Np(lk(r,o),lk(t,o),o),$a=!0,ia(e,i))};jn.minus=jn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?iTe(e,t):rTe(e,(t.s=-t.s,t))};jn.modulo=jn.mod=function(t){var e,r=this,n=r.constructor,i=n.precision;if(t=new n(t),!t.s)throw Error(ah+"NaN");return r.s?($a=!1,e=Np(r,t,0,1).times(t),$a=!0,r.minus(e)):ia(new n(r),i)};jn.naturalExponential=jn.exp=function(){return nTe(this)};jn.naturalLogarithm=jn.ln=function(){return lk(this)};jn.negated=jn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};jn.plus=jn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?rTe(e,t):iTe(e,(t.s=-t.s,t))};jn.precision=jn.sd=function(t){var e,r,n,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(N_+t);if(e=Ho(i)+1,n=i.d.length-1,r=n*Na+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};jn.squareRoot=jn.sqrt=function(){var t,e,r,n,i,o,c,s=this,f=s.constructor;if(s.s<1){if(!s.s)return new f(0);throw Error(ah+"NaN")}for(t=Ho(s),$a=!1,i=Math.sqrt(+s),i==0||i==1/0?(e=Jf(s.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=cT((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(o=n,n=o.plus(Np(s,o,c+2)).times(.5),Jf(o.d).slice(0,c)===(e=Jf(n.d)).slice(0,c)){if(e=e.slice(c-3,c+1),i==c&&e=="4999"){if(ia(o,r+1,0),o.times(o).eq(s)){n=o;break}}else if(e!="9999")break;c+=4}return $a=!0,ia(n,r)};jn.times=jn.mul=function(t){var e,r,n,i,o,c,s,f,p,y=this,_=y.constructor,T=y.d,E=(t=new _(t)).d;if(!y.s||!t.s)return new _(0);for(t.s*=y.s,r=y.e+t.e,f=T.length,p=E.length,f=0;){for(e=0,i=f+n;i>n;)s=o[i]+E[n]*T[i-n-1]+e,o[i--]=s%jl|0,e=s/jl|0;o[i]=(o[i]+e)%jl|0}for(;!o[--c];)o.pop();return e?++r:o.shift(),t.d=o,t.e=r,$a?ia(t,_.precision):t};jn.toDecimalPlaces=jn.todp=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(pm(t,0,lT),e===void 0?e=n.rounding:pm(e,0,8),ia(r,t+Ho(r)+1,e))};jn.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Y_(n,!0):(pm(t,0,lT),e===void 0?e=i.rounding:pm(e,0,8),n=ia(new i(n),t+1,e),r=Y_(n,!0,t+1)),r};jn.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?Y_(i):(pm(t,0,lT),e===void 0?e=o.rounding:pm(e,0,8),n=ia(new o(i),t+Ho(i)+1,e),r=Y_(n.abs(),!1,t+Ho(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};jn.toInteger=jn.toint=function(){var t=this,e=t.constructor;return ia(new e(t),Ho(t)+1,e.rounding)};jn.toNumber=function(){return+this};jn.toPower=jn.pow=function(t){var e,r,n,i,o,c,s=this,f=s.constructor,p=12,y=+(t=new f(t));if(!t.s)return new f(rd);if(s=new f(s),!s.s){if(t.s<1)throw Error(ah+"Infinity");return s}if(s.eq(rd))return s;if(n=f.precision,t.eq(rd))return ia(s,n);if(e=t.e,r=t.d.length-1,c=e>=r,o=s.s,c){if((r=y<0?-y:y)<=tTe){for(i=new f(rd),e=Math.ceil(n/Na+4),$a=!1;r%2&&(i=i.times(s),Aae(i.d,e)),r=cT(r/2),r!==0;)s=s.times(s),Aae(s.d,e);return $a=!0,t.s<0?new f(rd).div(i):ia(i,n)}}else if(o<0)throw Error(ah+"NaN");return o=o<0&&t.d[Math.max(e,r)]&1?-1:1,s.s=1,$a=!1,i=t.times(lk(s,n+p)),$a=!0,i=nTe(i),i.s=o,i};jn.toPrecision=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?(r=Ho(i),n=Y_(i,r<=o.toExpNeg||r>=o.toExpPos)):(pm(t,1,lT),e===void 0?e=o.rounding:pm(e,0,8),i=ia(new o(i),t,e),r=Ho(i),n=Y_(i,t<=r||r<=o.toExpNeg,t)),n};jn.toSignificantDigits=jn.tosd=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(pm(t,1,lT),e===void 0?e=n.rounding:pm(e,0,8)),ia(new n(r),t,e)};jn.toString=jn.valueOf=jn.val=jn.toJSON=jn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=Ho(t),r=t.constructor;return Y_(t,e<=r.toExpNeg||e>=r.toExpPos)};function rTe(t,e){var r,n,i,o,c,s,f,p,y=t.constructor,_=y.precision;if(!t.s||!e.s)return e.s||(e=new y(t)),$a?ia(e,_):e;if(f=t.d,p=e.d,c=t.e,i=e.e,f=f.slice(),o=c-i,o){for(o<0?(n=f,o=-o,s=p.length):(n=p,i=c,s=f.length),c=Math.ceil(_/Na),s=c>s?c+1:s+1,o>s&&(o=s,n.length=1),n.reverse();o--;)n.push(0);n.reverse()}for(s=f.length,o=p.length,s-o<0&&(o=s,n=p,p=f,f=n),r=0;o;)r=(f[--o]=f[o]+p[o]+r)/jl|0,f[o]%=jl;for(r&&(f.unshift(r),++i),s=f.length;f[--s]==0;)f.pop();return e.d=f,e.e=i,$a?ia(e,_):e}function pm(t,e,r){if(t!==~~t||tr)throw Error(N_+t)}function Jf(t){var e,r,n,i=t.length-1,o="",c=t[0];if(i>0){for(o+=c,e=1;ec?1:-1;else for(s=f=0;si[s]?1:-1;break}return f}function r(n,i,o){for(var c=0;o--;)n[o]-=c,c=n[o]1;)n.shift()}return function(n,i,o,c){var s,f,p,y,_,T,E,k,P,R,D,M,B,V,G,W,Z,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(ah+"Division by zero");for(f=n.e-i.e,Z=_e.length,G=ue.length,E=new re(se),k=E.d=[],p=0;_e[p]==(ue[p]||0);)++p;if(_e[p]>(ue[p]||0)&&--f,o==null?M=o=re.precision:c?M=o+(Ho(n)-Ho(i))+1:M=o,M<0)return new re(0);if(M=M/Na+2|0,p=0,Z==1)for(y=0,_e=_e[0],M++;(p1&&(_e=t(_e,y),ue=t(ue,y),Z=_e.length,G=ue.length),V=Z,P=ue.slice(0,Z),R=P.length;R=jl/2&&++W;do y=0,s=e(_e,P,Z,R),s<0?(D=P[0],Z!=R&&(D=D*jl+(P[1]||0)),y=D/W|0,y>1?(y>=jl&&(y=jl-1),_=t(_e,y),T=_.length,R=P.length,s=e(_,P,T,R),s==1&&(y--,r(_,Z16)throw Error(jW+Ho(t));if(!t.s)return new y(rd);for(e==null?($a=!1,s=_):s=e,c=new y(.03125);t.abs().gte(.1);)t=t.times(c),p+=5;for(n=Math.log(t_(2,p))/Math.LN10*2+5|0,s+=n,r=i=o=new y(rd),y.precision=s;;){if(i=ia(i.times(t),s),r=r.times(++f),c=o.plus(Np(i,r,s)),Jf(c.d).slice(0,s)===Jf(o.d).slice(0,s)){for(;p--;)o=ia(o.times(o),s);return y.precision=_,e==null?($a=!0,ia(o,_)):o}o=c}}function Ho(t){for(var e=t.e*Na,r=t.d[0];r>=10;r/=10)e++;return e}function y$(t,e,r){if(e>t.LN10.sd())throw $a=!0,r&&(t.precision=r),Error(ah+"LN10 precision limit exceeded");return ia(new t(t.LN10),e)}function ly(t){for(var e="";t--;)e+="0";return e}function lk(t,e){var r,n,i,o,c,s,f,p,y,_=1,T=10,E=t,k=E.d,P=E.constructor,R=P.precision;if(E.s<1)throw Error(ah+(E.s?"NaN":"-Infinity"));if(E.eq(rd))return new P(0);if(e==null?($a=!1,p=R):p=e,E.eq(10))return e==null&&($a=!0),y$(P,p);if(p+=T,P.precision=p,r=Jf(k),n=r.charAt(0),o=Ho(E),Math.abs(o)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)E=E.times(t),r=Jf(E.d),n=r.charAt(0),_++;o=Ho(E),n>1?(E=new P("0."+r),o++):E=new P(n+"."+r.slice(1))}else return f=y$(P,p+2,R).times(o+""),E=lk(new P(n+"."+r.slice(1)),p-T).plus(f),P.precision=R,e==null?($a=!0,ia(E,R)):E;for(s=c=E=Np(E.minus(rd),E.plus(rd),p),y=ia(E.times(E),p),i=3;;){if(c=ia(c.times(y),p),f=s.plus(Np(c,new P(i),p)),Jf(f.d).slice(0,p)===Jf(s.d).slice(0,p))return s=s.times(2),o!==0&&(s=s.plus(y$(P,p+2,R).times(o+""))),s=Np(s,new P(_),p),P.precision=R,e==null?($a=!0,ia(s,R)):s;s=f,i+=2}}function Eae(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=cT(r/Na),t.d=[],n=(r+1)%Na,r<0&&(n+=Na),nSM||t.e<-SM))throw Error(jW+r)}else t.s=0,t.e=0,t.d=[0];return t}function ia(t,e,r){var n,i,o,c,s,f,p,y,_=t.d;for(c=1,o=_[0];o>=10;o/=10)c++;if(n=e-c,n<0)n+=Na,i=e,p=_[y=0];else{if(y=Math.ceil((n+1)/Na),o=_.length,y>=o)return t;for(p=o=_[y],c=1;o>=10;o/=10)c++;n%=Na,i=n-Na+c}if(r!==void 0&&(o=t_(10,c-i-1),s=p/o%10|0,f=e<0||_[y+1]!==void 0||p%o,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?p/t_(10,c-i):0:_[y-1])%10&1||r==(t.s<0?8:7))),e<1||!_[0])return f?(o=Ho(t),_.length=1,e=e-o-1,_[0]=t_(10,(Na-e%Na)%Na),t.e=cT(-e/Na)||0):(_.length=1,_[0]=t.e=t.s=0),t;if(n==0?(_.length=y,o=1,y--):(_.length=y+1,o=t_(10,Na-n),_[y]=i>0?(p/t_(10,c-i)%t_(10,i)|0)*o:0),f)for(;;)if(y==0){(_[0]+=o)==jl&&(_[0]=1,++t.e);break}else{if(_[y]+=o,_[y]!=jl)break;_[y--]=0,o=1}for(n=_.length;_[--n]===0;)_.pop();if($a&&(t.e>SM||t.e<-SM))throw Error(jW+Ho(t));return t}function iTe(t,e){var r,n,i,o,c,s,f,p,y,_,T=t.constructor,E=T.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new T(t),$a?ia(e,E):e;if(f=t.d,_=e.d,n=e.e,p=t.e,f=f.slice(),c=p-n,c){for(y=c<0,y?(r=f,c=-c,s=_.length):(r=_,n=p,s=f.length),i=Math.max(Math.ceil(E/Na),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,y=i0;--i)f[s++]=0;for(i=_.length;i>c;){if(f[--i]<_[i]){for(o=i;o&&f[--o]===0;)f[o]=jl-1;--f[o],f[i]+=jl}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,$a?ia(e,E):e):new T(0)}function Y_(t,e,r){var n,i=Ho(t),o=Jf(t.d),c=o.length;return e?(r&&(n=r-c)>0?o=o.charAt(0)+"."+o.slice(1)+ly(n):c>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(i<0?"e":"e+")+i):i<0?(o="0."+ly(-i-1)+o,r&&(n=r-c)>0&&(o+=ly(n))):i>=c?(o+=ly(i+1-c),r&&(n=r-i-1)>0&&(o=o+"."+ly(n))):((n=i+1)0&&(i+1===c&&(o+="."),o+=ly(n))),t.s<0?"-"+o:o}function Aae(t,e){if(t.length>e)return t.length=e,!0}function sTe(t){var e,r,n;function i(o){var c=this;if(!(c instanceof i))return new i(o);if(c.constructor=i,o instanceof i){c.s=o.s,c.e=o.e,c.d=(o=o.d)?o.slice():o;return}if(typeof o=="number"){if(o*0!==0)throw Error(N_+o);if(o>0)c.s=1;else if(o<0)o=-o,c.s=-1;else{c.s=0,c.e=0,c.d=[0];return}if(o===~~o&&o<1e7){c.e=0,c.d=[o];return}return Eae(c,o.toString())}else if(typeof o!="string")throw Error(N_+o);if(o.charCodeAt(0)===45?(o=o.slice(1),c.s=-1):c.s=1,pbt.test(o))Eae(c,o);else throw Error(N_+o)}if(i.prototype=jn,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=sTe,i.config=i.set=gbt,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(N_+r+": "+n);if((n=t[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(N_+r+": "+n);return this}var kW=sTe(mbt);rd=new kW(1);const Ks=kW;function ybt(t){return bbt(t)||vbt(t)||_bt(t)||xbt()}function xbt(){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 _bt(t,e){if(t){if(typeof t=="string")return B8(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 B8(t,e)}}function vbt(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function bbt(t){if(Array.isArray(t))return B8(t)}function B8(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,jae(function(){for(var s=arguments.length,f=new Array(s),p=0;pt.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,o=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,o=f}finally{try{!n&&c.return!=null&&c.return()}finally{if(i)throw o}}return r}}function Mbt(t){if(Array.isArray(t))return t}function uTe(t){var e=ck(t,2),r=e[0],n=e[1],i=r,o=n;return r>n&&(i=n,o=r),[i,o]}function dTe(t,e,r){if(t.lte(0))return new Ks(0);var n=jF.getDigitCount(t.toNumber()),i=new Ks(10).pow(n),o=t.div(i),c=n!==1?.05:.1,s=new Ks(Math.ceil(o.div(c).toNumber())).add(r).mul(c),f=s.mul(i);return e?f:new Ks(Math.ceil(f))}function Obt(t,e,r){var n=1,i=new Ks(t);if(!i.isint()&&r){var o=Math.abs(t);o<1?(n=new Ks(10).pow(jF.getDigitCount(t)-1),i=new Ks(Math.floor(i.div(n).toNumber())).mul(n)):o>1&&(i=new Ks(Math.floor(t)))}else t===0?i=new Ks(Math.floor((e-1)/2)):r||(i=new Ks(Math.floor(t)));var c=Math.floor((e-1)/2),s=Ebt(Tbt(function(f){return i.add(new Ks(f-c).mul(n)).toNumber()}),z8);return s(0,e)}function hTe(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 Ks(0),tickMin:new Ks(0),tickMax:new Ks(0)};var o=dTe(new Ks(e).sub(t).div(r-1),n,i),c;t<=0&&e>=0?c=new Ks(0):(c=new Ks(t).add(e).div(2),c=c.sub(new Ks(c).mod(o)));var s=Math.ceil(c.sub(t).div(o).toNumber()),f=Math.ceil(new Ks(e).sub(c).div(o).toNumber()),p=s+f+1;return p>r?hTe(t,e,r,n,i+1):(p0?f+(r-p):f,s=e>0?s:s+(r-p)),{step:o,tickMin:c.sub(new Ks(s).mul(o)),tickMax:c.add(new Ks(f).mul(o))})}function Fbt(t){var e=ck(t,2),r=e[0],n=e[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=Math.max(i,2),s=uTe([r,n]),f=ck(s,2),p=f[0],y=f[1];if(p===-1/0||y===1/0){var _=y===1/0?[p].concat(U8(z8(0,i-1).map(function(){return 1/0}))):[].concat(U8(z8(0,i-1).map(function(){return-1/0})),[y]);return r>n?$8(_):_}if(p===y)return Obt(p,i,o);var T=hTe(p,y,c,o),E=T.step,k=T.tickMin,P=T.tickMax,R=jF.rangeStep(k,P.add(new Ks(.1).mul(E)),E);return r>n?$8(R):R}function Bbt(t,e){var r=ck(t,2),n=r[0],i=r[1],o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=uTe([n,i]),s=ck(c,2),f=s[0],p=s[1];if(f===-1/0||p===1/0)return[n,i];if(f===p)return[f];var y=Math.max(e,2),_=dTe(new Ks(p).sub(f).div(y-1),o,0),T=[].concat(U8(jF.rangeStep(new Ks(f),new Ks(p).sub(new Ks(.99).mul(_)),_)),[p]);return n>i?$8(T):T}var zbt=lTe(Fbt),$bt=lTe(Bbt),Ubt="Invariant failed";function Z_(t,e){throw new Error(Ubt)}var Vbt=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function sS(t){"@babel/helpers - typeof";return sS=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},sS(t)}function TM(){return TM=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 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 Xbt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Qbt(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,o=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(o&&o.axisType==="angleAxis"&&Math.abs(Math.abs(o.range[1]-o.range[0])-360)<=1e-6)for(var f=o.range,p=0;p0?i[p-1].coordinate:i[s-1].coordinate,_=i[p].coordinate,T=p>=s-1?i[0].coordinate:i[p+1].coordinate,E=void 0;if(Zc(_-y)!==Zc(T-_)){var k=[];if(Zc(T-_)===Zc(f[1]-f[0])){E=T;var P=_+f[1]-f[0];k[0]=Math.min(P,(P+y)/2),k[1]=Math.max(P,(P+y)/2)}else{E=y;var R=T+f[1]-f[0];k[0]=Math.min(_,(R+_)/2),k[1]=Math.max(_,(R+_)/2)}var D=[Math.min(_,(E+_)/2),Math.max(_,(E+_)/2)];if(e>D[0]&&e<=D[1]||e>=k[0]&&e<=k[1]){c=i[p].index;break}}else{var M=Math.min(y,T),B=Math.max(y,T);if(e>(M+_)/2&&e<=(B+_)/2){c=i[p].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},CW=function(e){var r,n=e,i=n.type.displayName,o=(r=e.type)!==null&&r!==void 0&&r.defaultProps?mo(mo({},e.type.defaultProps),e.props):e.props,c=o.stroke,s=o.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},pwt=function(e){var r=e.barSize,n=e.totalSize,i=e.stackGroups,o=i===void 0?{}:i;if(!o)return{};for(var c={},s=Object.keys(o),f=0,p=s.length;f=0});if(D&&D.length){var M=D[0].type.defaultProps,B=M!==void 0?mo(mo({},M),D[0].props):D[0].props,V=B.barSize,G=B[R];c[G]||(c[G]=[]);var W=Fi(V)?r:V;c[G].push({item:D[0],stackList:D.slice(1),barSize:Fi(W)?void 0:Xc(W,n,0)})}}return c},gwt=function(e){var r=e.barGap,n=e.barCategoryGap,i=e.bandSize,o=e.sizeList,c=o===void 0?[]:o,s=e.maxBarSize,f=c.length;if(f<1)return null;var p=Xc(r,i,0,!0),y,_=[];if(c[0].barSize===+c[0].barSize){var T=!1,E=i/f,k=c.reduce(function(V,G){return V+G.barSize||0},0);k+=(f-1)*p,k>=i&&(k-=(f-1)*p,p=0),k>=i&&E>0&&(T=!0,E*=.9,k=f*E);var P=(i-k)/2>>0,R={offset:P-p,size:0};y=c.reduce(function(V,G){var W={item:G.item,position:{offset:R.offset+R.size+p,size:T?E:G.barSize}},Z=[].concat(Iae(V),[W]);return R=Z[Z.length-1].position,G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){Z.push({item:Q,position:R})}),Z},_)}else{var D=Xc(n,i,0,!0);i-2*D-(f-1)*p<=0&&(p=0);var M=(i-2*D-(f-1)*p)/f;M>1&&(M>>=0);var B=s===+s?Math.min(M,s):M;y=c.reduce(function(V,G,W){var Z=[].concat(Iae(V),[{item:G.item,position:{offset:D+(M+p)*W+(M-B)/2,size:B}}]);return G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){Z.push({item:Q,position:Z[Z.length-1].position})}),Z},_)}return y},ywt=function(e,r,n,i){var o=n.children,c=n.width,s=n.margin,f=c-(s.left||0)-(s.right||0),p=gTe({children:o,legendWidth:f});if(p){var y=i||{},_=y.width,T=y.height,E=p.align,k=p.verticalAlign,P=p.layout;if((P==="vertical"||P==="horizontal"&&k==="middle")&&E!=="center"&&Wr(e[E]))return mo(mo({},e),{},s1({},E,e[E]+(_||0)));if((P==="horizontal"||P==="vertical"&&E==="center")&&k!=="middle"&&Wr(e[k]))return mo(mo({},e),{},s1({},k,e[k]+(T||0)))}return e},xwt=function(e,r,n){return Fi(r)?!0:e==="horizontal"?r==="yAxis":e==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},yTe=function(e,r,n,i,o){var c=r.props.children,s=nh(c,kF).filter(function(p){return xwt(i,o,p.props.direction)});if(s&&s.length){var f=s.map(function(p){return p.props.dataKey});return e.reduce(function(p,y){var _=Xl(y,n);if(Fi(_))return p;var T=Array.isArray(_)?[TF(_),SF(_)]:[_,_],E=f.reduce(function(k,P){var R=Xl(y,P,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,k[0]),Math.max(M,k[1])]},[1/0,-1/0]);return[Math.min(E[0],p[0]),Math.max(E[1],p[1])]},[1/0,-1/0])}return null},_wt=function(e,r,n,i,o){var c=r.map(function(s){return yTe(e,s,n,o,i)}).filter(function(s){return!Fi(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},xTe=function(e,r,n,i,o){var c=r.map(function(f){var p=f.props.dataKey;return n==="number"&&p&&yTe(e,f,p,i)||XA(e,p,n,o)});if(n==="number")return c.reduce(function(f,p){return[Math.min(f[0],p[0]),Math.max(f[1],p[1])]},[1/0,-1/0]);var s={};return c.reduce(function(f,p){for(var y=0,_=p.length;y<_;y++)s[p[y]]||(s[p[y]]=!0,f.push(p[y]));return f},[])},_Te=function(e,r){return e==="horizontal"&&r==="xAxis"||e==="vertical"&&r==="yAxis"||e==="centric"&&r==="angleAxis"||e==="radial"&&r==="radiusAxis"},vTe=function(e,r,n,i){if(i)return e.map(function(f){return f.coordinate});var o,c,s=e.map(function(f){return f.coordinate===r&&(o=!0),f.coordinate===n&&(c=!0),f.coordinate});return o||s.push(r),c||s.push(n),s},Ep=function(e,r,n){if(!e)return null;var i=e.scale,o=e.duplicateDomain,c=e.type,s=e.range,f=e.realScaleType==="scaleBand"?i.bandwidth()/2:2,p=(r||n)&&c==="category"&&i.bandwidth?i.bandwidth()/f:0;if(p=e.axisType==="angleAxis"&&(s==null?void 0:s.length)>=2?Zc(s[0]-s[1])*2*p:p,r&&(e.ticks||e.niceTicks)){var y=(e.ticks||e.niceTicks).map(function(_){var T=o?o.indexOf(_):_;return{coordinate:i(T)+p,value:_,offset:p}});return y.filter(function(_){return!IC(_.coordinate)})}return e.isCategorical&&e.categoricalDomain?e.categoricalDomain.map(function(_,T){return{coordinate:i(_)+p,value:_,index:T,offset:p}}):i.ticks&&!n?i.ticks(e.tickCount).map(function(_){return{coordinate:i(_)+p,value:_,offset:p}}):i.domain().map(function(_,T){return{coordinate:i(_)+p,value:o?o[_]:_,index:T,offset:p}})},x$=new WeakMap,dR=function(e,r){if(typeof r!="function")return e;x$.has(e)||x$.set(e,new WeakMap);var n=x$.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},bTe=function(e,r,n){var i=e.scale,o=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:_M(),realScaleType:"linear"}:o==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:ZA(),realScaleType:"point"}:o==="category"?{scale:nk(),realScaleType:"band"}:{scale:_M(),realScaleType:"linear"};if(H_(i)){var f="scale".concat(lF(i));return{scale:(Tae[f]||ZA)(),realScaleType:Tae[f]?f:"point"}}return _i(i)?{scale:i}:{scale:ZA(),realScaleType:"point"}},Pae=1e-4,wTe=function(e){var r=e.domain();if(!(!r||r.length<=2)){var n=r.length,i=e.range(),o=Math.min(i[0],i[1])-Pae,c=Math.max(i[0],i[1])+Pae,s=e(r[0]),f=e(r[n-1]);(sc||fc)&&e.domain([r[0],r[n-1]])}},vwt=function(e,r){if(!e)return null;for(var n=0,i=e.length;ni)&&(o[1]=i),o[0]>i&&(o[0]=i),o[1]=0?(e[s][n][0]=o,e[s][n][1]=o+f,o=e[s][n][1]):(e[s][n][0]=c,e[s][n][1]=c+f,c=e[s][n][1])}},Swt=function(e){var r=e.length;if(!(r<=0))for(var n=0,i=e[0].length;n=0?(e[c][n][0]=o,e[c][n][1]=o+s,o=e[c][n][1]):(e[c][n][0]=0,e[c][n][1]=0)}},Twt={sign:wwt,expand:Vct,none:X1,silhouette:qct,wiggle:Gct,positive:Swt},Ewt=function(e,r,n){var i=r.map(function(s){return s.props.dataKey}),o=Twt[n],c=Uct().keys(i).value(function(s,f){return+Xl(s,f,0)}).order(p8).offset(o);return c(e)},Awt=function(e,r,n,i,o,c){if(!e)return null;var s=c?r.reverse():r,f={},p=s.reduce(function(_,T){var E,k=(E=T.type)!==null&&E!==void 0&&E.defaultProps?mo(mo({},T.type.defaultProps),T.props):T.props,P=k.stackId,R=k.hide;if(R)return _;var D=k[n],M=_[D]||{hasStack:!1,stackGroups:{}};if(fl(P)){var B=M.stackGroups[P]||{numericAxisId:n,cateAxisId:i,items:[]};B.items.push(T),M.hasStack=!0,M.stackGroups[P]=B}else M.stackGroups[NC("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[T]};return mo(mo({},_),{},s1({},D,M))},f),y={};return Object.keys(p).reduce(function(_,T){var E=p[T];if(E.hasStack){var k={};E.stackGroups=Object.keys(E.stackGroups).reduce(function(P,R){var D=E.stackGroups[R];return mo(mo({},P),{},s1({},R,{numericAxisId:n,cateAxisId:i,items:D.items,stackedData:Ewt(e,D.items,o)}))},k)}return mo(mo({},_),{},s1({},T,E))},y)},STe=function(e,r){var n=r.realScaleType,i=r.type,o=r.tickCount,c=r.originalDomain,s=r.allowDecimals,f=n||r.scale;if(f!=="auto"&&f!=="linear")return null;if(o&&i==="number"&&c&&(c[0]==="auto"||c[1]==="auto")){var p=e.domain();if(!p.length)return null;var y=zbt(p,o,s);return e.domain([TF(y),SF(y)]),{niceTicks:y}}if(o&&i==="number"){var _=e.domain(),T=$bt(_,o,s);return{niceTicks:T}}return null};function FGt(t){var e=t.axis,r=t.ticks,n=t.bandSize,i=t.entry,o=t.index,c=t.dataKey;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!Fi(i[e.dataKey])){var s=QD(r,"value",i[e.dataKey]);if(s)return s.coordinate+n/2}return r[o]?r[o].coordinate+n/2:null}var f=Xl(i,Fi(c)?e.dataKey:c);return Fi(f)?null:e.scale(f)}var Rae=function(e){var r=e.axis,n=e.ticks,i=e.offset,o=e.bandSize,c=e.entry,s=e.index;if(r.type==="category")return n[s]?n[s].coordinate+i:null;var f=Xl(c,r.dataKey,r.domain[s]);return Fi(f)?null:r.scale(f)-o/2+i},jwt=function(e){var r=e.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),o=Math.max(n[0],n[1]);return i<=0&&o>=0?0:o<0?o:i}return n[0]},kwt=function(e,r){var n,i=(n=e.type)!==null&&n!==void 0&&n.defaultProps?mo(mo({},e.type.defaultProps),e.props):e.props,o=i.stackId;if(fl(o)){var c=r[o];if(c){var s=c.items.indexOf(e);return s>=0?c.stackedData[s]:null}}return null},Cwt=function(e){return e.reduce(function(r,n){return[TF(n.concat([r[0]]).filter(Wr)),SF(n.concat([r[1]]).filter(Wr))]},[1/0,-1/0])},TTe=function(e,r,n){return Object.keys(e).reduce(function(i,o){var c=e[o],s=c.stackedData,f=s.reduce(function(p,y){var _=Cwt(y.slice(r,n+1));return[Math.min(p[0],_[0]),Math.max(p[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})},Lae=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Dae=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,H8=function(e,r,n){if(_i(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(Lae.test(e[0])){var o=+Lae.exec(e[0])[1];i[0]=r[0]-o}else _i(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(Dae.test(e[1])){var c=+Dae.exec(e[1])[1];i[1]=r[1]+c}else _i(e[1])?i[1]=e[1](r[1]):i[1]=r[1];return i},AM=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 o=nW(r,function(_){return _.coordinate}),c=1/0,s=1,f=o.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},Fwt=function(e,r,n,i,o){var c=e.width,s=e.height,f=e.startAngle,p=e.endAngle,y=Xc(e.cx,c,c/2),_=Xc(e.cy,s,s/2),T=jTe(c,s,n),E=Xc(e.innerRadius,T,0),k=Xc(e.outerRadius,T,T*.8),P=Object.keys(r);return P.reduce(function(R,D){var M=r[D],B=M.domain,V=M.reversed,G;if(Fi(M.range))i==="angleAxis"?G=[f,p]:i==="radiusAxis"&&(G=[E,k]),V&&(G=[G[1],G[0]]);else{G=M.range;var W=G,Z=Pwt(W,2);f=Z[0],p=Z[1]}var Q=bTe(M,o),re=Q.realScaleType,se=Q.scale;se.domain(B).range(G),wTe(se);var ue=STe(se,mp(mp({},M),{},{realScaleType:re})),_e=mp(mp(mp({},M),ue),{},{range:G,radius:k,realScaleType:re,scale:se,cx:y,cy:_,innerRadius:E,outerRadius:k,startAngle:f,endAngle:p});return mp(mp({},R),{},ATe({},D,_e))},{})},Bwt=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return Math.sqrt(Math.pow(n-o,2)+Math.pow(i-c,2))},zwt=function(e,r){var n=e.x,i=e.y,o=r.cx,c=r.cy,s=Bwt({x:n,y:i},{x:o,y:c});if(s<=0)return{radius:s};var f=(n-o)/s,p=Math.acos(f);return i>c&&(p=2*Math.PI-p),{radius:s,angle:Owt(p),angleInRadian:p}},$wt=function(e){var r=e.startAngle,n=e.endAngle,i=Math.floor(r/360),o=Math.floor(n/360),c=Math.min(i,o);return{startAngle:r-c*360,endAngle:n-c*360}},Uwt=function(e,r){var n=r.startAngle,i=r.endAngle,o=Math.floor(n/360),c=Math.floor(i/360),s=Math.min(o,c);return e+s*360},Bae=function(e,r){var n=e.x,i=e.y,o=zwt({x:n,y:i},r),c=o.radius,s=o.angle,f=r.innerRadius,p=r.outerRadius;if(cp)return!1;if(c===0)return!0;var y=$wt(r),_=y.startAngle,T=y.endAngle,E=s,k;if(_<=T){for(;E>T;)E-=360;for(;E<_;)E+=360;k=E>=_&&E<=T}else{for(;E>_;)E-=360;for(;E=T&&E<=_}return k?mp(mp({},r),{},{radius:c,angle:Uwt(E,r)}):null},kTe=function(e){return!I.isValidElement(e)&&!_i(e)&&typeof e!="boolean"?e.className:""};function fk(t){"@babel/helpers - typeof";return fk=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},fk(t)}var Vwt=["offset"];function qwt(t){return Kwt(t)||Wwt(t)||Hwt(t)||Gwt()}function Gwt(){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 Hwt(t,e){if(t){if(typeof t=="string")return W8(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 W8(t,e)}}function Wwt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function Kwt(t){if(Array.isArray(t))return W8(t)}function W8(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 Zwt(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 zae(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 rl(t){for(var e=1;e=0?1:-1,B,V;i==="insideStart"?(B=E+M*c,V=P):i==="insideEnd"?(B=k-M*c,V=!P):i==="end"&&(B=k+M*c,V=P),V=D<=0?V:!V;var G=xa(p,y,R,B),W=xa(p,y,R,B+(V?1:-1)*359),Z="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=Fi(e.id)?NC("recharts-radial-line-"):e.id;return Xe.createElement("text",mk({},n,{dominantBaseline:"central",className:Oi("recharts-radial-bar-label",s)}),Xe.createElement("defs",null,Xe.createElement("path",{id:Q,d:Z})),Xe.createElement("textPath",{xlinkHref:"#".concat(Q)},r))},n1t=function(e){var r=e.viewBox,n=e.offset,i=e.position,o=r,c=o.cx,s=o.cy,f=o.innerRadius,p=o.outerRadius,y=o.startAngle,_=o.endAngle,T=(y+_)/2;if(i==="outside"){var E=xa(c,s,p+n,T),k=E.x,P=E.y;return{x:k,y:P,textAnchor:k>=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+p)/2,D=xa(c,s,R,T),M=D.x,B=D.y;return{x:M,y:B,textAnchor:"middle",verticalAnchor:"middle"}},i1t=function(e){var r=e.viewBox,n=e.parentViewBox,i=e.offset,o=e.position,c=r,s=c.x,f=c.y,p=c.width,y=c.height,_=y>=0?1:-1,T=_*i,E=_>0?"end":"start",k=_>0?"start":"end",P=p>=0?1:-1,R=P*i,D=P>0?"end":"start",M=P>0?"start":"end";if(o==="top"){var B={x:s+p/2,y:f-_*i,textAnchor:"middle",verticalAnchor:E};return rl(rl({},B),n?{height:Math.max(f-n.y,0),width:p}:{})}if(o==="bottom"){var V={x:s+p/2,y:f+y+T,textAnchor:"middle",verticalAnchor:k};return rl(rl({},V),n?{height:Math.max(n.y+n.height-(f+y),0),width:p}:{})}if(o==="left"){var G={x:s-R,y:f+y/2,textAnchor:D,verticalAnchor:"middle"};return rl(rl({},G),n?{width:Math.max(G.x-n.x,0),height:y}:{})}if(o==="right"){var W={x:s+p+R,y:f+y/2,textAnchor:M,verticalAnchor:"middle"};return rl(rl({},W),n?{width:Math.max(n.x+n.width-W.x,0),height:y}:{})}var Z=n?{width:p,height:y}:{};return o==="insideLeft"?rl({x:s+R,y:f+y/2,textAnchor:M,verticalAnchor:"middle"},Z):o==="insideRight"?rl({x:s+p-R,y:f+y/2,textAnchor:D,verticalAnchor:"middle"},Z):o==="insideTop"?rl({x:s+p/2,y:f+T,textAnchor:"middle",verticalAnchor:k},Z):o==="insideBottom"?rl({x:s+p/2,y:f+y-T,textAnchor:"middle",verticalAnchor:E},Z):o==="insideTopLeft"?rl({x:s+R,y:f+T,textAnchor:M,verticalAnchor:k},Z):o==="insideTopRight"?rl({x:s+p-R,y:f+T,textAnchor:D,verticalAnchor:k},Z):o==="insideBottomLeft"?rl({x:s+R,y:f+y-T,textAnchor:M,verticalAnchor:E},Z):o==="insideBottomRight"?rl({x:s+p-R,y:f+y-T,textAnchor:D,verticalAnchor:E},Z):eT(o)&&(Wr(o.x)||h_(o.x))&&(Wr(o.y)||h_(o.y))?rl({x:s+Xc(o.x,p),y:f+Xc(o.y,y),textAnchor:"end",verticalAnchor:"end"},Z):rl({x:s+p/2,y:f+y/2,textAnchor:"middle",verticalAnchor:"middle"},Z)},s1t=function(e){return"cx"in e&&Wr(e.cx)};function Nl(t){var e=t.offset,r=e===void 0?5:e,n=Ywt(t,Vwt),i=rl({offset:r},n),o=i.viewBox,c=i.position,s=i.value,f=i.children,p=i.content,y=i.className,_=y===void 0?"":y,T=i.textBreakAll;if(!o||Fi(s)&&Fi(f)&&!I.isValidElement(p)&&!_i(p))return null;if(I.isValidElement(p))return I.cloneElement(p,i);var E;if(_i(p)){if(E=I.createElement(p,i),I.isValidElement(E))return E}else E=e1t(i);var k=s1t(o),P=fi(i,!0);if(k&&(c==="insideStart"||c==="insideEnd"||c==="end"))return r1t(i,E,P);var R=k?n1t(i):i1t(i);return Xe.createElement(K_,mk({className:Oi("recharts-label",_)},P,R,{breakAll:T}),E)}Nl.displayName="Label";var CTe=function(e){var r=e.cx,n=e.cy,i=e.angle,o=e.startAngle,c=e.endAngle,s=e.r,f=e.radius,p=e.innerRadius,y=e.outerRadius,_=e.x,T=e.y,E=e.top,k=e.left,P=e.width,R=e.height,D=e.clockWise,M=e.labelViewBox;if(M)return M;if(Wr(P)&&Wr(R)){if(Wr(_)&&Wr(T))return{x:_,y:T,width:P,height:R};if(Wr(E)&&Wr(k))return{x:E,y:k,width:P,height:R}}return Wr(_)&&Wr(T)?{x:_,y:T,width:0,height:0}:Wr(r)&&Wr(n)?{cx:r,cy:n,startAngle:o||i||0,endAngle:c||i||0,innerRadius:p||0,outerRadius:y||f||s||0,clockWise:D}:e.viewBox?e.viewBox:{}},a1t=function(e,r){return e?e===!0?Xe.createElement(Nl,{key:"label-implicit",viewBox:r}):fl(e)?Xe.createElement(Nl,{key:"label-implicit",viewBox:r,value:e}):I.isValidElement(e)?e.type===Nl?I.cloneElement(e,{key:"label-implicit",viewBox:r}):Xe.createElement(Nl,{key:"label-implicit",content:e,viewBox:r}):_i(e)?Xe.createElement(Nl,{key:"label-implicit",content:e,viewBox:r}):eT(e)?Xe.createElement(Nl,mk({viewBox:r},e,{key:"label-implicit"})):null:null},o1t=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,o=CTe(e),c=nh(i,Nl).map(function(f,p){return I.cloneElement(f,{viewBox:r||o,key:"label-".concat(p)})});if(!n)return c;var s=a1t(e.label,r||o);return[s].concat(qwt(c))};Nl.parseViewBox=CTe;Nl.renderCallByParent=o1t;function l1t(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var c1t=l1t;const u1t=ds(c1t);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)}var d1t=["valueAccessor"],h1t=["data","dataKey","clockWise","id","textBreakAll"];function f1t(t){return y1t(t)||g1t(t)||p1t(t)||m1t()}function m1t(){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 p1t(t,e){if(t){if(typeof t=="string")return K8(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 K8(t,e)}}function g1t(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function y1t(t){if(Array.isArray(t))return K8(t)}function K8(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 b1t(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 w1t=function(e){return Array.isArray(e.value)?u1t(e.value):e.value};function qy(t){var e=t.valueAccessor,r=e===void 0?w1t:e,n=Vae(t,d1t),i=n.data,o=n.dataKey,c=n.clockWise,s=n.id,f=n.textBreakAll,p=Vae(n,h1t);return!i||!i.length?null:Xe.createElement($s,{className:"recharts-label-list"},i.map(function(y,_){var T=Fi(o)?r(y,_):Xl(y&&y.payload,o),E=Fi(s)?{}:{id:"".concat(s,"-").concat(_)};return Xe.createElement(Nl,kM({},fi(y,!0),p,E,{parentViewBox:y.parentViewBox,value:T,textBreakAll:f,viewBox:Nl.parseViewBox(Fi(c)?y:Uae(Uae({},y),{},{clockWise:c})),key:"label-".concat(_),index:_}))}))}qy.displayName="LabelList";function S1t(t,e){return t?t===!0?Xe.createElement(qy,{key:"labelList-implicit",data:e}):Xe.isValidElement(t)||_i(t)?Xe.createElement(qy,{key:"labelList-implicit",data:e,content:t}):eT(t)?Xe.createElement(qy,kM({data:e},t,{key:"labelList-implicit"})):null:null}function T1t(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=nh(n,qy).map(function(c,s){return I.cloneElement(c,{data:e,key:"labelList-".concat(s)})});if(!r)return i;var o=S1t(t.label,e);return[o].concat(f1t(i))}qy.renderCallByParent=T1t;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 Y8(){return Y8=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>p),`, `).concat(_.x,",").concat(_.y,` `);if(i>0){var E=xa(r,n,i,c),k=xa(r,n,i,p);T+="L ".concat(k.x,",").concat(k.y,` A `).concat(i,",").concat(i,`,0, `).concat(+(Math.abs(f)>180),",").concat(+(c<=p),`, `).concat(E.x,",").concat(E.y," Z")}else T+="L ".concat(r,",").concat(n," Z");return T},C1t=function(e){var r=e.cx,n=e.cy,i=e.innerRadius,o=e.outerRadius,c=e.cornerRadius,s=e.forceCornerRadius,f=e.cornerIsExternal,p=e.startAngle,y=e.endAngle,_=Zc(y-p),T=hR({cx:r,cy:n,radius:o,angle:p,sign:_,cornerRadius:c,cornerIsExternal:f}),E=T.circleTangency,k=T.lineTangency,P=T.theta,R=hR({cx:r,cy:n,radius:o,angle:y,sign:-_,cornerRadius:c,cornerIsExternal:f}),D=R.circleTangency,M=R.lineTangency,B=R.theta,V=f?Math.abs(p-y):Math.abs(p-y)-P-B;if(V<0)return s?"M ".concat(k.x,",").concat(k.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 `):ITe({cx:r,cy:n,innerRadius:i,outerRadius:o,startAngle:p,endAngle:y});var G="M ".concat(k.x,",").concat(k.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(_<0),",").concat(E.x,",").concat(E.y,` A`).concat(o,",").concat(o,",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=hR({cx:r,cy:n,radius:i,angle:p,sign:_,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),Z=W.circleTangency,Q=W.lineTangency,re=W.theta,se=hR({cx:r,cy:n,radius:i,angle:y,sign:-_,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),ue=se.circleTangency,_e=se.lineTangency,we=se.theta,Ce=f?Math.abs(p-y):Math.abs(p-y)-re-we;if(Ce<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(+(Ce>180),",").concat(+(_>0),",").concat(Z.x,",").concat(Z.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},I1t={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},NTe=function(e){var r=Gae(Gae({},I1t),e),n=r.cx,i=r.cy,o=r.innerRadius,c=r.outerRadius,s=r.cornerRadius,f=r.forceCornerRadius,p=r.cornerIsExternal,y=r.startAngle,_=r.endAngle,T=r.className;if(c0&&Math.abs(y-_)<360?R=C1t({cx:n,cy:i,innerRadius:o,outerRadius:c,cornerRadius:Math.min(P,k/2),forceCornerRadius:f,cornerIsExternal:p,startAngle:y,endAngle:_}):R=ITe({cx:n,cy:i,innerRadius:o,outerRadius:c,startAngle:y,endAngle:_}),Xe.createElement("path",Y8({},fi(r,!0),{className:E,d:R,role:"img"}))};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 Z8(){return Z8=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 G1t(t,e){return uT(t.getTime(),e.getTime())}function Jae(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.entries(),o=0,c,s;(c=i.next())&&!c.done;){for(var f=e.entries(),p=!1,y=0;(s=f.next())&&!s.done;){var _=c.value,T=_[0],E=_[1],k=s.value,P=k[0],R=k[1];!p&&!n[y]&&(p=r.equals(T,P,o,y,t,e,r)&&r.equals(E,R,T,P,t,e,r))&&(n[y]=!0),y++}if(!p)return!1;o++}return!0}function H1t(t,e,r){var n=Qae(t),i=n.length;if(Qae(e).length!==i)return!1;for(var o;i-- >0;)if(o=n[i],o===MTe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!DTe(e,o)||!r.equals(t[o],e[o],o,o,t,e,r))return!1;return!0}function rA(t,e,r){var n=Zae(t),i=n.length;if(Zae(e).length!==i)return!1;for(var o,c,s;i-- >0;)if(o=n[i],o===MTe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!DTe(e,o)||!r.equals(t[o],e[o],o,o,t,e,r)||(c=Xae(t,o),s=Xae(e,o),(c||s)&&(!c||!s||c.configurable!==s.configurable||c.enumerable!==s.enumerable||c.writable!==s.writable)))return!1;return!0}function W1t(t,e){return uT(t.valueOf(),e.valueOf())}function K1t(t,e){return t.source===e.source&&t.flags===e.flags}function eoe(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.values(),o,c;(o=i.next())&&!o.done;){for(var s=e.values(),f=!1,p=0;(c=s.next())&&!c.done;)!f&&!n[p]&&(f=r.equals(o.value,c.value,o.value,c.value,t,e,r))&&(n[p]=!0),p++;if(!f)return!1}return!0}function Y1t(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 Z1t="[object Arguments]",X1t="[object Boolean]",Q1t="[object Date]",J1t="[object Map]",eSt="[object Number]",tSt="[object Object]",rSt="[object RegExp]",nSt="[object Set]",iSt="[object String]",sSt=Array.isArray,toe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,roe=Object.assign,aSt=Object.prototype.toString.call.bind(Object.prototype.toString);function oSt(t){var e=t.areArraysEqual,r=t.areDatesEqual,n=t.areMapsEqual,i=t.areObjectsEqual,o=t.arePrimitiveWrappersEqual,c=t.areRegExpsEqual,s=t.areSetsEqual,f=t.areTypedArraysEqual;return function(y,_,T){if(y===_)return!0;if(y==null||_==null||typeof y!="object"||typeof _!="object")return y!==y&&_!==_;var E=y.constructor;if(E!==_.constructor)return!1;if(E===Object)return i(y,_,T);if(sSt(y))return e(y,_,T);if(toe!=null&&toe(y))return f(y,_,T);if(E===Date)return r(y,_,T);if(E===RegExp)return c(y,_,T);if(E===Map)return n(y,_,T);if(E===Set)return s(y,_,T);var k=aSt(y);return k===Q1t?r(y,_,T):k===rSt?c(y,_,T):k===J1t?n(y,_,T):k===nSt?s(y,_,T):k===tSt?typeof y.then!="function"&&typeof _.then!="function"&&i(y,_,T):k===Z1t?i(y,_,T):k===X1t||k===eSt||k===iSt?o(y,_,T):!1}}function lSt(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,i={areArraysEqual:n?rA:q1t,areDatesEqual:G1t,areMapsEqual:n?Yae(Jae,rA):Jae,areObjectsEqual:n?rA:H1t,arePrimitiveWrappersEqual:W1t,areRegExpsEqual:K1t,areSetsEqual:n?Yae(eoe,rA):eoe,areTypedArraysEqual:n?rA:Y1t};if(r&&(i=roe({},i,r(i))),e){var o=mR(i.areArraysEqual),c=mR(i.areMapsEqual),s=mR(i.areObjectsEqual),f=mR(i.areSetsEqual);i=roe({},i,{areArraysEqual:o,areMapsEqual:c,areObjectsEqual:s,areSetsEqual:f})}return i}function cSt(t){return function(e,r,n,i,o,c,s){return t(e,r,s)}}function uSt(t){var e=t.circular,r=t.comparator,n=t.createState,i=t.equals,o=t.strict;if(n)return function(f,p){var y=n(),_=y.cache,T=_===void 0?e?new WeakMap:void 0:_,E=y.meta;return r(f,p,{cache:T,equals:i,meta:E,strict:o})};if(e)return function(f,p){return r(f,p,{cache:new WeakMap,equals:i,meta:void 0,strict:o})};var c={cache:void 0,equals:i,meta:void 0,strict:o};return function(f,p){return r(f,p,c)}}var dSt=Cx();Cx({strict:!0});Cx({circular:!0});Cx({circular:!0,strict:!0});Cx({createInternalComparator:function(){return uT}});Cx({strict:!0,createInternalComparator:function(){return uT}});Cx({circular:!0,createInternalComparator:function(){return uT}});Cx({circular:!0,createInternalComparator:function(){return uT},strict:!0});function Cx(t){t===void 0&&(t={});var e=t.circular,r=e===void 0?!1:e,n=t.createInternalComparator,i=t.createState,o=t.strict,c=o===void 0?!1:o,s=lSt(t),f=oSt(s),p=n?n(f):cSt(f);return uSt({circular:r,comparator:f,createState:i,equals:p,strict:c})}function hSt(t){typeof requestAnimationFrame<"u"&&requestAnimationFrame(t)}function noe(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(o){r<0&&(r=o),o-r>e?(t(o),r=-1):hSt(i)};requestAnimationFrame(n)}function Q8(t){"@babel/helpers - typeof";return Q8=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},Q8(t)}function fSt(t){return ySt(t)||gSt(t)||pSt(t)||mSt()}function mSt(){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 pSt(t,e){if(t){if(typeof t=="string")return ioe(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 ioe(t,e)}}function ioe(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},P=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,o=i===void 0?8:i,c=e.dt,s=c===void 0?17:c,f=function(y,_,T){var E=-(y-_)*n,k=T*o,P=T+(E-k)*s/1e3,R=T*s/1e3+y;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 KSt(t,e){if(t==null)return{};var r={},n=Object.keys(t),i,o;for(o=0;o=0)&&(r[i]=t[i]);return r}function _$(t){return QSt(t)||XSt(t)||ZSt(t)||YSt()}function YSt(){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 ZSt(t,e){if(t){if(typeof t=="string")return nq(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 nq(t,e)}}function XSt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function QSt(t){if(Array.isArray(t))return nq(t)}function nq(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 NM(t){return NM=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},NM(t)}var Wp=function(t){nTt(r,t);var e=iTt(r);function r(n,i){var o;JSt(this,r),o=e.call(this,n,i);var c=o.props,s=c.isActive,f=c.attributeName,p=c.from,y=c.to,_=c.steps,T=c.children,E=c.duration;if(o.handleStyleChange=o.handleStyleChange.bind(aq(o)),o.changeStyle=o.changeStyle.bind(aq(o)),!s||E<=0)return o.state={style:{}},typeof T=="function"&&(o.state={style:y}),sq(o);if(_&&_.length)o.state={style:_[0].style};else if(p){if(typeof T=="function")return o.state={style:p},sq(o);o.state={style:f?bA({},f,p):p}}else o.state={style:{}};return o}return tTt(r,[{key:"componentDidMount",value:function(){var i=this.props,o=i.isActive,c=i.canBegin;this.mounted=!0,!(!o||!c)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var o=this.props,c=o.isActive,s=o.canBegin,f=o.attributeName,p=o.shouldReAnimate,y=o.to,_=o.from,T=this.state.style;if(s){if(!c){var E={style:f?bA({},f,y):y};this.state&&T&&(f&&T[f]!==y||!f&&T!==y)&&this.setState(E);return}if(!(dSt(i.to,y)&&i.canBegin&&i.isActive)){var k=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var P=k||p?_:i.to;if(this.state&&T){var R={style:f?bA({},f,P):P};(f&&T[f]!==P||!f&&T!==P)&&this.setState(R)}this.runAnimation(Rh(Rh({},this.props),{},{from:P,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var o=this,c=i.from,s=i.to,f=i.duration,p=i.easing,y=i.begin,_=i.onAnimationEnd,T=i.onAnimationStart,E=GSt(c,s,LSt(p),f,this.changeStyle),k=function(){o.stopJSAnimation=E()};this.manager.start([T,y,k,f,_])}},{key:"runStepAnimation",value:function(i){var o=this,c=i.steps,s=i.begin,f=i.onAnimationStart,p=c[0],y=p.style,_=p.duration,T=_===void 0?0:_,E=function(P,R,D){if(D===0)return P;var M=R.duration,B=R.easing,V=B===void 0?"ease":B,G=R.style,W=R.properties,Z=R.onAnimationEnd,Q=D>0?c[D-1]:R,re=W||Object.keys(G);if(typeof V=="function"||V==="spring")return[].concat(_$(P),[o.runJSAnimation.bind(o,{from:Q.style,to:G,duration:M,easing:V}),M]);var se=ooe(re,M,V),ue=Rh(Rh(Rh({},Q.style),G),{},{transition:se});return[].concat(_$(P),[ue,M,Z]).filter(wSt)};return this.manager.start([f].concat(_$(c.reduce(E,[y,Math.max(T,s)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=xSt());var o=i.begin,c=i.duration,s=i.attributeName,f=i.to,p=i.easing,y=i.onAnimationStart,_=i.onAnimationEnd,T=i.steps,E=i.children,k=this.manager;if(this.unSubscribe=k.subscribe(this.handleStyleChange),typeof p=="function"||typeof E=="function"||p==="spring"){this.runJSAnimation(i);return}if(T.length>1){this.runStepAnimation(i);return}var P=s?bA({},s,f):f,R=ooe(Object.keys(P),c,p);k.start([y,o,Rh(Rh({},P),{},{transition:R}),c,_])}},{key:"render",value:function(){var i=this.props,o=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=WSt(i,HSt),p=I.Children.count(o),y=this.state.style;if(typeof o=="function")return o(y);if(!s||p===0||c<=0)return o;var _=function(E){var k=E.props,P=k.style,R=P===void 0?{}:P,D=k.className,M=I.cloneElement(E,Rh(Rh({},f),{},{style:Rh(Rh({},R),y),className:D}));return M};return p===1?_(I.Children.only(o)):Xe.createElement("div",null,I.Children.map(o,function(T){return _(T)}))}}]),r}(I.PureComponent);Wp.displayName="Animate";Wp.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Wp.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 vk(t){"@babel/helpers - typeof";return vk=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},vk(t)}function PM(){return PM=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,p=i>=0&&n>=0||i<0&&n<0?1:0,y;if(c>0&&o instanceof Array){for(var _=[0,0,0,0],T=0,E=4;Tc?c:o[T];y="M".concat(e,",").concat(r+s*_[0]),_[0]>0&&(y+="A ".concat(_[0],",").concat(_[0],",0,0,").concat(p,",").concat(e+f*_[0],",").concat(r)),y+="L ".concat(e+n-f*_[1],",").concat(r),_[1]>0&&(y+="A ".concat(_[1],",").concat(_[1],",0,0,").concat(p,`, `).concat(e+n,",").concat(r+s*_[1])),y+="L ".concat(e+n,",").concat(r+i-s*_[2]),_[2]>0&&(y+="A ".concat(_[2],",").concat(_[2],",0,0,").concat(p,`, `).concat(e+n-f*_[2],",").concat(r+i)),y+="L ".concat(e+f*_[3],",").concat(r+i),_[3]>0&&(y+="A ".concat(_[3],",").concat(_[3],",0,0,").concat(p,`, `).concat(e,",").concat(r+i-s*_[3])),y+="Z"}else if(c>0&&o===+o&&o>0){var k=Math.min(c,o);y="M ".concat(e,",").concat(r+s*k,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+f*k,",").concat(r,` L `).concat(e+n-f*k,",").concat(r,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+n,",").concat(r+s*k,` L `).concat(e+n,",").concat(r+i-s*k,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+n-f*k,",").concat(r+i,` L `).concat(e+f*k,",").concat(r+i,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e,",").concat(r+i-s*k," Z")}else y="M ".concat(e,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return y},mTt=function(e,r){if(!e||!r)return!1;var n=e.x,i=e.y,o=r.x,c=r.y,s=r.width,f=r.height;if(Math.abs(s)>0&&Math.abs(f)>0){var p=Math.min(o,o+s),y=Math.max(o,o+s),_=Math.min(c,c+f),T=Math.max(c,c+f);return n>=p&&n<=y&&i>=_&&i<=T}return!1},pTt={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},IW=function(e){var r=poe(poe({},pTt),e),n=I.useRef(),i=I.useState(-1),o=aTt(i,2),c=o[0],s=o[1];I.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var V=n.current.getTotalLength();V&&s(V)}catch{}},[]);var f=r.x,p=r.y,y=r.width,_=r.height,T=r.radius,E=r.className,k=r.animationEasing,P=r.animationDuration,R=r.animationBegin,D=r.isAnimationActive,M=r.isUpdateAnimationActive;if(f!==+f||p!==+p||y!==+y||_!==+_||y===0||_===0)return null;var B=Oi("recharts-rectangle",E);return M?Xe.createElement(Wp,{canBegin:c>0,from:{width:y,height:_,x:f,y:p},to:{width:y,height:_,x:f,y:p},duration:P,animationEasing:k,isActive:M},function(V){var G=V.width,W=V.height,Z=V.x,Q=V.y;return Xe.createElement(Wp,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:P,isActive:D,easing:k},Xe.createElement("path",PM({},fi(r,!0),{className:B,d:goe(Z,Q,G,W,T),ref:n})))}):Xe.createElement("path",PM({},fi(r,!0),{className:B,d:goe(f,p,y,_,T)}))},gTt=["points","className","baseLinePoints","connectNulls"];function Mw(){return Mw=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 xTt(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 yoe(t){return wTt(t)||bTt(t)||vTt(t)||_Tt()}function _Tt(){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 vTt(t,e){if(t){if(typeof t=="string")return oq(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 oq(t,e)}}function bTt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function wTt(t){if(Array.isArray(t))return oq(t)}function oq(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){xoe(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),xoe(e[0])&&r[r.length-1].push(e[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},JA=function(e,r){var n=STt(e);r&&(n=[n.reduce(function(o,c){return[].concat(yoe(o),yoe(c))},[])]);var i=n.map(function(o){return o.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},TTt=function(e,r,n){var i=JA(e,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(JA(r.reverse(),n).slice(1))},ETt=function(e){var r=e.points,n=e.className,i=e.baseLinePoints,o=e.connectNulls,c=yTt(e,gTt);if(!r||!r.length)return null;var s=Oi("recharts-polygon",n);if(i&&i.length){var f=c.stroke&&c.stroke!=="none",p=TTt(r,i,o);return Xe.createElement("g",{className:s},Xe.createElement("path",Mw({},fi(c,!0),{fill:p.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:p})),f?Xe.createElement("path",Mw({},fi(c,!0),{fill:"none",d:JA(r,o)})):null,f?Xe.createElement("path",Mw({},fi(c,!0),{fill:"none",d:JA(i,o)})):null)}var y=JA(r,o);return Xe.createElement("path",Mw({},fi(c,!0),{fill:y.slice(-1)==="Z"?c.fill:"none",className:s,d:y}))};function lq(){return lq=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 PTt(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 RTt=function(e,r,n,i,o,c){return"M".concat(e,",").concat(o,"v").concat(i,"M").concat(c,",").concat(r,"h").concat(n)},LTt=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.top,s=c===void 0?0:c,f=e.left,p=f===void 0?0:f,y=e.width,_=y===void 0?0:y,T=e.height,E=T===void 0?0:T,k=e.className,P=NTt(e,ATt),R=jTt({x:n,y:o,top:s,left:p,width:_,height:E},P);return!Wr(n)||!Wr(o)||!Wr(_)||!Wr(E)||!Wr(s)||!Wr(p)?null:Xe.createElement("path",cq({},fi(R,!0),{className:Oi("recharts-cross",k),d:RTt(n,o,_,E,s,p)}))},DTt=wF,MTt=JSe,OTt=Em;function FTt(t,e){return t&&t.length?DTt(t,OTt(e),MTt):void 0}var BTt=FTt;const zTt=ds(BTt);var $Tt=wF,UTt=Em,VTt=eTe;function qTt(t,e){return t&&t.length?$Tt(t,UTt(e),VTt):void 0}var GTt=qTt;const HTt=ds(GTt);var WTt=["cx","cy","angle","ticks","axisLine"],KTt=["ticks","tick","angle","tickFormatter","stroke"];function oS(t){"@babel/helpers - typeof";return oS=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},oS(t)}function ej(){return ej=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 YTt(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 ZTt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function woe(t,e){for(var r=0;rEoe?c=i==="outer"?"start":"end":o<-Eoe?c=i==="outer"?"end":"start":c="middle",c}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,o=n.cy,c=n.radius,s=n.axisLine,f=n.axisLineType,p=G0(G0({},fi(this.props,!1)),{},{fill:"none"},fi(s,!1));if(f==="circle")return Xe.createElement(NW,i_({className:"recharts-polar-angle-axis-line"},p,{cx:i,cy:o,r:c}));var y=this.props.ticks,_=y.map(function(T){return xa(i,o,c,T.coordinate)});return Xe.createElement(ETt,i_({className:"recharts-polar-angle-axis-line"},p,{points:_}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,o=i.ticks,c=i.tick,s=i.tickLine,f=i.tickFormatter,p=i.stroke,y=fi(this.props,!1),_=fi(c,!1),T=G0(G0({},y),{},{fill:"none"},fi(s,!1)),E=o.map(function(k,P){var R=n.getTickLineCoord(k),D=n.getTickTextAnchor(k),M=G0(G0(G0({textAnchor:D},y),{},{stroke:"none",fill:p},_),{},{index:P,payload:k,x:R.x2,y:R.y2});return Xe.createElement($s,i_({className:Oi("recharts-polar-angle-axis-tick",kTe(c)),key:"tick-".concat(k.coordinate)},W_(n.props,k,P)),s&&Xe.createElement("line",i_({className:"recharts-polar-angle-axis-tick-line"},T,R)),c&&e.renderTickItem(c,M,f?f(k.value,P):k.value))});return Xe.createElement($s,{className:"recharts-polar-angle-axis-ticks"},E)}},{key:"render",value:function(){var n=this.props,i=n.ticks,o=n.radius,c=n.axisLine;return o<=0||!i||!i.length?null:Xe.createElement($s,{className:Oi("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,o){var c;return Xe.isValidElement(n)?c=Xe.cloneElement(n,i):_i(n)?c=n(i):c=Xe.createElement(K_,i_({},i,{className:"recharts-polar-angle-axis-tick-value"}),o),c}}])}(I.PureComponent);NF(PF,"displayName","PolarAngleAxis");NF(PF,"axisType","angleAxis");NF(PF,"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 dEt=Y1e,hEt=dEt(Object.getPrototypeOf,Object),fEt=hEt,mEt=Qp,pEt=fEt,gEt=Jp,yEt="[object Object]",xEt=Function.prototype,_Et=Object.prototype,WTe=xEt.toString,vEt=_Et.hasOwnProperty,bEt=WTe.call(Object);function wEt(t){if(!gEt(t)||mEt(t)!=yEt)return!1;var e=pEt(t);if(e===null)return!0;var r=vEt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&WTe.call(r)==bEt}var SEt=wEt;const TEt=ds(SEt);var EEt=Qp,AEt=Jp,jEt="[object Boolean]";function kEt(t){return t===!0||t===!1||AEt(t)&&EEt(t)==jEt}var CEt=kEt;const IEt=ds(CEt);function wk(t){"@babel/helpers - typeof";return wk=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},wk(t)}function DM(){return DM=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:p},to:{upperWidth:y,lowerWidth:_,height:T,x:f,y:p},duration:P,animationEasing:k,isActive:D},function(B){var V=B.upperWidth,G=B.lowerWidth,W=B.height,Z=B.x,Q=B.y;return Xe.createElement(Wp,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:P,easing:k},Xe.createElement("path",DM({},fi(r,!0),{className:M,d:Coe(Z,Q,V,G,W),ref:n})))}):Xe.createElement("g",null,Xe.createElement("path",DM({},fi(r,!0),{className:M,d:Coe(f,p,y,_,T)})))},$Et=["option","shapeType","propTransformer","activeClassName","isActive"];function Sk(t){"@babel/helpers - typeof";return Sk=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},Sk(t)}function UEt(t,e){if(t==null)return{};var r=VEt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function VEt(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 Ioe(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 MM(t){for(var e=1;e0?ld(B,"paddingAngle",0):0;if(G){var Z=oy(G.endAngle-G.startAngle,B.endAngle-B.startAngle),Q=pa(pa({},B),{},{startAngle:M+W,endAngle:M+Z(P)+W});R.push(Q),M=Q.endAngle}else{var re=B.endAngle,se=B.startAngle,ue=oy(0,re-se),_e=ue(P),we=pa(pa({},B),{},{startAngle:M+W,endAngle:M+_e+W});R.push(we),M=we.endAngle}}),Xe.createElement($s,null,n.renderSectorsStatically(R))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(o){if(!o.altKey)switch(o.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,o=n.isAnimationActive,c=this.state.prevSectors;return o&&i&&i.length&&(!c||!EF(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,o=i.hide,c=i.sectors,s=i.className,f=i.label,p=i.cx,y=i.cy,_=i.innerRadius,T=i.outerRadius,E=i.isAnimationActive,k=this.state.isAnimationFinished;if(o||!c||!c.length||!Wr(p)||!Wr(y)||!Wr(_)||!Wr(T))return null;var P=Oi("recharts-pie",s);return Xe.createElement($s,{tabIndex:this.props.rootTabIndex,className:P,ref:function(D){n.pieRef=D}},this.renderSectors(),f&&this.renderLabels(c),Nl.renderCallByParent(this.props,null,!1),(!E||k)&&qy.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=Xl(re,D,0);return Q+(Wr(se)?se:0)},0),W;if(G>0){var Z;W=i.map(function(Q,re){var se=Xl(Q,D,0),ue=Xl(Q,y,re),_e=(Wr(se)?se:0)/G,we;re?we=Z.endAngle+Zc(P)*f*(se!==0?1:0):we=c;var Ce=we+Zc(P)*((se!==0?E:0)+_e*V),Me=(we+Ce)/2,Ae=(k.innerRadius+k.outerRadius)/2,be=[{name:ue,value:se,payload:Q,dataKey:D,type:T}],me=xa(k.cx,k.cy,Ae,Me);return Z=pa(pa(pa({percent:_e,cornerRadius:o,name:ue,tooltipPayload:be,midAngle:Me,middleRadius:Ae,tooltipPosition:me},Q),k),{},{value:Xl(Q,D),startAngle:we,endAngle:Ce,payload:Q,paddingAngle:Zc(P)*f}),Z})}return pa(pa({},k),{},{sectors:W,data:i})});var u2t=Math.ceil,d2t=Math.max;function h2t(t,e,r,n){for(var i=-1,o=d2t(u2t((e-t)/(r||1)),0),c=Array(o);o--;)c[n?o:++i]=t,t+=r;return c}var f2t=h2t,m2t=mSe,Loe=1/0,p2t=17976931348623157e292;function g2t(t){if(!t)return t===0?t:0;if(t=m2t(t),t===Loe||t===-Loe){var e=t<0?-1:1;return e*p2t}return t===t?t:0}var XTe=g2t,y2t=f2t,x2t=mF,v$=XTe;function _2t(t){return function(e,r,n){return n&&typeof n!="number"&&x2t(e,r,n)&&(r=n=void 0),e=v$(e),r===void 0?(r=e,e=0):r=v$(r),n=n===void 0?e0&&n.handleDrag(i.changedTouches[0])}),Ku(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,o=i.endIndex,c=i.onDragEnd,s=i.startIndex;c==null||c({endIndex:o,startIndex:s})}),n.detachDragEndListener()}),Ku(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Ku(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Ku(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Ku(n,"handleSlideDragStart",function(i){var o=Boe(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:o.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return R2t(e,t),C2t(e,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,o=n.endX,c=this.state.scaleValues,s=this.props,f=s.gap,p=s.data,y=p.length-1,_=Math.min(i,o),T=Math.max(i,o),E=e.getIndexInRange(c,_),k=e.getIndexInRange(c,T);return{startIndex:E-E%f,endIndex:k===y?y:k-k%f}}},{key:"getTextOfTick",value:function(n){var i=this.props,o=i.data,c=i.tickFormatter,s=i.dataKey,f=Xl(o[n],s,n);return _i(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,o=i.slideMoveStartX,c=i.startX,s=i.endX,f=this.props,p=f.x,y=f.width,_=f.travellerWidth,T=f.startIndex,E=f.endIndex,k=f.onChange,P=n.pageX-o;P>0?P=Math.min(P,p+y-_-s,p+y-_-c):P<0&&(P=Math.max(P,p-c,p-s));var R=this.getIndex({startX:c+P,endX:s+P});(R.startIndex!==T||R.endIndex!==E)&&k&&k(R),this.setState({startX:c+P,endX:s+P,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var o=Boe(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:o.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,o=i.brushMoveStartX,c=i.movingTravellerId,s=i.endX,f=i.startX,p=this.state[c],y=this.props,_=y.x,T=y.width,E=y.travellerWidth,k=y.onChange,P=y.gap,R=y.data,D={startX:this.state.startX,endX:this.state.endX},M=n.pageX-o;M>0?M=Math.min(M,_+T-E-p):M<0&&(M=Math.max(M,_-p)),D[c]=p+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%P===0:G%P===0)||sf?G%P===0:V%P===0)||s>f&&G===Q};this.setState(Ku(Ku({},c,p+M),"brushMoveStartX",n.pageX),function(){k&&W()&&k(B)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var o=this,c=this.state,s=c.scaleValues,f=c.startX,p=c.endX,y=this.state[i],_=s.indexOf(y);if(_!==-1){var T=_+n;if(!(T===-1||T>=s.length)){var E=s[T];i==="startX"&&E>=p||i==="endX"&&E<=f||this.setState(Ku({},i,E),function(){o.props.onChange(o.getIndex({startX:o.state.startX,endX:o.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,s=n.height,f=n.fill,p=n.stroke;return Xe.createElement("rect",{stroke:p,fill:f,x:i,y:o,width:c,height:s})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,s=n.height,f=n.data,p=n.children,y=n.padding,_=I.Children.only(p);return _?Xe.cloneElement(_,{x:i,y:o,width:c,height:s,margin:y,compact:!0,data:f}):null}},{key:"renderTravellerLayer",value:function(n,i){var o,c,s=this,f=this.props,p=f.y,y=f.travellerWidth,_=f.height,T=f.traveller,E=f.ariaLabel,k=f.data,P=f.startIndex,R=f.endIndex,D=Math.max(n,this.props.x),M=b$(b$({},fi(this.props,!1)),{},{x:D,y:p,width:y,height:_}),B=E||"Min value: ".concat((o=k[P])===null||o===void 0?void 0:o.name,", Max value: ").concat((c=k[R])===null||c===void 0?void 0:c.name);return Xe.createElement($s,{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 o=this.props,c=o.y,s=o.height,f=o.stroke,p=o.travellerWidth,y=Math.min(n,i)+p,_=Math.max(Math.abs(i-n)-p,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,y:c,width:_,height:s})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,o=n.endIndex,c=n.y,s=n.height,f=n.travellerWidth,p=n.stroke,y=this.state,_=y.startX,T=y.endX,E=5,k={pointerEvents:"none",fill:p};return Xe.createElement($s,{className:"recharts-brush-texts"},Xe.createElement(K_,BM({textAnchor:"end",verticalAnchor:"middle",x:Math.min(_,T)-E,y:c+s/2},k),this.getTextOfTick(i)),Xe.createElement(K_,BM({textAnchor:"start",verticalAnchor:"middle",x:Math.max(_,T)+f+E,y:c+s/2},k),this.getTextOfTick(o)))}},{key:"render",value:function(){var n=this.props,i=n.data,o=n.className,c=n.children,s=n.x,f=n.y,p=n.width,y=n.height,_=n.alwaysShowText,T=this.state,E=T.startX,k=T.endX,P=T.isTextActive,R=T.isSlideMoving,D=T.isTravellerMoving,M=T.isTravellerFocused;if(!i||!i.length||!Wr(s)||!Wr(f)||!Wr(p)||!Wr(y)||p<=0||y<=0)return null;var B=Oi("recharts-brush",o),V=Xe.Children.count(c)===1,G=j2t("userSelect","none");return Xe.createElement($s,{className:B,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:G},this.renderBackground(),V&&this.renderPanorama(),this.renderSlide(E,k),this.renderTravellerLayer(E,"startX"),this.renderTravellerLayer(k,"endX"),(P||R||D||M||_)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,o=n.y,c=n.width,s=n.height,f=n.stroke,p=Math.floor(o+s/2)-1;return Xe.createElement(Xe.Fragment,null,Xe.createElement("rect",{x:i,y:o,width:c,height:s,fill:f,stroke:"none"}),Xe.createElement("line",{x1:i+1,y1:p,x2:i+c-1,y2:p,fill:"none",stroke:"#fff"}),Xe.createElement("line",{x1:i+1,y1:p+2,x2:i+c-1,y2:p+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var o;return Xe.isValidElement(n)?o=Xe.cloneElement(n,i):_i(n)?o=n(i):o=e.renderDefaultTraveller(i),o}},{key:"getDerivedStateFromProps",value:function(n,i){var o=n.data,c=n.width,s=n.x,f=n.travellerWidth,p=n.updateId,y=n.startIndex,_=n.endIndex;if(o!==i.prevData||p!==i.prevUpdateId)return b$({prevData:o,prevTravellerWidth:f,prevUpdateId:p,prevX:s,prevWidth:c},o&&o.length?D2t({data:o,width:c,x:s,travellerWidth:f,startIndex:y,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:o,prevTravellerWidth:f,prevUpdateId:p,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 o=n.length,c=0,s=o-1;s-c>1;){var f=Math.floor((c+s)/2);n[f]>i?s=f:c=f}return i>=n[s]?s:c}}])}(I.PureComponent);Ku(dS,"displayName","Brush");Ku(dS,"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 M2t=rW;function O2t(t,e){var r;return M2t(t,function(n,i,o){return r=e(n,i,o),!r}),!!r}var F2t=O2t,B2t=$1e,z2t=Em,$2t=F2t,U2t=Mu,V2t=mF;function q2t(t,e,r){var n=U2t(t)?B2t:$2t;return r&&V2t(t,e,r)&&(e=void 0),n(t,z2t(e))}var G2t=q2t;const H2t=ds(G2t);var lm=function(e,r){var n=e.alwaysShow,i=e.ifOverflow;return n&&(i="extendDomain"),i===r},zoe=cSe;function W2t(t,e,r){e=="__proto__"&&zoe?zoe(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var K2t=W2t,Y2t=K2t,Z2t=oSe,X2t=Em;function Q2t(t,e){var r={};return e=X2t(e),Z2t(t,function(n,i,o){Y2t(r,i,e(n,i,o))}),r}var J2t=Q2t;const eAt=ds(J2t);function tAt(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 xAt(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 _At(t,e){var r=t.x,n=t.y,i=yAt(t,fAt),o="".concat(r),c=parseInt(o,10),s="".concat(n),f=parseInt(s,10),p="".concat(e.height||i.height),y=parseInt(p,10),_="".concat(e.width||i.width),T=parseInt(_,10);return nA(nA(nA(nA(nA({},e),i),c?{x:c}:{}),f?{y:f}:{}),{},{height:y,width:T,name:e.name,radius:e.radius})}function Uoe(t){return Xe.createElement(KTe,mq({shapeType:"rectangle",propTransformer:_At,activeClassName:"recharts-active-bar"},t))}var vAt=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 o=Wr(n)||rlt(n);return o?e(n,i):(o||Z_(),r)}},bAt=["value","background"],rEe;function hS(t){"@babel/helpers - typeof";return hS=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},hS(t)}function wAt(t,e){if(t==null)return{};var r=SAt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function SAt(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 $M(){return $M=Object.assign?Object.assign.bind():function(t){for(var e=1;e0&&Math.abs(Me)0&&Math.abs(Ce)0&&(we=Math.min((rt||0)-(Ce[at-1]||0),we))}),Number.isFinite(we)){var Me=we/_e,Ae=P.layout==="vertical"?n.height:n.width;if(P.padding==="gap"&&(Z=Me*Ae/2),P.padding==="no-gap"){var be=Xc(e.barCategoryGap,Me*Ae),me=Me*Ae/2;Z=me-be-(me-be)/Ae*be}}}i==="xAxis"?Q=[n.left+(B.left||0)+(Z||0),n.left+n.width-(B.right||0)-(Z||0)]:i==="yAxis"?Q=f==="horizontal"?[n.top+n.height-(B.bottom||0),n.top+(B.top||0)]:[n.top+(B.top||0)+(Z||0),n.top+n.height-(B.bottom||0)-(Z||0)]:Q=P.range,G&&(Q=[Q[1],Q[0]]);var Pe=bTe(P,o,T),Ie=Pe.scale,Se=Pe.realScaleType;Ie.domain(D).range(Q),wTe(Ie);var ve=STe(Ie,qh(qh({},P),{},{realScaleType:Se}));i==="xAxis"?(ue=R==="top"&&!V||R==="bottom"&&V,re=n.left,se=_[W]-ue*P.height):i==="yAxis"&&(ue=R==="left"&&!V||R==="right"&&V,re=_[W]-ue*P.width,se=n.top);var We=qh(qh(qh({},P),ve),{},{realScaleType:Se,x:re,y:se,scale:Ie,width:i==="xAxis"?n.width:P.width,height:i==="yAxis"?n.height:P.height});return We.bandSize=AM(We,ve),!P.hide&&i==="xAxis"?_[W]+=(ue?-1:1)*We.height:P.hide||(_[W]+=(ue?-1:1)*We.width),qh(qh({},E),{},DF({},k,We))},{})},aEe=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return{x:Math.min(n,o),y:Math.min(i,c),width:Math.abs(o-n),height:Math.abs(c-i)}},DAt=function(e){var r=e.x1,n=e.y1,i=e.x2,o=e.y2;return aEe({x:r,y:n},{x:i,y:o})},oEe=function(){function t(e){NAt(this,t),this.scale=e}return PAt(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,o=n.position;if(r!==void 0){if(o)switch(o){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],o=n[n.length-1];return i<=o?r>=i&&r<=o:r>=o&&r<=i}}],[{key:"create",value:function(r){return new t(r)}}])}();DF(oEe,"EPS",1e-4);var PW=function(e){var r=Object.keys(e).reduce(function(n,i){return qh(qh({},n),{},DF({},i,oEe.create(e[i])))},{});return qh(qh({},r),{},{apply:function(i){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=o.bandAware,s=o.position;return eAt(i,function(f,p){return r[p].apply(f,{bandAware:c,position:s})})},isInRange:function(i){return tEe(i,function(o,c){return r[c].isInRange(o)})}})};function MAt(t){return(t%180+180)%180}var OAt=function(e){var r=e.width,n=e.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=MAt(i),c=o*Math.PI/180,s=Math.atan(n/r),f=c>s&&c-1?i[o?e[c]:c]:void 0}}var UAt=$At,VAt=XTe;function qAt(t){var e=VAt(t),r=e%1;return e===e?r?e-r:e:0}var GAt=qAt,HAt=tSe,WAt=Em,KAt=GAt,YAt=Math.max;function ZAt(t,e,r){var n=t==null?0:t.length;if(!n)return-1;var i=r==null?0:KAt(r);return i<0&&(i=YAt(n+i,0)),HAt(t,WAt(e),i)}var XAt=ZAt,QAt=UAt,JAt=XAt,ejt=QAt(JAt),tjt=ejt;const rjt=ds(tjt);var njt=aot(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("")}),RW=I.createContext(void 0),LW=I.createContext(void 0),lEe=I.createContext(void 0),cEe=I.createContext({}),uEe=I.createContext(void 0),dEe=I.createContext(0),hEe=I.createContext(0),Woe=function(e){var r=e.state,n=r.xAxisMap,i=r.yAxisMap,o=r.offset,c=e.clipPathId,s=e.children,f=e.width,p=e.height,y=njt(o);return Xe.createElement(RW.Provider,{value:n},Xe.createElement(LW.Provider,{value:i},Xe.createElement(cEe.Provider,{value:o},Xe.createElement(lEe.Provider,{value:y},Xe.createElement(uEe.Provider,{value:c},Xe.createElement(dEe.Provider,{value:p},Xe.createElement(hEe.Provider,{value:f},s)))))))},ijt=function(){return I.useContext(uEe)},fEe=function(e){var r=I.useContext(RW);r==null&&Z_();var n=r[e];return n==null&&Z_(),n},sjt=function(){var e=I.useContext(RW);return my(e)},ajt=function(){var e=I.useContext(LW),r=rjt(e,function(n){return tEe(n.domain,Number.isFinite)});return r||my(e)},mEe=function(e){var r=I.useContext(LW);r==null&&Z_();var n=r[e];return n==null&&Z_(),n},ojt=function(){var e=I.useContext(lEe);return e},ljt=function(){return I.useContext(cEe)},DW=function(){return I.useContext(hEe)},MW=function(){return I.useContext(dEe)};function fS(t){"@babel/helpers - typeof";return fS=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},fS(t)}function cjt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ujt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);rt*i)return!1;var o=r();return t*(e-t*o/2-n)>=0&&t*(e+t*o/2-i)<=0}function Gjt(t,e){return bEe(t,e+1)}function Hjt(t,e,r,n,i){for(var o=(n||[]).slice(),c=e.start,s=e.end,f=0,p=1,y=c,_=function(){var k=n==null?void 0:n[f];if(k===void 0)return{v:bEe(n,p)};var P=f,R,D=function(){return R===void 0&&(R=r(k,P)),R},M=k.coordinate,B=f===0||HM(t,M,D,y,s);B||(f=0,y=c,p+=1),B&&(y=M+t*(D()/2+i),f+=p)},T;p<=o.length;)if(T=_(),T)return T.v;return[]}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 tle(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 yc(t){for(var e=1;e0?E.coordinate-R*t:E.coordinate})}else o[T]=E=yc(yc({},E),{},{tickCoord:E.coordinate});var D=HM(t,E.tickCoord,P,s,f);D&&(f=E.tickCoord-t*(P()/2+i),o[T]=yc(yc({},E),{},{isShow:!0}))},y=c-1;y>=0;y--)p(y);return o}function Xjt(t,e,r,n,i,o){var c=(n||[]).slice(),s=c.length,f=e.start,p=e.end;if(o){var y=n[s-1],_=r(y,s-1),T=t*(y.coordinate+t*_/2-p);c[s-1]=y=yc(yc({},y),{},{tickCoord:T>0?y.coordinate-T*t:y.coordinate});var E=HM(t,y.tickCoord,function(){return _},f,p);E&&(p=y.tickCoord-t*(_/2+i),c[s-1]=yc(yc({},y),{},{isShow:!0}))}for(var k=o?s-1:s,P=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=yc(yc({},B),{},{tickCoord:W<0?B.coordinate-W*t:B.coordinate})}else c[M]=B=yc(yc({},B),{},{tickCoord:B.coordinate});var Z=HM(t,B.tickCoord,G,f,p);Z&&(f=B.tickCoord+t*(G()/2+i),c[M]=yc(yc({},B),{},{isShow:!0}))},R=0;R=2?Zc(i[1].coordinate-i[0].coordinate):1,D=qjt(o,R,E);return f==="equidistantPreserveStart"?Hjt(R,D,P,i,c):(f==="preserveStart"||f==="preserveStartEnd"?T=Xjt(R,D,P,i,c,f==="preserveStartEnd"):T=Zjt(R,D,P,i,c),T.filter(function(M){return M.isShow}))}var Qjt=["viewBox"],Jjt=["viewBox"],ekt=["ticks"];function gS(t){"@babel/helpers - typeof";return gS=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},gS(t)}function Fw(){return Fw=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 tkt(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 rkt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function nle(t,e){for(var r=0;r0?f(this.props):f(E)),c<=0||s<=0||!k||!k.length?null:Xe.createElement($s,{className:Oi("recharts-cartesian-axis",p),ref:function(R){n.layerReference=R}},o&&this.renderAxisLine(),this.renderTicks(k,this.state.fontSize,this.state.letterSpacing),Nl.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,o){var c,s=Oi(i.className,"recharts-cartesian-axis-tick-value");return Xe.isValidElement(n)?c=Xe.cloneElement(n,tl(tl({},i),{},{className:s})):_i(n)?c=n(tl(tl({},i),{},{className:s})):c=Xe.createElement(K_,Fw({},i,{className:"recharts-cartesian-axis-tick-value"}),o),c}}])}(I.Component);zW(dT,"displayName","CartesianAxis");zW(dT,"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 ckt=["x1","y1","x2","y2","key"],ukt=["offset"];function X_(t){"@babel/helpers - typeof";return X_=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},X_(t)}function ile(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 _c(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function mkt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var pkt=function(e){var r=e.fill;if(!r||r==="none")return null;var n=e.fillOpacity,i=e.x,o=e.y,c=e.width,s=e.height,f=e.ry;return Xe.createElement("rect",{x:i,y:o,ry:f,width:c,height:s,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function TEe(t,e){var r;if(Xe.isValidElement(t))r=Xe.cloneElement(t,e);else if(_i(t))r=t(e);else{var n=e.x1,i=e.y1,o=e.x2,c=e.y2,s=e.key,f=sle(e,ckt),p=fi(f,!1);p.offset;var y=sle(p,ukt);r=Xe.createElement("line",p_({},y,{x1:n,y1:i,x2:o,y2:c,fill:"none",key:s}))}return r}function gkt(t){var e=t.x,r=t.width,n=t.horizontal,i=n===void 0?!0:n,o=t.horizontalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(s,f){var p=_c(_c({},t),{},{x1:e,y1:s,x2:e+r,y2:s,key:"line-".concat(f),index:f});return TEe(i,p)});return Xe.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function ykt(t){var e=t.y,r=t.height,n=t.vertical,i=n===void 0?!0:n,o=t.verticalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(s,f){var p=_c(_c({},t),{},{x1:s,y1:e,x2:s,y2:e+r,key:"line-".concat(f),index:f});return TEe(i,p)});return Xe.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function xkt(t){var e=t.horizontalFill,r=t.fillOpacity,n=t.x,i=t.y,o=t.width,c=t.height,s=t.horizontalPoints,f=t.horizontal,p=f===void 0?!0:f;if(!p||!e||!e.length)return null;var y=s.map(function(T){return Math.round(T+i-i)}).sort(function(T,E){return T-E});i!==y[0]&&y.unshift(0);var _=y.map(function(T,E){var k=!y[E+1],P=k?i+c-T:y[E+1]-T;if(P<=0)return null;var R=E%e.length;return Xe.createElement("rect",{key:"react-".concat(E),y:T,x:n,height:P,width:o,stroke:"none",fill:e[R],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},_)}function _kt(t){var e=t.vertical,r=e===void 0?!0:e,n=t.verticalFill,i=t.fillOpacity,o=t.x,c=t.y,s=t.width,f=t.height,p=t.verticalPoints;if(!r||!n||!n.length)return null;var y=p.map(function(T){return Math.round(T+o-o)}).sort(function(T,E){return T-E});o!==y[0]&&y.unshift(0);var _=y.map(function(T,E){var k=!y[E+1],P=k?o+s-T:y[E+1]-T;if(P<=0)return null;var R=E%n.length;return Xe.createElement("rect",{key:"react-".concat(E),x:T,y:c,width:P,height:f,stroke:"none",fill:n[R],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},_)}var vkt=function(e,r){var n=e.xAxis,i=e.width,o=e.height,c=e.offset;return vTe(BW(_c(_c(_c({},dT.defaultProps),n),{},{ticks:Ep(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.left,c.left+c.width,r)},bkt=function(e,r){var n=e.yAxis,i=e.width,o=e.height,c=e.offset;return vTe(BW(_c(_c(_c({},dT.defaultProps),n),{},{ticks:Ep(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.top,c.top+c.height,r)},aw={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function EEe(t){var e,r,n,i,o,c,s=DW(),f=MW(),p=ljt(),y=_c(_c({},t),{},{stroke:(e=t.stroke)!==null&&e!==void 0?e:aw.stroke,fill:(r=t.fill)!==null&&r!==void 0?r:aw.fill,horizontal:(n=t.horizontal)!==null&&n!==void 0?n:aw.horizontal,horizontalFill:(i=t.horizontalFill)!==null&&i!==void 0?i:aw.horizontalFill,vertical:(o=t.vertical)!==null&&o!==void 0?o:aw.vertical,verticalFill:(c=t.verticalFill)!==null&&c!==void 0?c:aw.verticalFill,x:Wr(t.x)?t.x:p.left,y:Wr(t.y)?t.y:p.top,width:Wr(t.width)?t.width:p.width,height:Wr(t.height)?t.height:p.height}),_=y.x,T=y.y,E=y.width,k=y.height,P=y.syncWithTicks,R=y.horizontalValues,D=y.verticalValues,M=sjt(),B=ajt();if(!Wr(E)||E<=0||!Wr(k)||k<=0||!Wr(_)||_!==+_||!Wr(T)||T!==+T)return null;var V=y.verticalCoordinatesGenerator||vkt,G=y.horizontalCoordinatesGenerator||bkt,W=y.horizontalPoints,Z=y.verticalPoints;if((!W||!W.length)&&_i(G)){var Q=R&&R.length,re=G({yAxis:B?_c(_c({},B),{},{ticks:Q?R:B.ticks}):void 0,width:s,height:f,offset:p},Q?!0:P);sf(Array.isArray(re),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(X_(re),"]")),Array.isArray(re)&&(W=re)}if((!Z||!Z.length)&&_i(V)){var se=D&&D.length,ue=V({xAxis:M?_c(_c({},M),{},{ticks:se?D:M.ticks}):void 0,width:s,height:f,offset:p},se?!0:P);sf(Array.isArray(ue),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(X_(ue),"]")),Array.isArray(ue)&&(Z=ue)}return Xe.createElement("g",{className:"recharts-cartesian-grid"},Xe.createElement(pkt,{fill:y.fill,fillOpacity:y.fillOpacity,x:y.x,y:y.y,width:y.width,height:y.height,ry:y.ry}),Xe.createElement(gkt,p_({},y,{offset:p,horizontalPoints:W,xAxis:M,yAxis:B})),Xe.createElement(ykt,p_({},y,{offset:p,verticalPoints:Z,xAxis:M,yAxis:B})),Xe.createElement(xkt,p_({},y,{horizontalPoints:W})),Xe.createElement(_kt,p_({},y,{verticalPoints:Z})))}EEe.displayName="CartesianGrid";function yS(t){"@babel/helpers - typeof";return yS=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},yS(t)}function wkt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Skt(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 cCt(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 uCt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function dCt(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(o)?e.slice(i,o+1):[]};function BEe(t){return t==="number"?[0,"auto"]:void 0}var Nq=function(e,r,n,i){var o=e.graphicalItems,c=e.tooltipAxis,s=UF(r,e);return n<0||!o||!o.length||n>=s.length?null:o.reduce(function(f,p){var y,_=(y=p.props.data)!==null&&y!==void 0?y: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=QD(E,c.dataKey,i)}else T=_&&_[n]||s[n];return T?[].concat(vS(f),[ETe(p,T)]):f},[])},dle=function(e,r,n,i){var o=i||{x:e.chartX,y:e.chartY},c=SCt(o,n),s=e.orderedTooltipTicks,f=e.tooltipAxis,p=e.tooltipTicks,y=mwt(c,s,p,f);if(y>=0&&p){var _=p[y]&&p[y].value,T=Nq(e,r,y,_),E=TCt(n,s,y,o);return{activeTooltipIndex:y,activeLabel:_,activePayload:T,activeCoordinate:E}}return null},ECt=function(e,r){var n=r.axes,i=r.graphicalItems,o=r.axisType,c=r.axisIdKey,s=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.layout,_=e.children,T=e.stackOffset,E=_Te(y,o);return n.reduce(function(k,P){var R,D=P.type.defaultProps!==void 0?vr(vr({},P.type.defaultProps),P.props):P.props,M=D.type,B=D.dataKey,V=D.allowDataOverflow,G=D.allowDuplicatedCategory,W=D.scale,Z=D.ticks,Q=D.includeHidden,re=D[c];if(k[re])return k;var se=UF(e.data,{graphicalItems:i.filter(function(ve){var We,rt=c in ve.props?ve.props[c]:(We=ve.type.defaultProps)===null||We===void 0?void 0:We[c];return rt===re}),dataStartIndex:f,dataEndIndex:p}),ue=se.length,_e,we,Ce;Xkt(D.domain,V,M)&&(_e=H8(D.domain,null,V),E&&(M==="number"||W!=="auto")&&(Ce=XA(se,B,"category")));var Me=BEe(M);if(!_e||_e.length===0){var Ae,be=(Ae=D.domain)!==null&&Ae!==void 0?Ae:Me;if(B){if(_e=XA(se,B,M),M==="category"&&E){var me=ilt(_e);G&&me?(we=_e,_e=FM(0,ue)):G||(_e=Mae(be,_e,P).reduce(function(ve,We){return ve.indexOf(We)>=0?ve:[].concat(vS(ve),[We])},[]))}else if(M==="category")G?_e=_e.filter(function(ve){return ve!==""&&!Fi(ve)}):_e=Mae(be,_e,P).reduce(function(ve,We){return ve.indexOf(We)>=0||We===""||Fi(We)?ve:[].concat(vS(ve),[We])},[]);else if(M==="number"){var Pe=_wt(se,i.filter(function(ve){var We,rt,at=c in ve.props?ve.props[c]:(We=ve.type.defaultProps)===null||We===void 0?void 0:We[c],Et="hide"in ve.props?ve.props.hide:(rt=ve.type.defaultProps)===null||rt===void 0?void 0:rt.hide;return at===re&&(Q||!Et)}),B,o,y);Pe&&(_e=Pe)}E&&(M==="number"||W!=="auto")&&(Ce=XA(se,B,"category"))}else E?_e=FM(0,ue):s&&s[re]&&s[re].hasStack&&M==="number"?_e=T==="expand"?[0,1]:TTe(s[re].stackGroups,f,p):_e=xTe(se,i.filter(function(ve){var We=c in ve.props?ve.props[c]:ve.type.defaultProps[c],rt="hide"in ve.props?ve.props.hide:ve.type.defaultProps.hide;return We===re&&(Q||!rt)}),M,y,!0);if(M==="number")_e=kq(_,_e,re,o,Z),be&&(_e=H8(be,_e,V));else if(M==="category"&&be){var Ie=be,Se=_e.every(function(ve){return Ie.indexOf(ve)>=0});Se&&(_e=Ie)}}return vr(vr({},k),{},ii({},re,vr(vr({},D),{},{axisType:o,domain:_e,categoricalDomain:Ce,duplicateDomain:we,originalDomain:(R=D.domain)!==null&&R!==void 0?R:Me,isCategorical:E,layout:y})))},{})},ACt=function(e,r){var n=r.graphicalItems,i=r.Axis,o=r.axisType,c=r.axisIdKey,s=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.layout,_=e.children,T=UF(e.data,{graphicalItems:n,dataStartIndex:f,dataEndIndex:p}),E=T.length,k=_Te(y,o),P=-1;return n.reduce(function(R,D){var M=D.type.defaultProps!==void 0?vr(vr({},D.type.defaultProps),D.props):D.props,B=M[c],V=BEe("number");if(!R[B]){P++;var G;return k?G=FM(0,E):s&&s[B]&&s[B].hasStack?(G=TTe(s[B].stackGroups,f,p),G=kq(_,G,B,o)):(G=H8(V,xTe(T,n.filter(function(W){var Z,Q,re=c in W.props?W.props[c]:(Z=W.type.defaultProps)===null||Z===void 0?void 0:Z[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",y),i.defaultProps.allowDataOverflow),G=kq(_,G,B,o)),vr(vr({},R),{},ii({},B,vr(vr({axisType:o},i.defaultProps),{},{hide:!0,orientation:ld(bCt,"".concat(o,".").concat(P%2),null),domain:G,originalDomain:V,isCategorical:k,layout:y})))}return R},{})},jCt=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,o=r.AxisComp,c=r.graphicalItems,s=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.children,_="".concat(i,"Id"),T=nh(y,o),E={};return T&&T.length?E=ECt(e,{axes:T,graphicalItems:c,axisType:i,axisIdKey:_,stackGroups:s,dataStartIndex:f,dataEndIndex:p}):c&&c.length&&(E=ACt(e,{Axis:o,graphicalItems:c,axisType:i,axisIdKey:_,stackGroups:s,dataStartIndex:f,dataEndIndex:p})),E},kCt=function(e){var r=my(e),n=Ep(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:nW(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:AM(r,n)}},hle=function(e){var r=e.children,n=e.defaultShowTooltip,i=Qu(r,dS),o=0,c=0;return e.data&&e.data.length!==0&&(c=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(o=i.props.startIndex),i.props.endIndex>=0&&(c=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:o,dataEndIndex:c,activeTooltipIndex:-1,isTooltipActive:!!n}},CCt=function(e){return!e||!e.length?!1:e.some(function(r){var n=Cp(r&&r.type);return n&&n.indexOf("Bar")>=0})},fle=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"}},ICt=function(e,r){var n=e.props,i=e.graphicalItems,o=e.xAxisMap,c=o===void 0?{}:o,s=e.yAxisMap,f=s===void 0?{}:s,p=n.width,y=n.height,_=n.children,T=n.margin||{},E=Qu(_,dS),k=Qu(_,n1),P=Object.keys(f).reduce(function(G,W){var Z=f[W],Q=Z.orientation;return!Z.mirror&&!Z.hide?vr(vr({},G),{},ii({},Q,G[Q]+Z.width)):G},{left:T.left||0,right:T.right||0}),R=Object.keys(c).reduce(function(G,W){var Z=c[W],Q=Z.orientation;return!Z.mirror&&!Z.hide?vr(vr({},G),{},ii({},Q,ld(G,"".concat(Q))+Z.height)):G},{top:T.top||0,bottom:T.bottom||0}),D=vr(vr({},R),P),M=D.bottom;E&&(D.bottom+=E.props.height||dS.defaultProps.height),k&&r&&(D=ywt(D,i,n,r));var B=p-D.left-D.right,V=y-D.top-D.bottom;return vr(vr({brushBottom:M},D),{},{width:Math.max(B,0),height:Math.max(V,0)})},NCt=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},zEe=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,o=i===void 0?"axis":i,c=e.validateTooltipEventTypes,s=c===void 0?["axis"]:c,f=e.axisComponents,p=e.legendContent,y=e.formatAxisMap,_=e.defaultProps,T=function(D,M){var B=M.graphicalItems,V=M.stackGroups,G=M.offset,W=M.updateId,Z=M.dataStartIndex,Q=M.dataEndIndex,re=D.barSize,se=D.layout,ue=D.barGap,_e=D.barCategoryGap,we=D.maxBarSize,Ce=fle(se),Me=Ce.numericAxisName,Ae=Ce.cateAxisName,be=CCt(B),me=[];return B.forEach(function(Pe,Ie){var Se=UF(D.data,{graphicalItems:[Pe],dataStartIndex:Z,dataEndIndex:Q}),ve=Pe.type.defaultProps!==void 0?vr(vr({},Pe.type.defaultProps),Pe.props):Pe.props,We=ve.dataKey,rt=ve.maxBarSize,at=ve["".concat(Me,"Id")],Et=ve["".concat(Ae,"Id")],_t={},Vt=f.reduce(function(At,Mt){var dr=M["".concat(Mt.axisType,"Map")],ur=ve["".concat(Mt.axisType,"Id")];dr&&dr[ur]||Mt.axisType==="zAxis"||Z_();var hr=dr[ur];return vr(vr({},At),{},ii(ii({},Mt.axisType,hr),"".concat(Mt.axisType,"Ticks"),Ep(hr)))},_t),pt=Vt[Ae],Nt=Vt["".concat(Ae,"Ticks")],er=V&&V[at]&&V[at].hasStack&&kwt(Pe,V[at].stackGroups),vt=Cp(Pe.type).indexOf("Bar")>=0,or=AM(pt,Nt),Sr=[],nn=be&&pwt({barSize:re,stackGroups:V,totalSize:NCt(Vt,Ae)});if(vt){var cr,xr,tr=Fi(rt)?we:rt,_n=(cr=(xr=AM(pt,Nt,!0))!==null&&xr!==void 0?xr:tr)!==null&&cr!==void 0?cr:0;Sr=gwt({barGap:ue,barCategoryGap:_e,bandSize:_n!==or?_n:or,sizeList:nn[Et],maxBarSize:tr}),_n!==or&&(Sr=Sr.map(function(At){return vr(vr({},At),{},{position:vr(vr({},At.position),{},{offset:At.position.offset-_n/2})})}))}var lt=Pe&&Pe.type&&Pe.type.getComposedData;lt&&me.push({props:vr(vr({},lt(vr(vr({},Vt),{},{displayedData:Se,props:D,dataKey:We,item:Pe,bandSize:or,barPosition:Sr,offset:G,stackedData:er,layout:se,dataStartIndex:Z,dataEndIndex:Q}))),{},ii(ii(ii({key:Pe.key||"item-".concat(Ie)},Me,Vt[Me]),Ae,Vt[Ae]),"animationId",W)),childIndex:glt(Pe,D.children),item:Pe})}),me},E=function(D,M){var B=D.props,V=D.dataStartIndex,G=D.dataEndIndex,W=D.updateId;if(!Iie({props:B}))return null;var Z=B.children,Q=B.layout,re=B.stackOffset,se=B.data,ue=B.reverseStackOrder,_e=fle(Q),we=_e.numericAxisName,Ce=_e.cateAxisName,Me=nh(Z,n),Ae=Awt(se,Me,"".concat(we,"Id"),"".concat(Ce,"Id"),re,ue),be=f.reduce(function(ve,We){var rt="".concat(We.axisType,"Map");return vr(vr({},ve),{},ii({},rt,jCt(B,vr(vr({},We),{},{graphicalItems:Me,stackGroups:We.axisType===we&&Ae,dataStartIndex:V,dataEndIndex:G}))))},{}),me=ICt(vr(vr({},be),{},{props:B,graphicalItems:Me}),M==null?void 0:M.legendBBox);Object.keys(be).forEach(function(ve){be[ve]=y(B,be[ve],me,ve.replace("Map",""),r)});var Pe=be["".concat(Ce,"Map")],Ie=kCt(Pe),Se=T(B,vr(vr({},be),{},{dataStartIndex:V,dataEndIndex:G,updateId:W,graphicalItems:Me,stackGroups:Ae,offset:me}));return vr(vr({formattedGraphicalItems:Se,graphicalItems:Me,offset:me,stackGroups:Ae},Ie),be)},k=function(R){function D(M){var B,V,G;return uCt(this,D),G=fCt(this,D,[M]),ii(G,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ii(G,"accessibilityManager",new Zkt),ii(G,"handleLegendBBoxUpdate",function(W){if(W){var Z=G.state,Q=Z.dataStartIndex,re=Z.dataEndIndex,se=Z.updateId;G.setState(vr({legendBBox:W},E({props:G.props,dataStartIndex:Q,dataEndIndex:re,updateId:se},vr(vr({},G.state),{},{legendBBox:W}))))}}),ii(G,"handleReceiveSyncEvent",function(W,Z,Q){if(G.props.syncId===W){if(Q===G.eventEmitterSymbol&&typeof G.props.syncMethod!="function")return;G.applySyncEvent(Z)}}),ii(G,"handleBrushChange",function(W){var Z=W.startIndex,Q=W.endIndex;if(Z!==G.state.dataStartIndex||Q!==G.state.dataEndIndex){var re=G.state.updateId;G.setState(function(){return vr({dataStartIndex:Z,dataEndIndex:Q},E({props:G.props,dataStartIndex:Z,dataEndIndex:Q,updateId:re},G.state))}),G.triggerSyncEvent({dataStartIndex:Z,dataEndIndex:Q})}}),ii(G,"handleMouseEnter",function(W){var Z=G.getMouseInfo(W);if(Z){var Q=vr(vr({},Z),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onMouseEnter;_i(re)&&re(Q,W)}}),ii(G,"triggeredAfterMouseMove",function(W){var Z=G.getMouseInfo(W),Q=Z?vr(vr({},Z),{},{isTooltipActive:!0}):{isTooltipActive:!1};G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onMouseMove;_i(re)&&re(Q,W)}),ii(G,"handleItemMouseEnter",function(W){G.setState(function(){return{isTooltipActive:!0,activeItem:W,activePayload:W.tooltipPayload,activeCoordinate:W.tooltipPosition||{x:W.cx,y:W.cy}}})}),ii(G,"handleItemMouseLeave",function(){G.setState(function(){return{isTooltipActive:!1}})}),ii(G,"handleMouseMove",function(W){W.persist(),G.throttleTriggeredAfterMouseMove(W)}),ii(G,"handleMouseLeave",function(W){G.throttleTriggeredAfterMouseMove.cancel();var Z={isTooltipActive:!1};G.setState(Z),G.triggerSyncEvent(Z);var Q=G.props.onMouseLeave;_i(Q)&&Q(Z,W)}),ii(G,"handleOuterEvent",function(W){var Z=plt(W),Q=ld(G.props,"".concat(Z));if(Z&&_i(Q)){var re,se;/.*touch.*/i.test(Z)?se=G.getMouseInfo(W.changedTouches[0]):se=G.getMouseInfo(W),Q((re=se)!==null&&re!==void 0?re:{},W)}}),ii(G,"handleClick",function(W){var Z=G.getMouseInfo(W);if(Z){var Q=vr(vr({},Z),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onClick;_i(re)&&re(Q,W)}}),ii(G,"handleMouseDown",function(W){var Z=G.props.onMouseDown;if(_i(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),ii(G,"handleMouseUp",function(W){var Z=G.props.onMouseUp;if(_i(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),ii(G,"handleTouchMove",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.throttleTriggeredAfterMouseMove(W.changedTouches[0])}),ii(G,"handleTouchStart",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseDown(W.changedTouches[0])}),ii(G,"handleTouchEnd",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseUp(W.changedTouches[0])}),ii(G,"handleDoubleClick",function(W){var Z=G.props.onDoubleClick;if(_i(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),ii(G,"handleContextMenu",function(W){var Z=G.props.onContextMenu;if(_i(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),ii(G,"triggerSyncEvent",function(W){G.props.syncId!==void 0&&S$.emit(T$,G.props.syncId,W,G.eventEmitterSymbol)}),ii(G,"applySyncEvent",function(W){var Z=G.props,Q=Z.layout,re=Z.syncMethod,se=G.state.updateId,ue=W.dataStartIndex,_e=W.dataEndIndex;if(W.dataStartIndex!==void 0||W.dataEndIndex!==void 0)G.setState(vr({dataStartIndex:ue,dataEndIndex:_e},E({props:G.props,dataStartIndex:ue,dataEndIndex:_e,updateId:se},G.state)));else if(W.activeTooltipIndex!==void 0){var we=W.chartX,Ce=W.chartY,Me=W.activeTooltipIndex,Ae=G.state,be=Ae.offset,me=Ae.tooltipTicks;if(!be)return;if(typeof re=="function")Me=re(me,W);else if(re==="value"){Me=-1;for(var Pe=0;Pe=0){var er,vt;if(we.dataKey&&!we.allowDuplicatedCategory){var or=typeof we.dataKey=="function"?Nt:"payload.".concat(we.dataKey.toString());er=QD(Pe,or,Me),vt=Ie&&Se&&QD(Se,or,Me)}else er=Pe==null?void 0:Pe[Ce],vt=Ie&&Se&&Se[Ce];if(Et||at){var Sr=W.props.activeIndex!==void 0?W.props.activeIndex:Ce;return[I.cloneElement(W,vr(vr(vr({},re.props),Vt),{},{activeIndex:Sr})),null,null]}if(!Fi(er))return[pt].concat(vS(G.renderActivePoints({item:re,activePoint:er,basePoint:vt,childIndex:Ce,isRange:Ie})))}else{var nn,cr=(nn=G.getItemByXY(G.state.activeCoordinate))!==null&&nn!==void 0?nn:{graphicalItem:pt},xr=cr.graphicalItem,tr=xr.item,_n=tr===void 0?W:tr,lt=xr.childIndex,At=vr(vr(vr({},re.props),Vt),{},{activeIndex:lt});return[I.cloneElement(_n,At),null,null]}return Ie?[pt,null,null]:[pt,null]}),ii(G,"renderCustomized",function(W,Z,Q){return I.cloneElement(W,vr(vr({key:"recharts-customized-".concat(Q)},G.props),G.state))}),ii(G,"renderMap",{CartesianGrid:{handler:gR,once:!0},ReferenceArea:{handler:G.renderReferenceElement},ReferenceLine:{handler:gR},ReferenceDot:{handler:G.renderReferenceElement},XAxis:{handler:gR},YAxis:{handler:gR},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:NC("recharts"),"-clip"),G.throttleTriggeredAfterMouseMove=pSe(G.triggeredAfterMouseMove,(V=M.throttleDelay)!==null&&V!==void 0?V:1e3/60),G.state={},G}return gCt(D,R),hCt(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,Z=B.layout,Q=Qu(V,Vh);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=Nq(this.state,G,re,se),_e=this.state.tooltipTicks[re].coordinate,we=(this.state.offset.top+W)/2,Ce=Z==="horizontal",Me=Ce?{x:_e,y:we}:{y:_e,x:we},Ae=this.state.formattedGraphicalItems.find(function(me){var Pe=me.item;return Pe.type.name==="Scatter"});Ae&&(Me=vr(vr({},Me),Ae.props.points[re].tooltipPosition),ue=Ae.props.points[re].tooltipPayload);var be={activeTooltipIndex:re,isTooltipActive:!0,activeLabel:se,activePayload:ue,activeCoordinate:Me};this.setState(be),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){a8([Qu(B.children,Vh)],[Qu(this.props.children,Vh)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var B=Qu(this.props.children,Vh);if(B&&typeof B.props.shared=="boolean"){var V=B.props.shared?"axis":"item";return s.indexOf(V)>=0?V:o}return o}},{key:"getMouseInfo",value:function(B){if(!this.container)return null;var V=this.container,G=V.getBoundingClientRect(),W=Uxt(G),Z={chartX:Math.round(B.pageX-W.left),chartY:Math.round(B.pageY-W.top)},Q=G.width/V.offsetWidth||1,re=this.inRange(Z.chartX,Z.chartY,Q);if(!re)return null;var se=this.state,ue=se.xAxisMap,_e=se.yAxisMap,we=this.getTooltipEventType(),Ce=dle(this.state,this.props.data,this.props.layout,re);if(we!=="axis"&&ue&&_e){var Me=my(ue).scale,Ae=my(_e).scale,be=Me&&Me.invert?Me.invert(Z.chartX):null,me=Ae&&Ae.invert?Ae.invert(Z.chartY):null;return vr(vr({},Z),{},{xValue:be,yValue:me},Ce)}return Ce?vr(vr({},Z),Ce):null}},{key:"inRange",value:function(B,V){var G=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,W=this.props.layout,Z=B/G,Q=V/G;if(W==="horizontal"||W==="vertical"){var re=this.state.offset,se=Z>=re.left&&Z<=re.left+re.width&&Q>=re.top&&Q<=re.top+re.height;return se?{x:Z,y:Q}:null}var ue=this.state,_e=ue.angleAxisMap,we=ue.radiusAxisMap;if(_e&&we){var Ce=my(_e);return Bae({x:Z,y:Q},Ce)}return null}},{key:"parseEventsOfWrapper",value:function(){var B=this.props.children,V=this.getTooltipEventType(),G=Qu(B,Vh),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 Z=JD(this.props,this.handleOuterEvent);return vr(vr({},Z),W)}},{key:"addListener",value:function(){S$.on(T$,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){S$.removeListener(T$,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(B,V,G){for(var W=this.state.formattedGraphicalItems,Z=0,Q=W.length;Z");return t}const VEe=I.forwardRef(({id:t,className:e,children:r,config:n,...i},o)=>{const c=I.useId(),s=`chart-${t||c.replace(/:/g,"")}`;return a.jsx($Ee.Provider,{value:{config:n},children:a.jsxs("div",{"data-chart":s,ref:o,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:[a.jsx(DCt,{id:s,config:n}),a.jsx(C8,{children:r})]})})});VEe.displayName="Chart";const DCt=({id:t,config:e})=>{const r=Object.entries(e).filter(([n,i])=>i.theme||i.color);return r.length?a.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(LCt).map(([n,i])=>` ${i} [data-chart=${t}] { ${r.map(([o,c])=>{var f;const s=((f=c.theme)==null?void 0:f[n])||c.color;return s?` --color-${o}: ${s};`:null}).join(` `)} } `).join(` `)}}):null},qEe=I.forwardRef(({active:t,payload:e,className:r,indicator:n="dot",hideLabel:i=!1,hideIndicator:o=!1,label:c,labelFormatter:s,labelClassName:f,formatter:p,color:y,nameKey:_,labelKey:T},E)=>{const{config:k}=UEe(),P=I.useMemo(()=>{var G;if(i||!(e!=null&&e.length))return null;const[D]=e,M=`${T||D.dataKey||D.name||"value"}`,B=Pq(k,D,M),V=!T&&typeof c=="string"?((G=k[c])==null?void 0:G.label)||c:B==null?void 0:B.label;return s?a.jsx("div",{className:sr("font-medium",f),children:s(V,e)}):V?a.jsx("div",{className:sr("font-medium",f),children:V}):null},[c,s,e,i,f,k,T]);if(!t||!(e!=null&&e.length))return null;const R=e.length===1&&n!=="dot";return a.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:P,a.jsx("div",{className:"grid gap-1.5",children:e.map((D,M)=>{const B=`${_||D.name||D.dataKey||"value"}`,V=Pq(k,D,B),G=y||D.payload.fill||D.color;return a.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:p&&(D==null?void 0:D.value)!==void 0&&D.name?p(D.value,D.name,D,M,D.payload):a.jsxs(a.Fragment,{children:[V!=null&&V.icon?a.jsx(V.icon,{}):!o&&a.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}}),a.jsxs("div",{className:sr("flex flex-1 justify-between leading-none",R?"items-end":"items-center"),children:[a.jsxs("div",{className:"grid gap-1.5",children:[R?P:null,a.jsx("span",{className:"text-muted-foreground",children:(V==null?void 0:V.label)||D.name})]}),D.value&&a.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:D.value.toLocaleString()})]})]})},D.dataKey)})})]})});qEe.displayName="ChartTooltip";const MCt=I.forwardRef(({className:t,hideIcon:e=!1,payload:r,verticalAlign:n="bottom",nameKey:i},o)=>{const{config:c}=UEe();return r!=null&&r.length?a.jsx("div",{ref:o,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"}`,p=Pq(c,s,f);return a.jsxs("div",{className:sr("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[p!=null&&p.icon&&!e?a.jsx(p.icon,{}):a.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:s.color}}),p==null?void 0:p.label]},s.value)})}):null});MCt.displayName="ChartLegend";function Pq(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 yR=["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 GEe({stats:t,year:e}){const r=t.transactionsByMonth.some(i=>i.count>0),n=t.leadSourceBreakdown.length>0;return!r&&!n?a.jsx(Wn,{children:a.jsx(si,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):a.jsxs("div",{className:"grid gap-6",children:[r&&a.jsxs(Wn,{className:"overflow-hidden",children:[a.jsx(id,{children:a.jsx(sd,{className:"text-base",children:"Transactions by Month"})}),a.jsx(si,{className:"overflow-hidden",children:a.jsx(VEe,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:a.jsx(C8,{width:"100%",height:"100%",children:a.jsxs(PCt,{data:t.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[a.jsx(EEe,{strokeDasharray:"3 3",className:"stroke-muted"}),a.jsx(zF,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),a.jsx($F,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),a.jsx(Vh,{content:a.jsx(qEe,{})}),a.jsx(fv,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&a.jsxs(Wn,{children:[a.jsx(id,{children:a.jsx(sd,{className:"text-base",children:"Lead Sources"})}),a.jsxs(si,{children:[a.jsx("div",{className:"h-[250px]",children:a.jsx(C8,{width:"100%",height:"100%",children:a.jsxs(RCt,{children:[a.jsx(tg,{data:t.leadSourceBreakdown,dataKey:"count",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:i,percent:o})=>o>.05?`${i} (${(o*100).toFixed(0)}%)`:"",labelLine:!1,children:t.leadSourceBreakdown.map((i,o)=>a.jsx(pF,{fill:yR[o%yR.length]},`cell-${o}`))}),a.jsx(Vh,{formatter:(i,o)=>[`${i} deals`,o]})]})})}),a.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:t.leadSourceBreakdown.slice(0,6).map((i,o)=>a.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:yR[o%yR.length]}}),a.jsx("span",{className:"text-muted-foreground",children:i.name})]},i.name))})]})]})]})}const OCt=kS("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"}}),HEe=I.forwardRef(({className:t,variant:e,...r},n)=>a.jsx("div",{ref:n,role:"alert",className:sr(OCt({variant:e}),t),...r}));HEe.displayName="Alert";const FCt=I.forwardRef(({className:t,...e},r)=>a.jsx("h5",{ref:r,className:sr("mb-1 font-medium leading-none tracking-tight",t),...e}));FCt.displayName="AlertTitle";const WEe=I.forwardRef(({className:t,...e},r)=>a.jsx("div",{ref:r,className:sr("text-sm [&_p]:leading-relaxed",t),...e}));WEe.displayName="AlertDescription";function BCt(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=RWe(e,n,new Date);if(_V(i))return Ni(i,"yyyy-MM-dd")}catch{}try{const n=new Date(e);if(_V(n))return Ni(n,"yyyy-MM-dd")}catch{}return null}const zCt=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function $Ct({open:t,onOpenChange:e}){const[r,n]=I.useState([]),[i,o]=I.useState(!1),[c,s]=I.useState(0),{data:f}=jH(),{data:p}=PH(),y=kH(),_=()=>{const D=zCt.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 be,me,Pe,Ie;const W=[];let Z="",Q=!1;for(const Se of V)Se==='"'?Q=!Q:Se===","&&!Q?(W.push(Z.trim()),Z=""):Z+=Se;W.push(Z.trim());const re=Se=>{var We;const ve=B.indexOf(Se);return ve>=0?(We=W[ve])==null?void 0:We.replace(/^["']|["']$/g,"").trim():""},se=(be=re("transaction_type"))==null?void 0:be.toLowerCase(),ue=(me=re("sale_price"))==null?void 0:me.replace(/[$,]/g,""),_e=(Pe=re("commission_amount"))==null?void 0:Pe.replace(/[$,]/g,""),we=(Ie=re("is_win"))==null?void 0:Ie.toLowerCase(),Ce=re("close_date"),Me=BCt(Ce);let Ae;return re("property_address")?["buyer","seller"].includes(se)?Me?(!ue||isNaN(Number(ue)))&&(Ae="Invalid sale price"):Ae=`Invalid date format: "${Ce}" - 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:Me||"",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(we),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,Z=T(W);n(Z)},B.readAsText(M)},k=async()=>{const D=r.filter(V=>!V.error);if(D.length===0){Gt.error("No valid transactions to import");return}o(!0),s(0);let M=0,B=0;for(let V=0;VQ.name.toLowerCase()===G.lead_source_name.toLowerCase()),Z=p==null?void 0:p.find(Q=>Q.name.toLowerCase()===G.client_type_name.toLowerCase());await y.mutateAsync({property_address:G.property_address,city:G.city||null,state:G.state||null,zip:G.zip||null,transaction_type:G.transaction_type,close_date:G.close_date,sale_price:G.sale_price,commission_amount:G.commission_amount,lead_source_id:(W==null?void 0:W.id)||null,client_type_id:(Z==null?void 0:Z.id)||null,contact_id:null,notes:G.notes||null,is_win:G.is_win}),M++}catch(W){B++,console.error("Failed to import transaction:",W)}s(Math.round((V+1)/D.length*100))}o(!1),M>0&&Gt.success(`Imported ${M} transaction${M>1?"s":""}`),B>0&&Gt.error(`Failed to import ${B} transaction${B>1?"s":""}`),n([]),e(!1)},P=r.filter(D=>!D.error).length,R=r.filter(D=>D.error).length;return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"max-w-2xl max-h-[90vh]",children:[a.jsxs(ml,{children:[a.jsx(Ko,{children:"Import Transactions"}),a.jsx(gd,{children:"Upload a CSV file with your past transactions"})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:"Download Template"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),a.jsxs(zt,{variant:"outline",onClick:_,children:[a.jsx(rc,{className:"h-4 w-4 mr-2"}),"Template"]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mr,{htmlFor:"csv-file",children:"Upload CSV File"}),a.jsx($r,{id:"csv-file",type:"file",accept:".csv",onChange:E})]}),r.length>0&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(us,{variant:"outline",children:[r.length," rows found"]}),P>0&&a.jsxs(us,{className:"bg-green-500 text-white",children:[a.jsx(ko,{className:"h-3 w-3 mr-1"}),P," valid"]}),R>0&&a.jsxs(us,{variant:"destructive",children:[a.jsx(Pfe,{className:"h-3 w-3 mr-1"}),R," errors"]})]}),a.jsx(Sm,{className:"h-[200px] border rounded-lg",children:a.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((D,M)=>a.jsxs("div",{className:`p-2 rounded text-sm ${D.error?"bg-destructive/10":"bg-muted/50"}`,children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"font-medium",children:D.property_address||"(no address)"}),a.jsx(us,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})]}),a.jsxs("div",{className:"text-muted-foreground",children:[D.close_date," • $",D.sale_price.toLocaleString()]}),D.error&&a.jsx(HEe,{variant:"destructive",className:"mt-1 py-1",children:a.jsx(WEe,{className:"text-xs",children:D.error})})]},M)),r.length>10&&a.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),i&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:a.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${c}%`}})}),a.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",c,"%"]})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(zt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),a.jsxs(zt,{onClick:k,disabled:P===0||i,children:[a.jsx(yU,{className:"h-4 w-4 mr-2"}),"Import ",P," Transaction",P!==1?"s":""]})]})]})]})})}const UCt=_x({transactions_goal:$A().min(0).optional(),volume_goal:$A().min(0).optional(),gci_goal:$A().min(0).optional()});function VCt({open:t,onOpenChange:e,year:r,existingGoals:n}){const i=Xnt(),{data:o}=G3(),c=(o==null?void 0:o.show_commission)??!0,s=m7({resolver:p7(UCt),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});I.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 p=>{await i.mutateAsync({year:r,transactions_goal:p.transactions_goal??null,volume_goal:p.volume_goal??null,gci_goal:c?p.gci_goal??null:null}),e(!1)};return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"max-w-md",children:[a.jsxs(ml,{children:[a.jsxs(Ko,{children:[r," Goals"]}),a.jsx(gd,{children:"Set your annual targets to track your progress throughout the year."})]}),a.jsx(T7,{...s,children:a.jsxs("form",{onSubmit:s.handleSubmit(f),className:"space-y-4",children:[a.jsx(sl,{control:s.control,name:"transactions_goal",render:({field:p})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Transactions Goal"}),a.jsx(Uo,{children:a.jsx($r,{type:"number",placeholder:"e.g., 24",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),a.jsx(cL,{children:"Total number of deals you want to close"}),a.jsx(Qh,{})]})}),a.jsx(sl,{control:s.control,name:"volume_goal",render:({field:p})=>a.jsxs(zo,{children:[a.jsx($o,{children:"Volume Goal ($)"}),a.jsx(Uo,{children:a.jsx($r,{type:"number",placeholder:"e.g., 5000000",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),a.jsx(cL,{children:"Total sales volume you want to achieve"}),a.jsx(Qh,{})]})}),c&&a.jsx(sl,{control:s.control,name:"gci_goal",render:({field:p})=>a.jsxs(zo,{children:[a.jsx($o,{children:"GCI Goal ($)"}),a.jsx(Uo,{children:a.jsx($r,{type:"number",placeholder:"e.g., 150000",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),a.jsx(cL,{children:"Gross commission income target"}),a.jsx(Qh,{})]})}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(zt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),a.jsx(zt,{type:"submit",disabled:i.isPending,children:"Save Goals"})]})]})})]})})}function KEe({transactions:t,isLoading:e}){const r=I.useRef(null),n=I.useRef(null),i=I.useRef([]),o=I.useRef(null),{isAdmin:c}=Gn(),[s,f]=I.useState(""),[p,y]=I.useState(!0),[_,T]=I.useState(0),[E,k]=I.useState(!1),P=t.filter(D=>D.latitude!=null&&D.longitude!=null),R=t.filter(D=>D.latitude==null||D.longitude==null);return I.useEffect(()=>{(async()=>{y(!0);try{const{data:M}=await Re.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)}y(!1)})()},[]),I.useEffect(()=>{if(!s||R.length===0||E)return;(async()=>{var B;k(!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 Z=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?access_token=${s}&limit=1`)).json();if((B=Z.features)!=null&&B[0]){const[Q,re]=Z.features[0].center;await Re.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),k(!1)})()},[s,t]),I.useEffect(()=>{if(!r.current||!s||n.current)return;Kd.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,Z)=>W+Z.longitude,0)/D.length,G=D.reduce((W,Z)=>W+Z.latitude,0)/D.length;M=[V,G],B=D.length===1?12:10}return n.current=new Kd.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:B,center:M}),n.current.addControl(new Kd.NavigationControl,"top-right"),()=>{var V;(V=n.current)==null||V.remove(),n.current=null}},[s]),I.useEffect(()=>{var M;if(!n.current||!s)return;i.current.forEach(B=>B.remove()),i.current=[],(M=o.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 Z=new Kd.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: ${Y1(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 Kd.Marker(W).setLngLat([B.longitude,B.latitude]).setPopup(Z).addTo(n.current);i.current.push(Q)}),D.length>1){const B=new Kd.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]),p||e?a.jsx(Wn,{children:a.jsx(si,{className:"flex items-center justify-center h-[50vh]",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?t.length===0?a.jsx(Wn,{children:a.jsxs(si,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[a.jsx(qs,{className:"h-12 w-12 text-muted-foreground"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),a.jsx("span",{children:"Buyer"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),a.jsx("span",{children:"Seller"})]}),a.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[P.length," of ",t.length," mapped",E&&" · Geocoding..."]})]}),a.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):a.jsx(Wn,{children:a.jsxs(si,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[a.jsx(Pfe,{className:"h-12 w-12 text-muted-foreground"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),a.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 YEe=()=>{const{data:t}=GS();return gr({queryKey:["team-scorecard-members",t==null?void 0:t.teamId],queryFn:async()=>{const{data:e,error:r}=await Re.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:o}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",n);if(o)throw o;return i||[]},enabled:!!(t!=null&&t.teamId)&&(t==null?void 0:t.role)==="team_leader"})},qCt=t=>{const{data:e}=GS(),{data:r}=YEe();return gr({queryKey:["team-scorecard-transactions",e==null?void 0:e.teamId,t],queryFn:async()=>{const n=r.map(s=>s.id);let i=Re.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:o,error:c}=await i;if(c)throw c;return o},enabled:!!r&&r.length>0})};function GCt(t,e){const r=e.filter(o=>o.owner_user_id===t.id),n=r.reduce((o,c)=>o+Number(c.sale_price),0),i=r.reduce((o,c)=>o+(Number(c.commission_amount)||0),0);return{member:t,totalTransactions:r.length,buyerCount:r.filter(o=>o.transaction_type==="buyer").length,sellerCount:r.filter(o=>o.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:i}}function HCt(t,e){return t?t.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):e[0].toUpperCase()}function WCt({year:t}){var T;const{data:e,isLoading:r}=YEe(),{data:n,isLoading:i}=qCt(t),o=Gs(),c=r||i,{aggregate:s,memberStats:f,topPerformer:p,agentNameMap:y,teamChartStats:_}=I.useMemo(()=>{if(!e||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const E=e.map(se=>GCt(se,n));E.sort((se,ue)=>ue.totalVolume-se.totalVolume);const k={};e.forEach(se=>{k[se.id]=se.name||se.email});const P=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=Y1(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:P,buyerCount:M,sellerCount:B,totalVolume:R,avgPrice:P>0?R/P:0,totalGCI:D,topSource:G?{name:G[0],count:G[1]}:null,memberCount:e.length},memberStats:E,topPerformer:E[0]||null,agentNameMap:k,teamChartStats:{transactionsByMonth:Q,leadSourceBreakdown:re}}},[e,n]);return c?a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(E=>a.jsx(dl,{className:"h-24"},E))}),a.jsx(dl,{className:"h-64"})]}):!s||f.length===0?a.jsx(Wn,{className:"py-12",children:a.jsxs(si,{className:"text-center space-y-2",children:[a.jsx(ul,{className:"h-10 w-10 mx-auto text-muted-foreground"}),a.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),a.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",t,"."]})]})}):a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(ul,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),a.jsx("p",{className:"text-2xl font-bold",children:s.memberCount})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(La,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),a.jsx("p",{className:"text-2xl font-bold",children:s.totalTxns}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.buyerCount,"B / ",s.sellerCount,"S"]})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(jp,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(s.totalVolume,!0)})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(NS,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(s.avgPrice,!0)})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(jp,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(s.totalGCI,!0)})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(Ww,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),a.jsx("p",{className:"text-lg font-bold truncate",children:((T=s.topSource)==null?void 0:T.name)||"-"}),s.topSource&&a.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.topSource.count," deals"]})]})})]}),p&&p.totalTransactions>0&&a.jsx(Wn,{className:"border-primary/30 bg-primary/5",children:a.jsxs(si,{className:"pt-4 flex items-center gap-4",children:[a.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:a.jsx(uD,{className:"h-5 w-5 text-primary"})}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",t]}),a.jsx("p",{className:"text-lg font-bold",children:p.member.name||p.member.email})]}),a.jsxs("div",{className:"text-right",children:[a.jsxs("p",{className:"text-sm text-muted-foreground",children:[p.totalTransactions," deals"]}),a.jsx("p",{className:"font-semibold",children:Ba(p.totalVolume,!0)})]})]})}),a.jsxs(Wn,{children:[a.jsx(id,{children:a.jsx(sd,{className:"text-lg",children:"Member Performance"})}),a.jsx(si,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs(CH,{children:[a.jsx(IH,{children:a.jsxs(Yj,{children:[a.jsx(Hl,{children:"Agent"}),a.jsx(Hl,{className:"text-center",children:"Transactions"}),a.jsx(Hl,{className:"text-center",children:"B / S"}),a.jsx(Hl,{className:"text-right",children:"Volume"}),a.jsx(Hl,{className:"text-right",children:"Avg Price"}),a.jsx(Hl,{className:"text-right",children:"GCI"}),a.jsx(Hl,{className:"text-right"})]})}),a.jsx(NH,{children:f.map((E,k)=>a.jsxs(Yj,{children:[a.jsx(Wl,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[k===0&&E.totalTransactions>0&&a.jsx(uD,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),a.jsxs(fd,{className:"h-8 w-8",children:[a.jsx(md,{src:E.member.avatar_url||void 0}),a.jsx(pd,{className:"text-xs",children:HCt(E.member.name,E.member.email)})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-sm",children:E.member.name||E.member.email}),E.member.name&&a.jsx("p",{className:"text-xs text-muted-foreground",children:E.member.email})]})]})}),a.jsx(Wl,{className:"text-center font-semibold",children:E.totalTransactions}),a.jsxs(Wl,{className:"text-center text-sm",children:[E.buyerCount," / ",E.sellerCount]}),a.jsx(Wl,{className:"text-right font-medium",children:Ba(E.totalVolume,!0)}),a.jsx(Wl,{className:"text-right text-sm",children:Ba(E.averagePrice,!0)}),a.jsx(Wl,{className:"text-right font-medium",children:Ba(E.totalGCI,!0)}),a.jsx(Wl,{className:"text-right",children:a.jsx(zt,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/scorecard/${E.member.id}`),children:a.jsx(CO,{className:"h-4 w-4"})})})]},E.member.id))})]})})})]}),a.jsxs(V7,{defaultValue:"transactions",className:"space-y-4",children:[a.jsxs(N3,{children:[a.jsxs(kp,{value:"transactions",children:[a.jsx(pU,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),a.jsxs(kp,{value:"charts",children:[a.jsx(wj,{className:"h-4 w-4 mr-1"}),"Charts"]}),a.jsxs(kp,{value:"map",children:[a.jsx(qs,{className:"h-4 w-4 mr-1"}),"Map"]})]}),a.jsx(Uy,{value:"transactions",children:a.jsx(e1e,{transactions:n||[],showCommission:!0,isLoading:i,agentNameMap:y,readOnly:!0})}),a.jsx(Uy,{value:"charts",children:_&&a.jsx(GEe,{stats:_,year:t})}),a.jsx(Uy,{value:"map",children:a.jsx(KEe,{transactions:n||[],isLoading:i})})]})]})}const TL=new Date().getFullYear(),mle=Array.from({length:10},(t,e)=>TL-e),xR="all";function KCt(){var _e;const[t,e]=I.useState(TL),r=t===null?xR:String(t),n=we=>e(we===xR?null:Number(we)),[i,o]=I.useState(!1),[c,s]=I.useState(!1),[f,p]=I.useState(!1),[y,_]=I.useState(!1),[T,E]=I.useState("my"),{data:k}=GS(),P=(k==null?void 0:k.role)==="team_leader",{data:R,isLoading:D}=Mwe(t??void 0),{yearStats:M,lifetimeStats:B,isLoading:V,showCommission:G}=Jnt(t??void 0),{data:W,isLoading:Z}=Znt(t??TL),{data:Q}=G3(),re=Qnt(),se=()=>{if(!R||R.length===0)return;const we=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...G?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],Ce=R.map(Pe=>{var Ie,Se;return[Pe.property_address,Pe.city||"",Pe.state||"",Pe.zip||"",Pe.transaction_type,Pe.close_date,Pe.sale_price,...G?[Pe.commission_amount||""]:[],((Ie=Pe.lead_source)==null?void 0:Ie.name)||"",((Se=Pe.client_type)==null?void 0:Se.name)||"",Pe.contact?`${Pe.contact.first_name} ${Pe.contact.last_name||""}`.trim():"",Pe.is_win?"Yes":"No",Pe.notes||""]}),Me=[we,...Ce].map(Pe=>Pe.map(Ie=>`"${String(Ie).replace(/"/g,'""')}"`).join(",")).join(` `),Ae=new Blob([Me],{type:"text/csv"}),be=URL.createObjectURL(Ae),me=document.createElement("a");me.href=be,me.download=t===null?"transactions-all.csv":`transactions-${t}.csv`,me.click(),URL.revokeObjectURL(be)},ue=!R||R.length===0;return a.jsxs(G1,{title:"Scorecard",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),a.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),P&&a.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[a.jsx(zt,{variant:T==="my"?"default":"ghost",size:"sm",onClick:()=>E("my"),className:"h-8",children:"My Scorecard"}),a.jsxs(zt,{variant:T==="team"?"default":"ghost",size:"sm",onClick:()=>E("team"),className:"h-8",children:[a.jsx(ul,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),T==="team"&&P?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),a.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),a.jsxs(_a,{value:r,onValueChange:n,children:[a.jsx(aa,{className:"w-[140px]",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:xR,children:"All Years"}),mle.map(we=>a.jsx(fn,{value:String(we),children:we},we))]})]})]}),a.jsx(WCt,{year:t??void 0})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),a.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs(_a,{value:r,onValueChange:n,children:[a.jsx(aa,{className:"w-[140px]",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:xR,children:"All Years"}),mle.map(we=>a.jsx(fn,{value:String(we),children:we},we))]})]}),a.jsx(zt,{variant:"outline",size:"icon",onClick:()=>_(!y),children:a.jsx(s9,{className:"h-4 w-4"})})]})]}),y&&a.jsxs(Wn,{children:[a.jsx(id,{className:"pb-3",children:a.jsx(sd,{className:"text-lg",children:"Settings"})}),a.jsx(si,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(Mr,{children:"Show Commission"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),a.jsx(YS,{checked:(Q==null?void 0:Q.show_commission)??!0,onCheckedChange:we=>re.mutate({show_commission:we})})]})})]}),ue&&!D?a.jsx(Wn,{className:"py-12",children:a.jsxs(si,{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:a.jsx(wj,{className:"h-8 w-8 text-primary"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),a.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."})]}),a.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[a.jsxs(zt,{onClick:()=>o(!0),children:[a.jsx(sm,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),a.jsxs(zt,{variant:"outline",onClick:()=>s(!0),children:[a.jsx(yU,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),a.jsxs("div",{className:"pt-4 border-t mt-4",children:[a.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),a.jsx(zt,{variant:"link",className:"h-auto p-0",asChild:!0,children:a.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[a.jsx(rc,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs(zt,{onClick:()=>o(!0),children:[a.jsx(sm,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),a.jsxs(zt,{variant:"outline",onClick:()=>p(!0),children:[a.jsx(l9,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),a.jsxs(zt,{variant:"outline",onClick:()=>s(!0),children:[a.jsx(yU,{className:"h-4 w-4 mr-2"}),"Import"]}),a.jsxs(zt,{variant:"outline",onClick:se,disabled:ue,children:[a.jsx(rc,{className:"h-4 w-4 mr-2"}),"Export"]}),a.jsx(zt,{variant:"ghost",size:"sm",asChild:!0,children:a.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[a.jsx(rc,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(La,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),a.jsx("p",{className:"text-2xl font-bold",children:M.totalTransactions}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[B.totalTransactions," lifetime"]})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(ul,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),a.jsxs("p",{className:"text-2xl font-bold",children:[M.buyerCount,"/",M.sellerCount]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(jp,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(M.totalVolume,!0)}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ba(B.totalVolume,!0)," lifetime"]})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(NS,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(M.averagePrice,!0)})]})}),a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(Ww,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),a.jsx("p",{className:"text-lg font-bold truncate",children:((_e=M.topLeadSource)==null?void 0:_e.name)||"-"}),M.topLeadSource&&a.jsxs("p",{className:"text-xs text-muted-foreground",children:[M.topLeadSource.count," deals"]})]})}),G&&a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[a.jsx(jp,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),a.jsx("p",{className:"text-2xl font-bold",children:Ba(M.totalCommission,!0)}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ba(B.totalCommission,!0)," lifetime"]})]})}),G&&M.totalNetToAgent>0&&M.totalNetToAgent!==M.totalCommission&&a.jsx(Wn,{children:a.jsxs(si,{className:"pt-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[a.jsx(jp,{className:"h-4 w-4"}),a.jsx("span",{className:"text-xs font-medium",children:"Net to Agent"})]}),a.jsx("p",{className:"text-2xl font-bold text-teal-600 dark:text-teal-400",children:Ba(M.totalNetToAgent,!0)}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ba(B.totalNetToAgent,!0)," lifetime"]})]})})]}),t!==null&&W&&a.jsx(Sit,{goals:W,stats:M,year:t,showCommission:G}),a.jsxs(V7,{defaultValue:"transactions",className:"space-y-4",children:[a.jsxs(N3,{children:[a.jsx(kp,{value:"transactions",children:"Transactions"}),a.jsx(kp,{value:"charts",children:"Charts"}),a.jsxs(kp,{value:"map",children:[a.jsx(qs,{className:"h-4 w-4 mr-1"}),"Map"]})]}),a.jsx(Uy,{value:"transactions",children:a.jsx(e1e,{transactions:R||[],showCommission:G,isLoading:D})}),a.jsx(Uy,{value:"charts",children:a.jsx(GEe,{stats:M,year:t??void 0})}),a.jsx(Uy,{value:"map",children:a.jsx(KEe,{transactions:R||[],isLoading:D})})]})]})]})]}),a.jsx(Jwe,{open:i,onOpenChange:o}),a.jsx($Ct,{open:c,onOpenChange:s}),a.jsx(VCt,{open:f,onOpenChange:p,year:t??TL,existingGoals:W})]})}function YCt(){const t=Gi();return gr({queryKey:["deal-tasks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name, phone, email), stage:deal_pipeline_stages(id, name, color) `).or(`owner_user_id.eq.${t},assignee_user_id.eq.${t}`).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function BGt(t){const e=Gi();return gr({queryKey:["deal-tasks","deal",t,e],queryFn:async()=>{if(!e||!t)return[];const{data:r,error:n}=await Re.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 ZEe(){const t=Gi(),e=Nr();return kr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.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,assignee_user_id:r.assignee_user_id||null,assigned_by_user_id:r.assignee_user_id?t:null}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function ZCt(){const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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"&&Tx("task_completed")}})}function XCt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("deal_tasks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function $W(){const t=Nr();return kr({mutationFn:async({id:e,status:r})=>{const{data:n,error:i}=await Re.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"&&Tx("task_completed")}})}function zGt(){const t=Nr();return kr({mutationFn:async e=>{if(e.length===0)return;const{error:r}=await Re.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&&Tx("task_completed")}})}function QCt(t){const e=Gi();return gr({queryKey:["deal-task-templates",e,t],queryFn:async()=>{if(!e)return[];let r=Re.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 JCt(){const t=Gi(),e=Nr();return kr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.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 eIt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("deal_task_templates").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function $Gt(){const t=Gi(),e=Nr();return kr({mutationFn:async({dealId:r,stageId:n})=>{if(!t)throw new Error("Not authenticated");const{data:i,error:o}=await Re.from("deal_task_templates").select("*").eq("owner_user_id",t).eq("stage_id",n).order("sort_order");if(o)throw o;if(!i||i.length===0)return[];const{data:c}=await Re.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:p,error:y}=await Re.from("deal_tasks").insert(f).select();if(y)throw y;return p},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function tIt(){const t=Nr();return kr({mutationFn:async({ids:e,due_date:r})=>{if(!e.length)return;const{error:n}=await Re.from("deal_tasks").update({due_date:r}).in("id",e);if(n)throw n},onSuccess:()=>t.invalidateQueries({queryKey:["deal-tasks"]})})}function UGt(t,e=!0){return gr({queryKey:["deal-tasks","team",t],enabled:!!t&&e,queryFn:async()=>{const{data:r,error:n}=await Re.rpc("get_team_tasks",{_team_id:t});if(n)throw n;return r||[]}})}function iA(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 o=e;t.referral_fee_pct&&(o-=e*(t.referral_fee_pct/100));let c=o;return t.brokerage_split_pct&&(c-=o*(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 rIt(){const t=Gi();return gr({queryKey:["deal-pipeline-stages",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("deal_pipeline_stages").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function VGt(){const t=Gi(),e=Nr();return kr({mutationFn:async()=>{if(!t)throw new Error("Not authenticated");const{error:r}=await Re.rpc("initialize_deal_pipeline_stages",{p_user_id:t});if(r)throw r},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function nIt(){const t=Gi();return gr({queryKey:["deal-pipeline-deals",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.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 qGt(){const t=Gi(),e=Nr();return kr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.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 Re.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 GGt(){const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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 HGt(){const t=Nr();return kr({mutationFn:async({dealId:e,stageId:r,stageName:n})=>{const{data:i}=await Re.from("deal_pipeline_stages").select("default_probability").eq("id",r).maybeSingle(),o={stage_id:r};typeof(i==null?void 0:i.default_probability)=="number"&&(o.probability=i.default_probability);const{data:c,error:s}=await Re.from("deal_pipeline").update(o).eq("id",e).select().single();if(s)throw s;return await Re.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 WGt(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.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 KGt(t){return gr({queryKey:["deal-activities",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("deal_activities").select("*").eq("deal_id",t).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function YGt(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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 ZGt(t){return gr({queryKey:["deal-checklist",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("deal_checklist_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function XGt(){const t=Nr();return kr({mutationFn:async({id:e,is_completed:r,deal_id:n})=>{const{data:i,error:o}=await Re.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",e).select().single();if(o)throw o;return i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function QGt(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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 JGt(){const t=Gi();return gr({queryKey:["deal-pipeline-stats",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.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,p,y;return!((f=s.deal_pipeline_stages)!=null&&f.is_won_stage)&&!((p=s.deal_pipeline_stages)!=null&&p.is_lost_stage)&&((y=s.deal_pipeline_stages)==null?void 0:y.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}))||[],o=new Date().getFullYear(),c=i.filter(s=>{const f=s.actual_close_date;return f?new Date(f).getFullYear()===o:!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+(iA(f)||0),0),wonValue:i.reduce((s,f)=>s+(f.expected_price||0),0),weightedGCI:n.reduce((s,f)=>{const p=(f.probability??50)/100;return s+((f.expected_commission||0)+(f.bonus_amount||0))*p},0),weightedNet:n.reduce((s,f)=>{const p=(f.probability??50)/100;return s+(iA(f)||0)*p},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+(iA(f)||0),0),projectedAnnualNet:c.reduce((s,f)=>s+(iA(f)||0),0)+n.reduce((s,f)=>{const p=(f.probability??50)/100;return s+(iA(f)||0)*p},0)}},enabled:!!t})}function e9t(t){const e=Gi();return gr({queryKey:["deal-by-listing",t,e],queryFn:async()=>{if(!e||!t)return null;const{data:r,error:n}=await Re.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 t9t(){const t=Nr();return kr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Re.from("deal_pipeline").update({listing_id:r}).eq("id",e).select().single();if(i)throw i;return await Re.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 r9t(){const t=Nr();return kr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Re.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]})}})}function XEe(){const t=Gi();return gr({queryKey:["drip-task-assignees",t],enabled:!!t,staleTime:5*6e4,queryFn:async()=>{const{data:e}=await Re.from("team_members").select("team_id").eq("user_id",t),r=(e||[]).map(p=>p.team_id);if(!r.length)return[];const[{data:n},{data:i}]=await Promise.all([Re.from("team_members").select("user_id, team_id").in("team_id",r),Re.from("teams").select("id, name").in("id",r)]),o=new Map((i||[]).map(p=>[p.id,p.name])),c=[...new Set((n||[]).map(p=>p.user_id).filter(p=>p!==t))];if(!c.length)return[];const{data:s}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",c),f=new Map((s||[]).map(p=>[p.id,p]));return c.map(p=>{const y=f.get(p),_=(n||[]).find(T=>T.user_id===p);return{id:p,name:(y==null?void 0:y.name)||(y==null?void 0:y.email)||"Teammate",avatar_url:y==null?void 0:y.avatar_url,teamName:o.get(_==null?void 0:_.team_id)}}).sort((p,y)=>p.name.localeCompare(y.name))}})}var hi=function(){return hi=Object.assign||function(e){for(var r,n=1,i=arguments.length;n1&&(f||!p),_=e>1&&(p||!f),T=function(){n&&o(n)},E=function(){i&&o(i)};return a.jsx(MIt,{displayMonth:t.displayMonth,hideNext:y,hidePrevious:_,nextMonth:i,previousMonth:n,onPreviousClick:T,onNextClick:E})}function OIt(t){var e,r=ba(),n=r.classNames,i=r.disableNavigation,o=r.styles,c=r.captionLayout,s=r.components,f=(e=s==null?void 0:s.CaptionLabel)!==null&&e!==void 0?e:e2e,p;return i?p=a.jsx(f,{id:t.id,displayMonth:t.displayMonth}):c==="dropdown"?p=a.jsx(ple,{displayMonth:t.displayMonth,id:t.id}):c==="dropdown-buttons"?p=a.jsxs(a.Fragment,{children:[a.jsx(ple,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),a.jsx(gle,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):p=a.jsxs(a.Fragment,{children:[a.jsx(f,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),a.jsx(gle,{displayMonth:t.displayMonth,id:t.id})]}),a.jsx("div",{className:n.caption,style:o.caption,children:p})}function FIt(t){var e=ba(),r=e.footer,n=e.styles,i=e.classNames.tfoot;return r?a.jsx("tfoot",{className:i,style:n.tfoot,children:a.jsx("tr",{children:a.jsx("td",{colSpan:8,children:r})})}):a.jsx(a.Fragment,{})}function BIt(t,e,r){for(var n=r?Vp(new Date):Sc(new Date,{locale:t,weekStartsOn:e}),i=[],o=0;o<7;o++){var c=Cl(n,o);i.push(c)}return i}function zIt(){var t=ba(),e=t.classNames,r=t.styles,n=t.showWeekNumber,i=t.locale,o=t.weekStartsOn,c=t.ISOWeek,s=t.formatters.formatWeekdayName,f=t.labels.labelWeekday,p=BIt(i,o,c);return a.jsxs("tr",{style:r.head_row,className:e.head_row,children:[n&&a.jsx("td",{style:r.head_cell,className:e.head_cell}),p.map(function(y,_){return a.jsx("th",{scope:"col",className:e.head_cell,style:r.head_cell,"aria-label":f(y,{locale:i}),children:s(y,{locale:i})},_)})]})}function $It(){var t,e=ba(),r=e.classNames,n=e.styles,i=e.components,o=(t=i==null?void 0:i.HeadRow)!==null&&t!==void 0?t:zIt;return a.jsx("thead",{style:n.head,className:r.head,children:a.jsx(o,{})})}function UIt(t){var e=ba(),r=e.locale,n=e.formatters.formatDay;return a.jsx(a.Fragment,{children:n(t.date,{locale:r})})}var UW=I.createContext(void 0);function VIt(t){if(!OC(t.initialProps)){var e={selected:void 0,modifiers:{disabled:[]}};return a.jsx(UW.Provider,{value:e,children:t.children})}return a.jsx(qIt,{initialProps:t.initialProps,children:t.children})}function qIt(t){var e=t.initialProps,r=t.children,n=e.selected,i=e.min,o=e.max,c=function(p,y,_){var T,E;(T=e.onDayClick)===null||T===void 0||T.call(e,p,y,_);var k=!!(y.selected&&i&&(n==null?void 0:n.length)===i);if(!k){var P=!!(!y.selected&&o&&(n==null?void 0:n.length)===o);if(!P){var R=n?QEe([],n):[];if(y.selected){var D=R.findIndex(function(M){return Jl(p,M)});R.splice(D,1)}else R.push(p);(E=e.onSelect)===null||E===void 0||E.call(e,R,p,y,_)}}},s={disabled:[]};n&&s.disabled.push(function(p){var y=o&&n.length>o-1,_=n.some(function(T){return Jl(T,p)});return!!(y&&!_)});var f={selected:n,onDayClick:c,modifiers:s};return a.jsx(UW.Provider,{value:f,children:r})}function VW(){var t=I.useContext(UW);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function GIt(t,e){var r=e||{},n=r.from,i=r.to;return n&&i?Jl(i,t)&&Jl(n,t)?void 0:Jl(i,t)?{from:i,to:void 0}:Jl(n,t)?void 0:Bj(n,t)?{from:t,to:i}:{from:n,to:t}:i?Bj(t,i)?{from:i,to:t}:{from:t,to:i}:n?L7(t,n)?{from:t,to:n}:{from:n,to:t}:{from:t,to:void 0}}var qW=I.createContext(void 0);function HIt(t){if(!FC(t.initialProps)){var e={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return a.jsx(qW.Provider,{value:e,children:t.children})}return a.jsx(WIt,{initialProps:t.initialProps,children:t.children})}function WIt(t){var e=t.initialProps,r=t.children,n=e.selected,i=n||{},o=i.from,c=i.to,s=e.min,f=e.max,p=function(E,k,P){var R,D;(R=e.onDayClick)===null||R===void 0||R.call(e,E,k,P);var M=GIt(E,n);(D=e.onSelect)===null||D===void 0||D.call(e,M,E,k,P)},y={range_start:[],range_end:[],range_middle:[],disabled:[]};if(o?(y.range_start=[o],c?(y.range_end=[c],Jl(o,c)||(y.range_middle=[{after:o,before:c}])):y.range_end=[o]):c&&(y.range_start=[c],y.range_end=[c]),s&&(o&&!c&&y.disabled.push({after:xz(o,s-1),before:Cl(o,s-1)}),o&&c&&y.disabled.push({after:o,before:Cl(o,s-1)}),!o&&c&&y.disabled.push({after:xz(c,s-1),before:Cl(c,s-1)})),f){if(o&&!c&&(y.disabled.push({before:Cl(o,-f+1)}),y.disabled.push({after:Cl(o,f-1)})),o&&c){var _=Jh(c,o)+1,T=f-_;y.disabled.push({before:xz(o,T)}),y.disabled.push({after:Cl(c,T)})}!o&&c&&(y.disabled.push({before:Cl(c,-f+1)}),y.disabled.push({after:Cl(c,f-1)}))}return a.jsx(qW.Provider,{value:{selected:n,onDayClick:p,modifiers:y},children:r})}function GW(){var t=I.useContext(qW);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function EL(t){return Array.isArray(t)?QEe([],t):t!==void 0?[t]:[]}function KIt(t){var e={};return Object.entries(t).forEach(function(r){var n=r[0],i=r[1];e[n]=EL(i)}),e}var uf;(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"})(uf||(uf={}));var YIt=uf.Selected,op=uf.Disabled,ZIt=uf.Hidden,XIt=uf.Today,A$=uf.RangeEnd,j$=uf.RangeMiddle,k$=uf.RangeStart,QIt=uf.Outside;function JIt(t,e,r){var n,i=(n={},n[YIt]=EL(t.selected),n[op]=EL(t.disabled),n[ZIt]=EL(t.hidden),n[XIt]=[t.today],n[A$]=[],n[j$]=[],n[k$]=[],n[QIt]=[],n);return t.fromDate&&i[op].push({before:t.fromDate}),t.toDate&&i[op].push({after:t.toDate}),OC(t)?i[op]=i[op].concat(e.modifiers[op]):FC(t)&&(i[op]=i[op].concat(r.modifiers[op]),i[k$]=r.modifiers[k$],i[j$]=r.modifiers[j$],i[A$]=r.modifiers[A$]),i}var n2e=I.createContext(void 0);function eNt(t){var e=ba(),r=VW(),n=GW(),i=JIt(e,r,n),o=KIt(e.modifiers),c=hi(hi({},i),o);return a.jsx(n2e.Provider,{value:c,children:t.children})}function i2e(){var t=I.useContext(n2e);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function tNt(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function rNt(t){return!!(t&&typeof t=="object"&&"from"in t)}function nNt(t){return!!(t&&typeof t=="object"&&"after"in t)}function iNt(t){return!!(t&&typeof t=="object"&&"before"in t)}function sNt(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function aNt(t,e){var r,n=e.from,i=e.to;if(n&&i){var o=Jh(i,n)<0;o&&(r=[i,n],n=r[0],i=r[1]);var c=Jh(t,n)>=0&&Jh(i,t)>=0;return c}return i?Jl(i,t):n?Jl(n,t):!1}function oNt(t){return I7(t)}function lNt(t){return Array.isArray(t)&&t.every(I7)}function cNt(t,e){return e.some(function(r){if(typeof r=="boolean")return r;if(oNt(r))return Jl(t,r);if(lNt(r))return r.includes(t);if(rNt(r))return aNt(t,r);if(sNt(r))return r.dayOfWeek.includes(t.getDay());if(tNt(r)){var n=Jh(r.before,t),i=Jh(r.after,t),o=n>0,c=i<0,s=Bj(r.before,r.after);return s?c&&o:o||c}return nNt(r)?Jh(t,r.after)>0:iNt(r)?Jh(r.before,t)>0:typeof r=="function"?r(t):!1})}function HW(t,e,r){var n=Object.keys(e).reduce(function(o,c){var s=e[c];return cNt(t,s)&&o.push(c),o},[]),i={};return n.forEach(function(o){return i[o]=!0}),r&&!E3(t,r)&&(i.outside=!0),i}function uNt(t,e){for(var r=tu(t[0]),n=_C(t[t.length-1]),i,o,c=r;c<=n;){var s=HW(c,e),f=!s.disabled&&!s.hidden;if(!f){c=Cl(c,1);continue}if(s.selected)return c;s.today&&!o&&(o=c),i||(i=c),c=Cl(c,1)}return o||i}var dNt=365;function s2e(t,e){var r=e.moveBy,n=e.direction,i=e.context,o=e.modifiers,c=e.retry,s=c===void 0?{count:0,lastFocused:t}:c,f=i.weekStartsOn,p=i.fromDate,y=i.toDate,_=i.locale,T={day:Cl,week:xV,month:yd,year:I7e,startOfWeek:function(R){return i.ISOWeek?Vp(R):Sc(R,{locale:_,weekStartsOn:f})},endOfWeek:function(R){return i.ISOWeek?z0e(R):S3(R,{locale:_,weekStartsOn:f})}},E=T[r](t,n==="after"?1:-1);n==="before"&&p?E=N7e([p,E]):n==="after"&&y&&(E=P7e([y,E]));var k=!0;if(o){var P=HW(E,o);k=!P.disabled&&!P.hidden}return k?E:s.count>dNt?s.lastFocused:s2e(E,{moveBy:r,direction:n,context:i,modifiers:o,retry:hi(hi({},s),{count:s.count+1})})}var a2e=I.createContext(void 0);function hNt(t){var e=BC(),r=i2e(),n=I.useState(),i=n[0],o=n[1],c=I.useState(),s=c[0],f=c[1],p=uNt(e.displayMonths,r),y=i??(s&&e.isDateDisplayed(s))?s:p,_=function(){f(i),o(void 0)},T=function(R){o(R)},E=ba(),k=function(R,D){if(i){var M=s2e(i,{moveBy:R,direction:D,context:E,modifiers:r});Jl(i,M)||(e.goToDate(M,i),T(M))}},P={focusedDay:i,focusTarget:y,blur:_,focus:T,focusDayAfter:function(){return k("day","after")},focusDayBefore:function(){return k("day","before")},focusWeekAfter:function(){return k("week","after")},focusWeekBefore:function(){return k("week","before")},focusMonthBefore:function(){return k("month","before")},focusMonthAfter:function(){return k("month","after")},focusYearBefore:function(){return k("year","before")},focusYearAfter:function(){return k("year","after")},focusStartOfWeek:function(){return k("startOfWeek","before")},focusEndOfWeek:function(){return k("endOfWeek","after")}};return a.jsx(a2e.Provider,{value:P,children:t.children})}function WW(){var t=I.useContext(a2e);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function fNt(t,e){var r=i2e(),n=HW(t,r,e);return n}var KW=I.createContext(void 0);function mNt(t){if(!VF(t.initialProps)){var e={selected:void 0};return a.jsx(KW.Provider,{value:e,children:t.children})}return a.jsx(pNt,{initialProps:t.initialProps,children:t.children})}function pNt(t){var e=t.initialProps,r=t.children,n=function(o,c,s){var f,p,y;if((f=e.onDayClick)===null||f===void 0||f.call(e,o,c,s),c.selected&&!e.required){(p=e.onSelect)===null||p===void 0||p.call(e,void 0,o,c,s);return}(y=e.onSelect)===null||y===void 0||y.call(e,o,o,c,s)},i={selected:e.selected,onDayClick:n};return a.jsx(KW.Provider,{value:i,children:r})}function o2e(){var t=I.useContext(KW);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function gNt(t,e){var r=ba(),n=o2e(),i=VW(),o=GW(),c=WW(),s=c.focusDayAfter,f=c.focusDayBefore,p=c.focusWeekAfter,y=c.focusWeekBefore,_=c.blur,T=c.focus,E=c.focusMonthBefore,k=c.focusMonthAfter,P=c.focusYearBefore,R=c.focusYearAfter,D=c.focusStartOfWeek,M=c.focusEndOfWeek,B=function(be){var me,Pe,Ie,Se;VF(r)?(me=n.onDayClick)===null||me===void 0||me.call(n,t,e,be):OC(r)?(Pe=i.onDayClick)===null||Pe===void 0||Pe.call(i,t,e,be):FC(r)?(Ie=o.onDayClick)===null||Ie===void 0||Ie.call(o,t,e,be):(Se=r.onDayClick)===null||Se===void 0||Se.call(r,t,e,be)},V=function(be){var me;T(t),(me=r.onDayFocus)===null||me===void 0||me.call(r,t,e,be)},G=function(be){var me;_(),(me=r.onDayBlur)===null||me===void 0||me.call(r,t,e,be)},W=function(be){var me;(me=r.onDayMouseEnter)===null||me===void 0||me.call(r,t,e,be)},Z=function(be){var me;(me=r.onDayMouseLeave)===null||me===void 0||me.call(r,t,e,be)},Q=function(be){var me;(me=r.onDayPointerEnter)===null||me===void 0||me.call(r,t,e,be)},re=function(be){var me;(me=r.onDayPointerLeave)===null||me===void 0||me.call(r,t,e,be)},se=function(be){var me;(me=r.onDayTouchCancel)===null||me===void 0||me.call(r,t,e,be)},ue=function(be){var me;(me=r.onDayTouchEnd)===null||me===void 0||me.call(r,t,e,be)},_e=function(be){var me;(me=r.onDayTouchMove)===null||me===void 0||me.call(r,t,e,be)},we=function(be){var me;(me=r.onDayTouchStart)===null||me===void 0||me.call(r,t,e,be)},Ce=function(be){var me;(me=r.onDayKeyUp)===null||me===void 0||me.call(r,t,e,be)},Me=function(be){var me;switch(be.key){case"ArrowLeft":be.preventDefault(),be.stopPropagation(),r.dir==="rtl"?s():f();break;case"ArrowRight":be.preventDefault(),be.stopPropagation(),r.dir==="rtl"?f():s();break;case"ArrowDown":be.preventDefault(),be.stopPropagation(),p();break;case"ArrowUp":be.preventDefault(),be.stopPropagation(),y();break;case"PageUp":be.preventDefault(),be.stopPropagation(),be.shiftKey?P():E();break;case"PageDown":be.preventDefault(),be.stopPropagation(),be.shiftKey?R():k();break;case"Home":be.preventDefault(),be.stopPropagation(),D();break;case"End":be.preventDefault(),be.stopPropagation(),M();break}(me=r.onDayKeyDown)===null||me===void 0||me.call(r,t,e,be)},Ae={onClick:B,onFocus:V,onBlur:G,onKeyDown:Me,onKeyUp:Ce,onMouseEnter:W,onMouseLeave:Z,onPointerEnter:Q,onPointerLeave:re,onTouchCancel:se,onTouchEnd:ue,onTouchMove:_e,onTouchStart:we};return Ae}function yNt(){var t=ba(),e=o2e(),r=VW(),n=GW(),i=VF(t)?e.selected:OC(t)?r.selected:FC(t)?n.selected:void 0;return i}function xNt(t){return Object.values(uf).includes(t)}function _Nt(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(xNt(n)){var o=t.classNames["day_".concat(n)];o&&r.push(o)}}),r}function vNt(t,e){var r=hi({},t.styles.day);return Object.keys(e).forEach(function(n){var i;r=hi(hi({},r),(i=t.modifiersStyles)===null||i===void 0?void 0:i[n])}),r}function bNt(t,e,r){var n,i,o,c=ba(),s=WW(),f=fNt(t,e),p=gNt(t,f),y=yNt(),_=!!(c.onDayClick||c.mode!=="default");I.useEffect(function(){var W;f.outside||s.focusedDay&&_&&Jl(s.focusedDay,t)&&((W=r.current)===null||W===void 0||W.focus())},[s.focusedDay,t,r,_,f.outside]);var T=_Nt(c,f).join(" "),E=vNt(c,f),k=!!(f.outside&&!c.showOutsideDays||f.hidden),P=(o=(i=c.components)===null||i===void 0?void 0:i.DayContent)!==null&&o!==void 0?o:UIt,R=a.jsx(P,{date:t,displayMonth:e,activeModifiers:f}),D={style:E,className:T,children:R,role:"gridcell"},M=s.focusTarget&&Jl(s.focusTarget,t)&&!f.outside,B=s.focusedDay&&Jl(s.focusedDay,t),V=hi(hi(hi({},D),(n={disabled:f.disabled,role:"gridcell"},n["aria-selected"]=f.selected,n.tabIndex=B||M?0:-1,n)),p),G={isButton:_,isHidden:k,activeModifiers:f,selectedDays:y,buttonProps:V,divProps:D};return G}function wNt(t){var e=I.useRef(null),r=bNt(t.date,t.displayMonth,e);return r.isHidden?a.jsx("div",{role:"gridcell"}):r.isButton?a.jsx(XM,hi({name:"day",ref:e},r.buttonProps)):a.jsx("div",hi({},r.divProps))}function SNt(t){var e=t.number,r=t.dates,n=ba(),i=n.onWeekNumberClick,o=n.styles,c=n.classNames,s=n.locale,f=n.labels.labelWeekNumber,p=n.formatters.formatWeekNumber,y=p(Number(e),{locale:s});if(!i)return a.jsx("span",{className:c.weeknumber,style:o.weeknumber,children:y});var _=f(Number(e),{locale:s}),T=function(E){i(e,r,E)};return a.jsx(XM,{name:"week-number","aria-label":_,className:c.weeknumber,style:o.weeknumber,onClick:T,children:y})}function TNt(t){var e,r,n=ba(),i=n.styles,o=n.classNames,c=n.showWeekNumber,s=n.components,f=(e=s==null?void 0:s.Day)!==null&&e!==void 0?e:wNt,p=(r=s==null?void 0:s.WeekNumber)!==null&&r!==void 0?r:SNt,y;return c&&(y=a.jsx("td",{className:o.cell,style:i.cell,children:a.jsx(p,{number:t.weekNumber,dates:t.dates})})),a.jsxs("tr",{className:o.row,style:i.row,children:[y,t.dates.map(function(_){return a.jsx("td",{className:o.cell,style:i.cell,role:"presentation",children:a.jsx(f,{displayMonth:t.displayMonth,date:_})},OHe(_))})]})}function yle(t,e,r){for(var n=r!=null&&r.ISOWeek?z0e(e):S3(e,r),i=r!=null&&r.ISOWeek?Vp(t):Sc(t,r),o=Jh(n,i),c=[],s=0;s<=o;s++)c.push(Cl(i,s));var f=c.reduce(function(p,y){var _=r!=null&&r.ISOWeek?N7(y):R7(y,r),T=p.find(function(E){return E.weekNumber===_});return T?(T.dates.push(y),p):(p.push({weekNumber:_,dates:[y]}),p)},[]);return f}function ENt(t,e){var r=yle(tu(t),_C(t),e);if(e!=null&&e.useFixedWeeks){var n=BHe(t,e);if(n<6){var i=r[r.length-1],o=i.dates[i.dates.length-1],c=xV(o,6-n),s=yle(xV(o,1),c,e);r.push.apply(r,s)}}return r}function ANt(t){var e,r,n,i=ba(),o=i.locale,c=i.classNames,s=i.styles,f=i.hideHead,p=i.fixedWeeks,y=i.components,_=i.weekStartsOn,T=i.firstWeekContainsDate,E=i.ISOWeek,k=ENt(t.displayMonth,{useFixedWeeks:!!p,ISOWeek:E,locale:o,weekStartsOn:_,firstWeekContainsDate:T}),P=(e=y==null?void 0:y.Head)!==null&&e!==void 0?e:$It,R=(r=y==null?void 0:y.Row)!==null&&r!==void 0?r:TNt,D=(n=y==null?void 0:y.Footer)!==null&&n!==void 0?n:FIt;return a.jsxs("table",{id:t.id,className:c.table,style:s.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!f&&a.jsx(P,{}),a.jsx("tbody",{className:c.tbody,style:s.tbody,children:k.map(function(M){return a.jsx(R,{displayMonth:t.displayMonth,dates:M.dates,weekNumber:M.weekNumber},M.weekNumber)})}),a.jsx(D,{displayMonth:t.displayMonth})]})}function jNt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var kNt=jNt()?I.useLayoutEffect:I.useEffect,C$=!1,CNt=0;function xle(){return"react-day-picker-".concat(++CNt)}function INt(t){var e,r=t??(C$?xle():null),n=I.useState(r),i=n[0],o=n[1];return kNt(function(){i===null&&o(xle())},[]),I.useEffect(function(){C$===!1&&(C$=!0)},[]),(e=t??i)!==null&&e!==void 0?e:void 0}function NNt(t){var e,r,n=ba(),i=n.dir,o=n.classNames,c=n.styles,s=n.components,f=BC().displayMonths,p=INt(n.id?"".concat(n.id,"-").concat(t.displayIndex):void 0),y=n.id?"".concat(n.id,"-grid-").concat(t.displayIndex):void 0,_=[o.month],T=c.month,E=t.displayIndex===0,k=t.displayIndex===f.length-1,P=!E&&!k;i==="rtl"&&(e=[E,k],k=e[0],E=e[1]),E&&(_.push(o.caption_start),T=hi(hi({},T),c.caption_start)),k&&(_.push(o.caption_end),T=hi(hi({},T),c.caption_end)),P&&(_.push(o.caption_between),T=hi(hi({},T),c.caption_between));var R=(r=s==null?void 0:s.Caption)!==null&&r!==void 0?r:OIt;return a.jsxs("div",{className:_.join(" "),style:T,children:[a.jsx(R,{id:p,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),a.jsx(ANt,{id:y,"aria-labelledby":p,displayMonth:t.displayMonth})]},t.displayIndex)}function PNt(t){var e=ba(),r=e.classNames,n=e.styles;return a.jsx("div",{className:r.months,style:n.months,children:t.children})}function RNt(t){var e,r,n=t.initialProps,i=ba(),o=WW(),c=BC(),s=I.useState(!1),f=s[0],p=s[1];I.useEffect(function(){i.initialFocus&&o.focusTarget&&(f||(o.focus(o.focusTarget),p(!0)))},[i.initialFocus,f,o.focus,o.focusTarget,o]);var y=[i.classNames.root,i.className];i.numberOfMonths>1&&y.push(i.classNames.multiple_months),i.showWeekNumber&&y.push(i.classNames.with_weeknumber);var _=hi(hi({},i.styles.root),i.style),T=Object.keys(n).filter(function(k){return k.startsWith("data-")}).reduce(function(k,P){var R;return hi(hi({},k),(R={},R[P]=n[P],R))},{}),E=(r=(e=n.components)===null||e===void 0?void 0:e.Months)!==null&&r!==void 0?r:PNt;return a.jsx("div",hi({className:y.join(" "),style:_,dir:i.dir,id:i.id,nonce:n.nonce,title:n.title,lang:n.lang},T,{children:a.jsx(E,{children:c.displayMonths.map(function(k,P){return a.jsx(NNt,{displayIndex:P,displayMonth:k},P)})})}))}function LNt(t){var e=t.children,r=iIt(t,["children"]);return a.jsx(SIt,{initialProps:r,children:a.jsx(RIt,{children:a.jsx(mNt,{initialProps:r,children:a.jsx(VIt,{initialProps:r,children:a.jsx(HIt,{initialProps:r,children:a.jsx(eNt,{children:a.jsx(hNt,{children:e})})})})})})})}function DNt(t){return a.jsx(LNt,hi({},t,{children:a.jsx(RNt,{initialProps:t})}))}function l2e({className:t,classNames:e,showOutsideDays:r=!0,captionLayout:n,...i}){const o=n==="dropdown"?"dropdown-buttons":n;return a.jsx(DNt,{showOutsideDays:r,captionLayout:o,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(Ej({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(Ej({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})=>a.jsx(xm,{className:"h-4 w-4"}),IconRight:({...c})=>a.jsx(vd,{className:"h-4 w-4"})},...i})}l2e.displayName="Calendar";function c2e({open:t,onOpenChange:e,editTask:r,defaultDealId:n,defaultStageId:i}){var be;const o=ZEe(),c=ZCt(),{data:s}=nIt(),f=Gi(),{data:p}=gr({queryKey:["contacts-for-tasks",f],queryFn:async()=>{if(!f)return[];const me=[],Pe=1e3;for(let Ie=0;;Ie+=Pe){const{data:Se,error:ve}=await Re.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",f).order("first_name").order("id").range(Ie,Ie+Pe-1);if(ve)throw ve;if(me.push(...Se||[]),!Se||Se.length{r?(_(r.title),E(r.description||""),P(r.deal_id||"none"),D(r.contact_id||"none"),B(r.priority),G(r.status),Z(r.due_date?Hc(r.due_date):void 0),re(r.assignee_user_id&&r.assignee_user_id!==r.owner_user_id?r.assignee_user_id:"me")):(_(""),E(""),P(n||"none"),D("none"),B("medium"),G("todo"),Z(void 0),re("me"))},[r,t,n]);const Ae=async()=>{if(!y.trim()){Gt.error("Task title is required");return}try{const me={title:y.trim(),description:T.trim()||null,deal_id:k==="none"?null:k,contact_id:R==="none"?null:R,stage_id:i||null,priority:M,status:V,due_date:W?Ni(W,"yyyy-MM-dd"):null},Pe=Q==="me"?null:Q;if(r){if(ue)await c.mutateAsync({id:r.id,...me,assignee_user_id:Pe,assigned_by_user_id:Pe?f:null});else{const{deal_id:Ie,contact_id:Se,stage_id:ve,...We}=me;await c.mutateAsync({id:r.id,...We})}Gt.success("Task updated")}else await o.mutateAsync({...me,assignee_user_id:Pe}),Tx("task_created"),Gt.success("Task created");e(!1)}catch{Gt.error("Failed to save task")}};return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"sm:max-w-[480px]",children:[a.jsx(ml,{children:a.jsx(Ko,{children:r?"Edit Task":"New Task"})}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx(Mr,{children:"Title *"}),a.jsx($r,{value:y,onChange:me=>_(me.target.value),placeholder:"e.g., Send inspection report"})]}),a.jsxs("div",{children:[a.jsx(Mr,{children:"Description"}),a.jsx(bd,{value:T,onChange:me=>E(me.target.value),placeholder:"Optional details...",rows:2})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx(Mr,{children:"Priority"}),a.jsxs(_a,{value:M,onValueChange:me=>B(me),children:[a.jsx(aa,{children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"low",children:"🟢 Low"}),a.jsx(fn,{value:"medium",children:"🟡 Medium"}),a.jsx(fn,{value:"high",children:"🟠 High"}),a.jsx(fn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{children:"Status"}),a.jsxs(_a,{value:V,onValueChange:me=>G(me),children:[a.jsx(aa,{children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"todo",children:"To Do"}),a.jsx(fn,{value:"in_progress",children:"In Progress"}),a.jsx(fn,{value:"done",children:"Done"})]})]})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{children:"Due Date"}),a.jsxs(bL,{children:[a.jsx(wL,{asChild:!0,children:a.jsxs(zt,{variant:"outline",className:sr("w-full justify-start text-left font-normal",!W&&"text-muted-foreground"),children:[a.jsx(yo,{className:"mr-2 h-4 w-4"}),W?Ni(W,"PPP"):"Pick a date"]})}),a.jsx(KA,{className:"w-auto p-0",align:"start",children:a.jsx(l2e,{mode:"single",selected:W,onSelect:Z,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),ue&&se.length>0&&a.jsxs("div",{children:[a.jsx(Mr,{children:"Assign to"}),a.jsxs(_a,{value:Q,onValueChange:re,children:[a.jsx(aa,{children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"me",children:"Me"}),se.map(me=>a.jsxs(fn,{value:me.id,children:[me.name,me.teamName?` · ${me.teamName}`:""]},me.id))]})]})]}),ue&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(Mr,{children:"Link to Deal"}),a.jsxs(bL,{open:_e,onOpenChange:we,children:[a.jsx(wL,{asChild:!0,children:a.jsxs(zt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[a.jsxs("span",{className:"flex items-center gap-2 truncate",children:[a.jsx(go,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),k!=="none"?((be=s==null?void 0:s.find(me=>me.id===k))==null?void 0:be.deal_name)||"Select deal":"No Deal"]}),a.jsx(dU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a.jsx(KA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:a.jsxs(zj,{children:[a.jsx($j,{placeholder:"Search deals..."}),a.jsxs(Uj,{children:[a.jsx(Vj,{children:"No deals found."}),a.jsxs(q1,{children:[a.jsxs(ky,{value:"no-deal",onSelect:()=>{P("none"),we(!1)},children:[a.jsx(ko,{className:sr("mr-2 h-4 w-4",k==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),s==null?void 0:s.map(me=>a.jsxs(ky,{value:me.deal_name,onSelect:()=>{P(me.id),we(!1)},children:[a.jsx(ko,{className:sr("mr-2 h-4 w-4",k===me.id?"opacity-100":"opacity-0")}),me.deal_name]},me.id))]})]})]})})]})]}),a.jsxs("div",{children:[a.jsx(Mr,{children:"Link to Contact"}),a.jsxs(bL,{open:Ce,onOpenChange:Me,children:[a.jsx(wL,{asChild:!0,children:a.jsxs(zt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[a.jsxs("span",{className:"flex items-center gap-2 truncate",children:[a.jsx(vc,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),R!=="none"?(()=>{const me=p==null?void 0:p.find(Pe=>Pe.id===R);return me?`${me.first_name} ${me.last_name}`:"Select contact"})():"No Contact"]}),a.jsx(dU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a.jsx(KA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:a.jsxs(zj,{children:[a.jsx($j,{placeholder:"Search contacts..."}),a.jsxs(Uj,{children:[a.jsx(Vj,{children:"No contacts found."}),a.jsxs(q1,{children:[a.jsxs(ky,{value:"no-contact",onSelect:()=>{D("none"),Me(!1)},children:[a.jsx(ko,{className:sr("mr-2 h-4 w-4",R==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),p==null?void 0:p.map(me=>a.jsxs(ky,{value:`${me.first_name??""} ${me.last_name??""} ${me.id}`,onSelect:()=>{D(me.id),Me(!1)},children:[a.jsx(ko,{className:sr("mr-2 h-4 w-4",R===me.id?"opacity-100":"opacity-0")}),me.first_name," ",me.last_name]},me.id))]})]})]})})]})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(zt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),a.jsx(zt,{onClick:Ae,disabled:o.isPending||c.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const MNt={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 ONt({tasks:t}){const e=$W(),r=XCt(),n=Gs(),[i,o]=I.useState(null),c=async y=>{const _=y.status==="done"?"todo":"done";try{await e.mutateAsync({id:y.id,status:_})}catch{Gt.error("Failed to update task")}},s=async y=>{try{await r.mutateAsync(y),Gt.success("Task deleted")}catch{Gt.error("Failed to delete task")}};if(t.length===0)return a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[a.jsx(ic,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),a.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),a.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const f=new Map,p=[];return t.forEach(y=>{if(y.deal){const _=f.get(y.deal.id)||{dealName:y.deal.deal_name,tasks:[]};_.tasks.push(y),f.set(y.deal.id,_)}else p.push(y)}),a.jsxs("div",{className:"space-y-4",children:[p.length>0&&a.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[a.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:a.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),p.map(y=>a.jsx(_le,{task:y,onToggle:c,onDelete:s,onEdit:o,onNavigateDeal:_=>n(`/mission-control/pipeline?deal=${_}`)},y.id))]}),Array.from(f.entries()).map(([y,_])=>a.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${y}`),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:[a.jsx(go,{className:"h-3.5 w-3.5 text-muted-foreground"}),a.jsx("h3",{className:"font-medium text-sm",children:_.dealName}),a.jsxs(us,{variant:"secondary",className:"ml-auto text-xs",children:[_.tasks.filter(T=>T.status==="done").length,"/",_.tasks.length]}),a.jsx(vd,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),_.tasks.map(T=>a.jsx(_le,{task:T,onToggle:c,onDelete:s,onEdit:o,onNavigateDeal:E=>n(`/mission-control/pipeline?deal=${E}`)},T.id))]},y)),i&&a.jsx(c2e,{open:!!i,onOpenChange:()=>o(null),editTask:i})]})}function FNt({task:t,onToggle:e}){const r=sit(),{data:n}=nit(),i=t.contact;if(!i||t.status==="done")return null;const o="h-7 w-7 inline-flex items-center justify-center rounded-md border bg-background text-muted-foreground hover:text-primary hover:border-primary/40 transition-colors",c=async()=>{const s=(n==null?void 0:n.find(f=>/call/i.test(f.name)))||(n==null?void 0:n[0]);if(!s){Gt.error("No touch types available");return}try{await r.mutateAsync({contactId:i.id,actionTypeId:s.id,notes:`Task: ${t.title}`}),e(t),Gt.success(`Touch logged for ${i.first_name} and task completed`)}catch{Gt.error("Could not log touch")}};return a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.phone&&a.jsx("a",{href:`tel:${i.phone}`,className:o,title:`Call ${i.first_name}`,children:a.jsx(ai,{className:"h-3.5 w-3.5"})}),i.phone&&a.jsx("a",{href:`sms:${i.phone}`,className:o,title:`Text ${i.first_name}`,children:a.jsx(of,{className:"h-3.5 w-3.5"})}),i.email&&a.jsx("a",{href:`mailto:${i.email}`,className:o,title:`Email ${i.first_name}`,children:a.jsx(Ti,{className:"h-3.5 w-3.5"})}),a.jsx("button",{onClick:c,disabled:r.isPending,className:o,title:"Log touch & complete",children:a.jsx(dDe,{className:"h-3.5 w-3.5"})})]})}function _le({task:t,onToggle:e,onDelete:r,onEdit:n,onNavigateDeal:i}){const o=t.status==="done",c=!o&&t.due_date&&V1(Hc(t.due_date))&&!th(Hc(t.due_date)),s=!o&&t.due_date&&th(Hc(t.due_date)),f=MNt[t.priority],p=Gi(),{data:y=[]}=XEe(),_=k=>{var P;return((P=y.find(R=>R.id===k))==null?void 0:P.name)||"Teammate"},T=t.owner_user_id===p&&t.assignee_user_id&&t.assignee_user_id!==p,E=t.owner_user_id!==p&&t.assignee_user_id===p;return a.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",o&&"opacity-60"),children:[a.jsx("button",{onClick:()=>e(t),className:"shrink-0",children:o?a.jsx(ic,{className:"h-5 w-5 text-emerald-500"}):a.jsx(F_,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:sr("text-sm font-medium truncate",o&&"line-through text-muted-foreground"),children:t.title}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[t.stage&&a.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&&a.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[a.jsx(vc,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]}),T&&a.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary flex items-center gap-0.5",children:[a.jsx(xU,{className:"h-2.5 w-2.5"})," Assigned to ",_(t.assignee_user_id)]}),E&&a.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent text-accent-foreground flex items-center gap-0.5",children:[a.jsx(xU,{className:"h-2.5 w-2.5"})," From ",_(t.owner_user_id)]})]})]}),a.jsx(FNt,{task:t,onToggle:e}),a.jsxs(us,{variant:"outline",className:sr("text-[10px] shrink-0",f.color),children:[f.dot," ",f.label]}),t.due_date&&a.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:[a.jsx(Rl,{className:"h-3 w-3"}),Ni(Hc(t.due_date),"MMM d")]}),a.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:()=>n(t),className:"p-1 hover:bg-muted rounded",children:a.jsx(gU,{className:"h-3.5 w-3.5 text-muted-foreground"})}),t.owner_user_id===p&&a.jsx("button",{onClick:()=>r(t.id),className:"p-1 hover:bg-destructive/10 rounded",children:a.jsx(cD,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const BNt=[{status:"todo",label:"To Do",icon:F_,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:n9,color:"border-t-blue-500"},{status:"done",label:"Done",icon:ic,color:"border-t-emerald-500"}],zNt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function $Nt({tasks:t}){const e=$W(),r=I.useMemo(()=>{const o={todo:[],in_progress:[],done:[]};return t.forEach(c=>o[c.status].push(c)),o},[t]),n=(o,c)=>{o.dataTransfer.setData("taskId",c)},i=async(o,c)=>{o.preventDefault();const s=o.dataTransfer.getData("taskId");if(!s)return;const f=t.find(p=>p.id===s);if(!(!f||f.status===c))try{await e.mutateAsync({id:s,status:c})}catch{Gt.error("Failed to move task")}};return a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:BNt.map(o=>a.jsxs("div",{className:sr("border rounded-lg border-t-4 bg-muted/20",o.color),onDragOver:c=>c.preventDefault(),onDrop:c=>i(c,o.status),children:[a.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[a.jsx(o.icon,{className:"h-4 w-4 text-muted-foreground"}),a.jsx("h3",{className:"font-semibold text-sm",children:o.label}),a.jsx(us,{variant:"secondary",className:"ml-auto text-xs",children:r[o.status].length})]}),a.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[o.status].map(c=>a.jsx(UNt,{task:c,onDragStart:n},c.id)),r[o.status].length===0&&a.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},o.status))})}function UNt({task:t,onDragStart:e}){const r=t.status==="done",n=!r&&t.due_date&&V1(Hc(t.due_date))&&!th(Hc(t.due_date)),i=!r&&t.due_date&&th(Hc(t.due_date));return a.jsx("div",{draggable:!0,onDragStart:o=>e(o,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:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-xs mt-0.5",children:zNt[t.priority]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:sr("text-sm font-medium",r&&"line-through text-muted-foreground"),children:t.title}),a.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[t.deal&&a.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[a.jsx(go,{className:"h-2.5 w-2.5"}),t.deal.deal_name]}),t.contact&&a.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[a.jsx(vc,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]}),t.due_date&&a.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:[a.jsx(Rl,{className:"h-2.5 w-2.5"}),n?"Overdue — ":i?"Due today — ":"",Ni(Hc(t.due_date),"MMM d")]}),t.stage&&a.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 vle={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function VNt({tasks:t}){const[e,r]=I.useState(new Date),n=$W(),i=tu(e),o=_C(e),c=Sc(i),s=S3(o),f=$7e({start:c,end:s}),p=I.useMemo(()=>{const T=new Map;return t.forEach(E=>{if(!E.due_date)return;const k=E.due_date,P=T.get(k)||[];P.push(E),T.set(k,P)}),T},[t]),y=I.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{Gt.error("Failed to update task")}};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(zt,{variant:"ghost",size:"icon",onClick:()=>r(JWe(e,1)),children:a.jsx(xm,{className:"h-4 w-4"})}),a.jsx("h3",{className:"font-semibold",children:Ni(e,"MMMM yyyy")}),a.jsx(zt,{variant:"ghost",size:"icon",onClick:()=>r(yd(e,1)),children:a.jsx(vd,{className:"h-4 w-4"})})]}),a.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>a.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:T},T))}),a.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:f.map(T=>{const E=Ni(T,"yyyy-MM-dd"),k=p.get(E)||[],P=E3(T,e),R=th(T);return a.jsxs("div",{className:sr("border-r border-b min-h-[100px] p-1",!P&&"bg-muted/30",R&&"bg-primary/5"),children:[a.jsx("div",{className:sr("text-xs font-medium mb-1 text-right px-1",!P&&"text-muted-foreground/40",R&&"text-primary font-bold"),children:Ni(T,"d")}),a.jsxs("div",{className:"space-y-0.5",children:[k.slice(0,3).map(D=>a.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"?a.jsx(ic,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):a.jsx(F_,{className:"h-2.5 w-2.5 shrink-0"}),a.jsxs("span",{className:"truncate",children:[vle[D.priority]," ",D.title]})]},D.id)),k.length>3&&a.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",k.length-3," more"]})]})]},E)})}),y.length>0&&a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",y.length,")"]}),a.jsx("div",{className:"space-y-1",children:y.map(T=>a.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"?a.jsx(ic,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):a.jsx(F_,{className:"h-3.5 w-3.5 shrink-0"}),a.jsxs("span",{className:"truncate",children:[vle[T.priority]," ",T.title]}),T.deal&&a.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",T.deal.deal_name]})]},T.id))})]})]})}const qNt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function GNt({open:t,onOpenChange:e,stages:r}){var D;const[n,i]=I.useState(((D=r[0])==null?void 0:D.id)||""),{data:o,isLoading:c}=QCt(n||void 0),s=JCt(),f=eIt(),[p,y]=I.useState(""),[_,T]=I.useState("medium"),[E,k]=I.useState(""),P=async()=>{if(!(!p.trim()||!n))try{await s.mutateAsync({stage_id:n,title:p.trim(),priority:_,default_due_offset_days:E?parseInt(E):null,sort_order:((o==null?void 0:o.length)||0)+1}),y(""),k(""),Gt.success("Template added")}catch{Gt.error("Failed to add template")}},R=async M=>{try{await f.mutateAsync(M),Gt.success("Template deleted")}catch{Gt.error("Failed to delete template")}};return a.jsx(io,{open:t,onOpenChange:e,children:a.jsxs(Ua,{className:"sm:max-w-[560px]",children:[a.jsx(ml,{children:a.jsxs(Ko,{className:"flex items-center gap-2",children:[a.jsx(XLe,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),a.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),a.jsxs("div",{children:[a.jsx(Mr,{children:"Pipeline Stage"}),a.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=>a.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))})]}),a.jsx(Sm,{className:"max-h-[250px]",children:a.jsxs("div",{className:"space-y-1.5",children:[o==null?void 0:o.map((M,B)=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[a.jsx("span",{className:"text-xs",children:qNt[M.priority]}),a.jsx("span",{className:"text-sm flex-1 truncate",children:M.title}),M.default_due_offset_days&&a.jsxs(us,{variant:"outline",className:"text-[10px]",children:["+",M.default_due_offset_days,"d"]}),a.jsx("button",{onClick:()=>R(M.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:a.jsx(cD,{className:"h-3.5 w-3.5 text-destructive"})})]},M.id)),(o==null?void 0:o.length)===0&&n&&a.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&a.jsxs("div",{className:"space-y-3 border-t pt-3",children:[a.jsx(Mr,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx($r,{placeholder:"Task title...",value:p,onChange:M=>y(M.target.value),className:"flex-1",onKeyDown:M=>M.key==="Enter"&&P()}),a.jsxs(_a,{value:_,onValueChange:M=>T(M),children:[a.jsx(aa,{className:"w-[100px]",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"low",children:"🟢 Low"}),a.jsx(fn,{value:"medium",children:"🟡 Med"}),a.jsx(fn,{value:"high",children:"🟠 High"}),a.jsx(fn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),a.jsxs("div",{className:"flex gap-2 items-end",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx(Mr,{className:"text-xs",children:"Due offset (days from entering stage)"}),a.jsx($r,{type:"number",placeholder:"e.g., 7",value:E,onChange:M=>k(M.target.value)})]}),a.jsxs(zt,{onClick:P,disabled:!p.trim()||s.isPending,children:[a.jsx(sm,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}const qF=t=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,HNt=t=>{const[e,r,n]=t.split(/[-/T]/).map(Number);return new Date(e,r-1,n)},tj=(t,e)=>{const r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+e);return qF(r)},u2e=t=>{const r=(8-t.getDay())%7||7;return tj(t,r)},WNt=(t,e)=>!!t&&t.slice(0,10)t==="today"?qF(e):t==="plus3"?tj(e,3):u2e(e),YNt=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function ZNt(t,e){let r=` ${t.trim()} `,n=null,i=null;const o=r.match(/\s!(low|medium|high|urgent)\b/i)||r.match(/\s(urgent|high priority|low priority)\b/i);o&&(i=o[1].toLowerCase().replace(" priority",""),r=r.replace(o[0]," "));const c=[[/\s(today)\b/i,()=>qF(e)],[/\s(tomorrow|tmrw)\b/i,()=>tj(e,1)],[/\s(next week)\b/i,()=>u2e(e)],[/\sin (\d{1,2}) days?\b/i,()=>""]];for(const[s,f]of c){const p=r.match(s);if(p){n=s.source.includes("\\d")?tj(e,Number(p[1])):f(),r=r.replace(p[0]," ");break}}if(!n){const s=r.match(/\s(?:on |next )?(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\b/i);if(s){const p=(YNt.indexOf(s[1].toLowerCase())-e.getDay()+7)%7||7;n=tj(e,p),r=r.replace(s[0]," ")}}return{title:r.replace(/\s+/g," ").trim(),due:n,priority:i}}function XNt({tasks:t}){const e=tIt(),r=new Date,n=t.filter(o=>o.status!=="done"&&WNt(o.due_date,r));if(!n.length)return null;const i=async(o,c)=>{try{await e.mutateAsync({ids:n.map(s=>s.id),due_date:KNt(o,new Date)}),Gt.success(`${n.length} task${n.length===1?"":"s"} moved to ${c}`)}catch{Gt.error("Could not reschedule tasks")}};return a.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(PS,{className:"h-4 w-4 text-destructive"}),a.jsxs("span",{children:[a.jsxs("strong",{children:[n.length," overdue"]})," — clear the backlog in one click."]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 md:ml-auto",children:[a.jsxs(zt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("today","today"),children:[a.jsx(r9,{className:"h-3.5 w-3.5 mr-1"})," Move all to today"]}),a.jsx(zt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("plus3","3 days from now"),children:"Push +3 days"}),a.jsx(zt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("monday","Monday"),children:"Push to Monday"})]})]})}function QNt({contactId:t,dealId:e}){const[r,n]=I.useState(""),i=ZEe(),o=r.trim()?ZNt(r,new Date):null,c=async()=>{if(o!=null&&o.title)try{await i.mutateAsync({title:o.title,due_date:o.due,priority:o.priority||"medium",contact_id:t||null,deal_id:e||null}),Tx("task_created"),n(""),Gt.success("Task added")}catch{Gt.error("Could not add task")}};return a.jsxs("div",{className:"rounded-lg border bg-card px-3 py-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sm,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a.jsx($r,{value:r,onChange:s=>n(s.target.value),onKeyDown:s=>{s.key==="Enter"&&c()},placeholder:'Quick add… try "Call Sarah tomorrow !high" or "Send CMA friday"',className:"border-0 shadow-none focus-visible:ring-0 px-0"}),a.jsx(zt,{size:"sm",onClick:c,disabled:!(o!=null&&o.title)||i.isPending,children:"Add"})]}),o&&(o.due||o.priority)&&a.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground mt-1 pl-6",children:[a.jsx(xs,{className:"h-3 w-3 text-primary"}),o.due&&a.jsxs(a.Fragment,{children:["Due ",Ni(HNt(o.due),"EEE, MMM d")]}),o.priority&&a.jsxs(a.Fragment,{children:[" · ",o.priority," priority"]})]})]})}function JNt(){const{data:t,isLoading:e}=YCt(),{data:r}=rIt(),[n,i]=I.useState("list"),[o,c]=I.useState(""),[s,f]=I.useState("active"),[p,y]=I.useState("all"),[_,T]=I.useState("all"),[E,k]=I.useState("all"),P=Gi(),[R,D]=I.useState(!1),[M,B]=I.useState(!1),V=I.useMemo(()=>{if(!t)return[];const Z=new Map;return t.forEach(Q=>{Q.deal&&Z.set(Q.deal.id,Q.deal.deal_name)}),Array.from(Z,([Q,re])=>({id:Q,name:re}))},[t]),G=I.useMemo(()=>t?t.filter(Z=>{var Ae,be,me,Pe;const Q=o.toLowerCase(),re=!Q||Z.title.toLowerCase().includes(Q)||((be=(Ae=Z.deal)==null?void 0:Ae.deal_name)==null?void 0:be.toLowerCase().includes(Q))||`${((me=Z.contact)==null?void 0:me.first_name)||""} ${((Pe=Z.contact)==null?void 0:Pe.last_name)||""}`.toLowerCase().includes(Q),se=s==="all"||s==="active"&&Z.status!=="done"||s==="todo"&&Z.status==="todo"||s==="in_progress"&&Z.status==="in_progress"||s==="done"&&Z.status==="done"||s==="overdue"&&Z.status!=="done"&&Z.due_date&&V1(Hc(Z.due_date))&&!th(Hc(Z.due_date)),ue=p==="all"||Z.priority===p,_e=_==="all"||_==="no_deal"&&!Z.deal_id||Z.deal_id===_,we=Z.owner_user_id===P&&!!Z.assignee_user_id&&Z.assignee_user_id!==P,Ce=Z.owner_user_id!==P&&Z.assignee_user_id===P;return re&&se&&ue&&_e&&(E==="all"||E==="mine"&&!we||E==="delegated"&&we||E==="assigned"&&Ce)}):[],[t,o,s,p,_,E,P]),W=I.useMemo(()=>{if(!t)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const Z=t.filter(Q=>Q.status!=="done");return{total:Z.length,overdue:Z.filter(Q=>Q.due_date&&V1(Hc(Q.due_date))&&!th(Hc(Q.due_date))).length,dueToday:Z.filter(Q=>Q.due_date&&th(Hc(Q.due_date))).length,dueThisWeek:Z.filter(Q=>Q.due_date&&OWe(Hc(Q.due_date))).length,completed:t.filter(Q=>Q.status==="done").length}},[t]);return a.jsx(G1,{children:a.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[a.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),a.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(zt,{variant:"outline",size:"sm",onClick:()=>B(!0),children:[a.jsx(QLe,{className:"h-4 w-4 mr-1"}),"Templates"]}),a.jsxs(zt,{size:"sm",onClick:()=>D(!0),children:[a.jsx(sm,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[a.jsx(pU,{className:"h-3.5 w-3.5"}),"Active"]}),a.jsx("p",{className:"text-xl font-bold mt-1",children:W.total})]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[a.jsx(PS,{className:"h-3.5 w-3.5"}),"Overdue"]}),a.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:W.overdue})]}),a.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[a.jsx(Rl,{className:"h-3.5 w-3.5"}),"Due Today"]}),a.jsx("p",{className:"text-xl font-bold mt-1",children:W.dueToday})]}),a.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[a.jsx(im,{className:"h-3.5 w-3.5"}),"This Week"]}),a.jsx("p",{className:"text-xl font-bold mt-1",children:W.dueThisWeek})]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[a.jsx(ic,{className:"h-3.5 w-3.5"}),"Completed"]}),a.jsx("p",{className:"text-xl font-bold mt-1",children:W.completed})]})]}),a.jsx(XNt,{tasks:t||[]}),a.jsx(QNt,{}),a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[a.jsxs("div",{className:"relative flex-1 max-w-sm",children:[a.jsx(hd,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a.jsx($r,{placeholder:"Search tasks...",value:o,onChange:Z=>c(Z.target.value),className:"pl-9"})]}),a.jsxs(_a,{value:p,onValueChange:y,children:[a.jsx(aa,{className:"w-[130px]",children:a.jsx(va,{placeholder:"Priority"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"All Priorities"}),a.jsx(fn,{value:"urgent",children:"🔴 Urgent"}),a.jsx(fn,{value:"high",children:"🟠 High"}),a.jsx(fn,{value:"medium",children:"🟡 Medium"}),a.jsx(fn,{value:"low",children:"🟢 Low"})]})]}),a.jsxs(_a,{value:_,onValueChange:T,children:[a.jsx(aa,{className:"w-[160px]",children:a.jsx(va,{placeholder:"Deal"})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"All Deals"}),a.jsx(fn,{value:"no_deal",children:"No Deal"}),V.map(Z=>a.jsx(fn,{value:Z.id,children:Z.name},Z.id))]})]}),a.jsxs(_a,{value:E,onValueChange:Z=>k(Z),children:[a.jsx(aa,{className:"w-[170px]",children:a.jsx(va,{})}),a.jsxs(oa,{children:[a.jsx(fn,{value:"all",children:"Everyone's"}),a.jsx(fn,{value:"mine",children:"My to-dos"}),a.jsx(fn,{value:"assigned",children:"Assigned to me"}),a.jsx(fn,{value:"delegated",children:"Delegated by me"})]})]}),a.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[a.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:a.jsx(pU,{className:"h-4 w-4"})}),a.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:a.jsx(i9,{className:"h-4 w-4"})}),a.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:a.jsx(im,{className:"h-4 w-4"})})]})]}),e?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):a.jsxs(a.Fragment,{children:[n==="list"&&a.jsx(ONt,{tasks:G}),n==="kanban"&&a.jsx($Nt,{tasks:G}),n==="calendar"&&a.jsx(VNt,{tasks:G})]}),a.jsx(c2e,{open:R,onOpenChange:D}),a.jsx(GNt,{open:M,onOpenChange:B,stages:r||[]})]})})}const n9t={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"},i9t={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 ePt(t=!0){return gr({queryKey:["marketplace-categories",t],queryFn:async()=>{let e=Re.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 s9t(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_categories").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Gt.success("Category created successfully")},onError:e=>{Gt.error("Failed to create category: "+e.message)}})}function a9t(){const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("marketplace_categories").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Gt.success("Category updated successfully")},onError:e=>{Gt.error("Failed to update category: "+e.message)}})}function o9t(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("marketplace_categories").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Gt.success("Category deleted successfully")},onError:e=>{Gt.error("Failed to delete category: "+e.message)}})}function tPt(t,e=!0){return gr({queryKey:["marketplace-products",t,e],queryFn:async()=>{let r=Re.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 l9t(t){return gr({queryKey:["marketplace-product",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 c9t(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_products").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Gt.success("Product created successfully")},onError:e=>{Gt.error("Failed to create product: "+e.message)}})}function u9t(){const t=Nr();return kr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.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]}),Gt.success("Product updated successfully")},onError:e=>{Gt.error("Failed to update product: "+e.message)}})}function d9t(){const t=Nr();return kr({mutationFn:async e=>{const{error:r}=await Re.from("marketplace_products").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Gt.success("Product deleted successfully")},onError:e=>{Gt.error("Failed to delete product: "+e.message)}})}function h9t(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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 f9t(){const t=Nr();return kr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Re.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]}),Gt.success("Image deleted successfully")},onError:e=>{Gt.error("Failed to delete image: "+e.message)}})}function m9t(){const t=Nr();return kr({mutationFn:async({imageId:e,productId:r})=>{const{error:n}=await Re.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:i}=await Re.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]}),Gt.success("Primary image updated")},onError:e=>{Gt.error("Failed to set primary image: "+e.message)}})}function p9t(){const t=Nr();return kr({mutationFn:async e=>{const{data:r,error:n}=await Re.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]}),Gt.success("Variant added successfully")}})}function g9t(){const t=Nr();return kr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Re.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]}),Gt.success("Variant deleted successfully")}})}function y9t(){const t=Nr();return kr({mutationFn:async({productId:e,videoUrl:r})=>{await Re.from("marketplace_product_videos").delete().eq("product_id",e);const{data:n,error:i}=await Re.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]}),Gt.success("Video updated successfully")}})}function x9t(t){const{isAdmin:e}=Gn();return gr({queryKey:["marketplace-orders",t,e],queryFn:async()=>{let r=Re.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 o=[...new Set(n.map(f=>f.user_id))],{data:c}=await Re.from("profiles").select("id, name, email").in("id",o),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 _9t(){const{user:t}=Gn();return gr({queryKey:["my-marketplace-orders",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Re.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 v9t(t){return gr({queryKey:["marketplace-order",t],queryFn:async()=>{const{data:e,error:r}=await Re.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 b9t(){const t=Nr(),{user:e}=Gn();return kr({mutationFn:async({orderId:r,status:n,notes:i,trackingNumber:o,trackingUrl:c,previousStatus:s})=>{const f={status:n};o!==void 0&&(f.tracking_number=o),c!==void 0&&(f.tracking_url=c);const{error:p}=await Re.from("marketplace_orders").update(f).eq("id",r);if(p)throw p;const{error:y}=await Re.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:i,created_by:e==null?void 0:e.id});if(y)throw y;if(["shipped","in_production","processing","completed"].includes(n)&&n!==s)try{await Re.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:o,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"]}),Gt.success("Order status updated")},onError:r=>{Gt.error("Failed to update order: "+r.message)}})}function w9t(){const t=Nr();return kr({mutationFn:async({itemId:e,proofUrl:r,proofNotes:n,orderId:i})=>{const{error:o}=await Re.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",e);if(o)throw o;await Re.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",i);try{await Re.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"]}),Gt.success("Proof uploaded & customer notified")}})}function S9t(){const t=Nr();return kr({mutationFn:async({itemId:e,orderId:r})=>{const{error:n}=await Re.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"]}),Gt.success("Proof approved")}})}function T9t(){const t=Nr();return kr({mutationFn:async({itemId:e,orderId:r,reason:n})=>{const{error:i}=await Re.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"]}),Gt.success("Proof rejected - please upload a new proof")}})}function rPt(){const t=Gs(),[e,r]=I.useState(null),{data:n,isLoading:i}=tPt(e||void 0,!0),{data:o,isLoading:c}=ePt(!0),{cartItems:s}=N_e(),f=s.reduce((y,_)=>y+_.quantity,0),p=y=>{t(`/marketplace/${y.id}`)};return i||c?a.jsx(G1,{title:"Marketplace",children:a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(y=>a.jsx(dl,{className:"h-10 w-24 flex-shrink-0"},y))}),a.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(y=>a.jsx(dl,{className:"h-72 w-full"},y))})]})}):a.jsx(G1,{title:"Marketplace",children:a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),a.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),a.jsxs(zt,{variant:"outline",onClick:()=>t("/marketplace/cart"),className:"relative",children:[a.jsx($fe,{className:"h-4 w-4 mr-2"}),"Cart",f>0&&a.jsx(us,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:f})]})]}),o&&o.length>0&&a.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[a.jsx(zt,{variant:e===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),o.map(y=>a.jsx(zt,{variant:e===y.id?"default":"outline",size:"sm",onClick:()=>r(y.id),children:y.name},y.id))]}),n&&n.length>0?a.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(y=>{var _;return a.jsxs(Wn,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>p(y),children:[a.jsxs("div",{className:"aspect-square bg-muted relative",children:[y.images&&y.images.length>0?a.jsx("img",{src:((_=y.images.find(T=>T.is_primary))==null?void 0:_.image_url)||y.images[0].image_url,alt:y.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(xee,{className:"h-12 w-12 text-muted-foreground"})}),y.category&&a.jsx(us,{className:"absolute top-2 left-2",variant:"secondary",children:y.category.name})]}),a.jsxs(si,{className:"p-4",children:[a.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:y.name}),y.description&&a.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:y.description}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"font-bold text-lg",children:["$",Number(y.base_price).toFixed(2)]}),y.variants&&y.variants.length>0&&a.jsxs("span",{className:"text-xs text-muted-foreground",children:[y.variants.length," options"]})]})]})]},y.id)})}):a.jsxs("div",{className:"text-center py-12",children:[a.jsx(xee,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),a.jsx("p",{className:"text-muted-foreground",children:"No products available yet."})]})]})})}const zC={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 sA({delay:t,x:e,y:r,size:n}){return a.jsx(fr.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 nPt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:_,videoUrl:T}=t,E=zC[e];return a.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:[a.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[a.jsx(fr.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"}}),a.jsx(fr.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"}}),a.jsx(sA,{delay:0,x:"15%",y:"20%",size:8}),a.jsx(sA,{delay:1,x:"80%",y:"30%",size:6}),a.jsx(sA,{delay:2,x:"60%",y:"70%",size:10}),a.jsx(sA,{delay:.5,x:"25%",y:"80%",size:7}),a.jsx(sA,{delay:1.5,x:"70%",y:"15%",size:5})]}),a.jsxs(fr.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:[a.jsxs(fr.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:[a.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:a.jsx(fr.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"}})}),a.jsxs("div",{className:"px-8 py-10 text-center",children:[a.jsxs(fr.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:[a.jsx(fr.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"}}),a.jsx("span",{className:"text-4xl",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&a.jsx(fr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:a.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[i," ",i===1?"Year":"Years"]})}),a.jsx(fr.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]&&a.jsx(fr.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]}),a.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[a.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&a.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),a.jsx(fr.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"}}),_&&a.jsx(fr.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:a.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&a.jsx(fr.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:a.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),a.jsx(fr.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:o||E.defaultMessage}),a.jsxs(fr.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:[a.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?a.jsx(fr.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}}):a.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:a.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:c.charAt(0)})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:c}),y&&a.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:y})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[f&&a.jsxs(fr.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call"]}),p&&a.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),a.jsx(fr.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 I$({delay:t,x:e,y:r,color:n,size:i}){return a.jsx(fr.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 aA({delay:t,x:e,y:r}){return a.jsx(fr.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 ble={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 iPt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:_,videoUrl:T}=t,E=zC[e],k=ble[e]||ble.home_anniversary;return a.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${k.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[a.jsx(I$,{delay:0,x:"10%",y:"10%",color:k.orbs[0],size:200}),a.jsx(I$,{delay:1,x:"70%",y:"60%",color:k.orbs[1],size:180}),a.jsx(I$,{delay:2,x:"50%",y:"20%",color:k.orbs[2],size:150}),a.jsx(aA,{delay:0,x:"20%",y:"25%"}),a.jsx(aA,{delay:.8,x:"75%",y:"15%"}),a.jsx(aA,{delay:1.6,x:"85%",y:"65%"}),a.jsx(aA,{delay:2.4,x:"10%",y:"75%"}),a.jsx(aA,{delay:.4,x:"45%",y:"85%"}),a.jsxs(fr.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:[a.jsxs(fr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[a.jsx(fr.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%"}}),a.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:[a.jsxs(fr.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:[a.jsx(fr.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"}}),a.jsx("span",{className:"text-4xl relative z-10",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&a.jsxs(fr.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:[a.jsx(fr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),a.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:i===1?"Year":"Years"})]}),a.jsx(fr.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]&&a.jsx(fr.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]}),a.jsx(fr.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("")}),a.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[a.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&a.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[a.jsx(La,{className:"h-3.5 w-3.5"}),n]})]}),_&&a.jsx(fr.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:a.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&a.jsx(fr.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:a.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),a.jsx(fr.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:a.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:o||E.defaultMessage})}),a.jsxs(fr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[a.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?a.jsx(fr.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}}):a.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:a.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-sm font-bold text-white",children:c}),y&&a.jsx("p",{className:"text-xs text-violet-300/60",children:y})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[f&&a.jsxs(fr.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call Me"]}),p&&a.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),a.jsx(fr.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 sPt({emoji:t,delay:e,x:r,duration:n}){return a.jsx(fr.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 wle={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 aPt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:_,videoUrl:T}=t,E=zC[e],k=wle[e]||wle.home_anniversary;return a.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${k.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[E.emojis.map((P,R)=>a.jsx(sPt,{emoji:P,delay:R*1.2,x:`${15+R*14}%`,duration:5+R%3},R)),a.jsx(fr.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"}}),a.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[a.jsxs(fr.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:[a.jsxs(fr.div,{className:`h-28 bg-gradient-to-r ${k.header} relative overflow-hidden`,children:[a.jsx(fr.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"}}),a.jsx(fr.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]}),a.jsx(fr.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]}),a.jsx(fr.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]})]}),a.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[a.jsx(fr.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:a.jsx(fr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:a.jsx("span",{className:"text-3xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&a.jsx(fr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:a.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${k.accent}`,children:[a.jsx(fr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),a.jsx("span",{className:"text-sm font-semibold",children:i===1?"year":"wonderful years"})]})}),a.jsxs(fr.h1,{className:`text-3xl font-bold ${k.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[E.title.join(" ")," ",E.emojis[4]]}),a.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[a.jsx("p",{className:`text-lg font-semibold ${k.text} mb-1`,children:r}),n&&a.jsxs("p",{className:`text-sm ${k.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[a.jsx(qs,{className:"h-3 w-3"}),n]})]}),_&&a.jsx(fr.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:a.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&a.jsx(fr.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:a.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),a.jsx(fr.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:a.jsxs("p",{className:`text-sm ${k.text} leading-relaxed italic`,children:['"',o||E.defaultMessage,'"']})}),a.jsxs(fr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[a.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[s?a.jsx(fr.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}}):a.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${k.header} flex items-center justify-center shadow-md`,children:a.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:`text-sm font-bold ${k.accent}`,children:c}),y&&a.jsx("p",{className:`text-xs ${k.text} opacity-60`,children:y})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&a.jsxs(fr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call"]}),p&&a.jsxs(fr.a,{href:`mailto:${p}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),a.jsx(fr.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 _R({delay:t,x:e,y:r,size:n,color:i}){return a.jsx(fr.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 N$({delay:t,x:e,y:r,size:n}){return a.jsx(fr.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 Sle={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 oPt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:_,videoUrl:T}=t,E=zC[e],k=Sle[e]||Sle.home_anniversary;return a.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[a.jsx(_R,{delay:0,x:"5%",y:"10%",size:300,color:k.mesh[0]}),a.jsx(_R,{delay:2,x:"60%",y:"50%",size:250,color:k.mesh[1]}),a.jsx(_R,{delay:4,x:"30%",y:"70%",size:200,color:k.mesh[2]}),a.jsx(_R,{delay:1,x:"80%",y:"15%",size:180,color:k.mesh[0]}),a.jsx(N$,{delay:0,x:"15%",y:"20%",size:100}),a.jsx(N$,{delay:3,x:"70%",y:"60%",size:140}),a.jsx(N$,{delay:6,x:"40%",y:"10%",size:80}),a.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")`}}),a.jsxs(fr.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:[a.jsxs(fr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${k.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[a.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:a.jsx(fr.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"}})}),a.jsxs("div",{className:"px-8 py-10 text-center",children:[a.jsxs(fr.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:[a.jsx(fr.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"}}),a.jsx(fr.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&&a.jsxs(fr.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:[a.jsx(fr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:i}),a.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${k.accent}`,children:i===1?"Year":"Years"})]}),a.jsx(fr.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]&&a.jsx(fr.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]}),a.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[a.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&a.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[a.jsx(qs,{className:"h-3 w-3"})," ",n]})]}),a.jsx(fr.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"}}),_&&a.jsx(fr.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:a.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&a.jsx(fr.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:a.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),a.jsx(fr.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:a.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',o||E.defaultMessage,'"']})}),a.jsxs(fr.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:[a.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?a.jsx(fr.img,{src:s,alt:c,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):a.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:a.jsx("span",{className:"text-sm font-semibold text-white/60",children:c.charAt(0)})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-sm font-semibold text-white/80",children:c}),y&&a.jsx("p",{className:"text-xs text-white/30",children:y})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&a.jsxs(fr.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call"]}),p&&a.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),a.jsx(fr.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 P$({delay:t,x:e,angle:r,color:n}){return a.jsx(fr.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 vR({delay:t,x:e}){return a.jsx(fr.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 Tle={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 lPt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:_,videoUrl:T}=t,E=zC[e],k=Tle[e]||Tle.home_anniversary;return a.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${k.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[a.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),a.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),a.jsx(P$,{delay:0,x:"20%",angle:15,color:k.stripe}),a.jsx(P$,{delay:2,x:"75%",angle:-12,color:k.stripe}),a.jsx(P$,{delay:4,x:"50%",angle:5,color:k.stripe}),a.jsx(vR,{delay:0,x:"30%"}),a.jsx(vR,{delay:1.5,x:"60%"}),a.jsx(vR,{delay:3,x:"45%"}),a.jsx(vR,{delay:.7,x:"75%"}),a.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")`}}),a.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[a.jsx(fr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:a.jsxs("div",{className:"px-8 py-12 text-center",children:[a.jsx(fr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:a.jsx(fr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${k.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:a.jsx("span",{className:"text-4xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&a.jsxs(fr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[a.jsx(fr.span,{className:`text-6xl font-black bg-gradient-to-r ${k.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:i}),a.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:i===1?"Year":"Years"})]}),a.jsx("div",{className:"overflow-hidden mb-2",children:a.jsx(fr.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]&&a.jsx("div",{className:"overflow-hidden mb-8",children:a.jsx(fr.h2,{className:`text-5xl font-black bg-gradient-to-r ${k.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]})}),a.jsxs(fr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[a.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&a.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[a.jsx(qs,{className:"h-3 w-3"})," ",n]})]}),a.jsxs(fr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[a.jsx(fr.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"}}),a.jsx(fr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),a.jsx(fr.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"}})]}),_&&a.jsxs(fr.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:[a.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),T&&a.jsx(fr.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:a.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),a.jsx(fr.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:o||E.defaultMessage}),a.jsxs(fr.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:[a.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[s?a.jsx(fr.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}}):a.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${k.accent} flex items-center justify-center shadow-xl`,children:a.jsx("span",{className:"text-sm font-bold text-slate-900",children:c.charAt(0)})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-sm font-medium text-white/70",children:c}),y&&a.jsx("p",{className:"text-[11px] text-white/25",children:y})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f&&a.jsxs(fr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call"]}),p&&a.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),a.jsx(fr.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 d2e(){const{shareToken:t}=bm(),{data:e,isLoading:r,error:n}=gr({queryKey:["public-sendable-card",t],queryFn:async()=>{const{data:c,error:s}=await Re.from("sendable_cards").select("*").eq("share_token",t).single();if(s)throw s;return c},enabled:!!t});if(I.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]),I.useEffect(()=>{t&&Re.rpc("log_sendable_card_view",{p_share_token:t}).then(({error:c})=>{c&&console.error("Error tracking view:",c)})},[t]),r)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:a.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[a.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),a.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!e)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),a.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()-Y1(e.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,o={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 a.jsx(iPt,{...o});case"warm":return a.jsx(aPt,{...o});case"glass":return a.jsx(oPt,{...o});case"cinematic":return a.jsx(lPt,{...o});case"elegant":default:return a.jsx(nPt,{...o})}}const cPt=Object.freeze(Object.defineProperty({__proto__:null,default:d2e},Symbol.toStringTag,{value:"Module"})),h2e=()=>{const t=Bi();return I.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]),a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),a.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),a.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function uPt(){return I.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),a.jsxs(l_,{children:[a.jsx(Te,{path:"/c/:shareToken",element:a.jsx(d2e,{})}),a.jsx(Te,{path:"*",element:a.jsx(h2e,{})})]})}function dPt(t,e){return e?t.find(r=>r.id===e)??null:null}const R$={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},hPt=["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 fPt(t,e,r){const[n,i,o]=t.split("-").map(Number),[c,s]=e.split(":").map(Number),f=Date.UTC(n,i-1,o,c,s),p=new Intl.DateTimeFormat("en-US",{timeZone:r,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),y=Object.fromEntries(p.formatToParts(new Date(f)).filter(T=>T.type!=="literal").map(T=>[T.type,T.value])),_=Date.UTC(Number(y.year),Number(y.month)-1,Number(y.day),Number(y.hour)%24,Number(y.minute));return f+(f-_)}function L$(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 f2e({slugOverride:t}){const e=bm(),r=t||e.slug,[n]=px(),i=n.get("type"),[o,c]=I.useState("types"),[s,f]=I.useState(null),[p,y]=I.useState(null),[_,T]=I.useState(null),[E,k]=I.useState(new Date),[P,R]=I.useState({name:"",email:"",phone:"",message:""}),[D,M]=I.useState(!1),[B,V]=I.useState(null),[G,W]=I.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:Z,isLoading:Q}=gr({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:ve,error:We}=await Re.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(We)throw We;return ve},enabled:!!r}),{data:re}=gr({queryKey:["public-booking-profile",Z==null?void 0:Z.user_id],queryFn:async()=>{const{data:ve,error:We}=await Re.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",Z.user_id).single();if(We)throw We;return ve},enabled:!!(Z!=null&&Z.user_id)}),{data:se=[]}=gr({queryKey:["public-booking-types",Z==null?void 0:Z.user_id],queryFn:async()=>{const{data:ve,error:We}=await Re.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",Z.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(We)throw We;return ve},enabled:!!(Z!=null&&Z.user_id)});I.useEffect(()=>{if(!i||s||se.length===0)return;const ve=dPt(se,i);ve&&(f(ve),c("date"))},[i,se,s]);const ue=Ni(E,"yyyy-MM"),{data:_e={},isFetching:we}=gr({queryKey:["public-availability-map",r,s==null?void 0:s.id,ue],enabled:!!r&&!!s,staleTime:6e4,queryFn:async()=>{const ve=new Date(E.getFullYear(),E.getMonth(),1),We=tx(new Date),rt=Bj(We,ve)?We:ve,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 Re.functions.invoke("agent-booking",{body:{action:"availability",slug:r,booking_type_id:s.id,start:Ni(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)||{}}}),Ce=ve=>{const We=tx(new Date),rt=Cl(We,(Z==null?void 0:Z.max_advance_days)||30);return L7(ve,We)||Bj(ve,rt)?!1:(_e[Ni(ve,"yyyy-MM-dd")]||[]).length>0},Me=I.useMemo(()=>p?_e[Ni(p,"yyyy-MM-dd")]||[]:[],[p,_e]),Ae=I.useMemo(()=>{const ve=E.getFullYear(),We=E.getMonth(),rt=new Date(ve,We,1),at=new Date(ve,We+1,0),Et=rt.getDay(),_t=[];for(let Vt=0;Vt{var ve,We;if(!(!s||!p||!_||!P.name||!Z)){M(!0);try{const rt=Ni(p,"yyyy-MM-dd"),{data:at,error:Et}=await Re.functions.invoke("agent-booking",{body:{action:"create",slug:r,booking_type_id:s.id,date:rt,time:_,guest_name:P.name,guest_email:P.email||null,guest_phone:P.phone||null,guest_message:P.message||null,guest_timezone:G}});if(Et){let pt=Et.message;try{const Nt=await((We=(ve=Et.context)==null?void 0:ve.json)==null?void 0:We.call(ve));Nt!=null&&Nt.error&&(pt=Nt.error)}catch{}throw new Error(pt)}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),Re.functions.invoke("booking-notify",{body:{agentUserId:Z.user_id,guestName:P.name,guestEmail:P.email||null,guestPhone:P.phone||null,guestMessage:P.message||null,bookingTypeName:s.name,bookingDate:rt,startTime:_,endTime:_t,durationMinutes:s.duration_minutes,meetingLink:Z.meeting_link||null,manageUrl:Vt}}).catch(pt=>console.error("Booking notify error:",pt)),c("confirmed")}catch(rt){Gt.error("Failed to book: "+rt.message)}finally{M(!1)}}},me=ve=>{const[We,rt]=ve.split(":").map(Number),at=We>=12?"PM":"AM";return`${We%12||12}:${rt.toString().padStart(2,"0")} ${at}`},Pe=(Z==null?void 0:Z.timezone)||"America/New_York",Ie=G!==Pe,Se=(ve,We)=>{if(!Ie)return me(We);try{return new Intl.DateTimeFormat("en-US",{timeZone:G,hour:"numeric",minute:"2-digit"}).format(new Date(fPt(ve,We,Pe)))}catch{return me(We)}};return Q?a.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),a.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):Z?a.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[a.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),a.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[a.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[a.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:a.jsxs("div",{className:"absolute inset-0 opacity-10",children:[a.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),a.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),a.jsx("div",{className:"relative -mt-10 px-6",children:a.jsxs("div",{className:"flex items-end gap-4",children:[re!=null&&re.avatar_url?a.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"}):a.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:a.jsx(vc,{className:"h-10 w-10 text-white"})}),a.jsxs("div",{className:"pb-1.5",children:[a.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)&&a.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:re.title})]})]})}),a.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(re==null?void 0:re.phone)&&a.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:[a.jsx(ai,{className:"h-3.5 w-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:re.phone}),a.jsx("span",{className:"sm:hidden",children:"Call"})]}),(re==null?void 0:re.email)&&a.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:[a.jsx(Ti,{className:"h-3.5 w-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:re.email}),a.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),a.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:a.jsxs("div",{className:"p-5 sm:p-6",children:[o==="types"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),a.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),a.jsx("div",{className:"space-y-2.5",children:se.map(ve=>a.jsx("button",{onClick:()=>{f(ve),c("date")},className:"w-full text-left group",children:a.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:ve.color},children:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[a.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:R$[ve.icon]||"📅"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:ve.name}),ve.description&&a.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:ve.description})]})]}),a.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:[a.jsx(Rl,{className:"h-3 w-3"}),ve.duration_minutes,"m"]})]})})},ve.id))})]}),o==="date"&&s&&a.jsxs("div",{className:"space-y-5",children:[a.jsxs("button",{onClick:()=>{c("types"),y(null),T(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[a.jsx(Yy,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),a.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:s.color+"40",backgroundColor:s.color+"08"},children:[a.jsx("span",{className:"text-xl",children:R$[s.icon]||"📅"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("p",{className:"font-semibold text-sm text-slate-800",children:s.name})}),a.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[a.jsx(Rl,{className:"h-3 w-3"}),s.duration_minutes," min"]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ni(E,"MMMM yyyy")}),a.jsxs("div",{className:"flex gap-1",children:[a.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:()=>k(new Date(E.getFullYear(),E.getMonth()-1)),children:a.jsx(xm,{className:"h-4 w-4"})}),a.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:()=>k(new Date(E.getFullYear(),E.getMonth()+1)),children:a.jsx(vd,{className:"h-4 w-4"})})]})]}),a.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(ve=>a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:ve},ve)),Ae.map((ve,We)=>{if(!ve)return a.jsx("div",{},`pad-${We}`);const rt=Ce(ve),at=p&&Jl(ve,p),Et=Jl(ve,new Date);return a.jsx("button",{disabled:!rt,onClick:()=>{y(ve),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:ve.getDate()},ve.toISOString())})]})]}),p&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(im,{className:"h-4 w-4 text-[#406E71]"}),a.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ni(p,"EEEE, MMMM d")})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[a.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),a.jsx("select",{value:G,onChange:ve=>W(ve.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([G,Pe,...hPt])).map(ve=>a.jsxs("option",{value:ve,children:[ve.replace(/_/g," ")," (",L$(ve),")"]},ve))})]}),we&&Me.length===0?a.jsxs("div",{className:"text-center py-8 space-y-2",children:[a.jsx(Ru,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),a.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):Me.length===0?a.jsxs("div",{className:"text-center py-8 space-y-2",children:[a.jsx(Rl,{className:"h-8 w-8 text-slate-300 mx-auto"}),a.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),a.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):a.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:Me.map(ve=>{const We=_===ve;return a.jsx("button",{onClick:()=>T(ve),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:Se(Ni(p,"yyyy-MM-dd"),ve)},ve)})}),_&&a.jsx(zt,{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"})]})]}),o==="form"&&s&&p&&_&&a.jsxs("div",{className:"space-y-5",children:[a.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:[a.jsx(Yy,{className:"h-3.5 w-3.5"})," Back"]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-lg",children:R$[s.icon]||"📅"}),a.jsx("p",{className:"font-semibold text-sm text-slate-800",children:s.name})]}),a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(im,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ni(p,"EEE, MMM d, yyyy")]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Rl,{className:"h-3.5 w-3.5 text-[#406E71]"}),Se(Ni(p,"yyyy-MM-dd"),_)," (",L$(G),") · ",s.duration_minutes," min"]})]})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),a.jsx($r,{value:P.name,onChange:ve=>R({...P,name:ve.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Email"}),a.jsxs("div",{className:"relative",children:[a.jsx(Ti,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),a.jsx($r,{type:"email",value:P.email,onChange:ve=>R({...P,email:ve.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),a.jsxs("div",{className:"relative",children:[a.jsx(ai,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),a.jsx($r,{type:"tel",value:P.phone,onChange:ve=>R({...P,phone:ve.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),a.jsx(bd,{value:P.message,onChange:ve=>R({...P,message:ve.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"})]})]}),a.jsx(zt,{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:be,disabled:!P.name||D,children:D?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),o==="confirmed"&&a.jsxs("div",{className:"text-center space-y-5 py-6",children:[a.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[a.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),a.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:a.jsx(ic,{className:"h-10 w-10 text-white"})})]}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),a.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"]})]}),a.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:a.jsxs("div",{className:"text-left text-sm",children:[a.jsx("p",{className:"font-semibold text-slate-800",children:p&&Ni(p,"EEEE, MMMM d, yyyy")}),a.jsxs("p",{className:"text-slate-500",children:[p&&_?`${Se(Ni(p,"yyyy-MM-dd"),_)} (${L$(G)})`:""," · ",s==null?void 0:s.duration_minutes," min"]})]})}),a.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&&a.jsx("div",{className:"pt-1",children:a.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))&&a.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[a.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),a.jsxs("div",{className:"flex gap-3",children:[(re==null?void 0:re.phone)&&a.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," Call"]}),(re==null?void 0:re.email)&&a.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:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),a.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):a.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:a.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[a.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:a.jsx(im,{className:"h-8 w-8 text-slate-400"})}),a.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),a.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}const mPt=Object.freeze(Object.defineProperty({__proto__:null,default:f2e},Symbol.toStringTag,{value:"Module"}));function pPt(){const e=Bi().pathname.slice(1).split("/")[0];return I.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(o=>{document.querySelectorAll(o).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?a.jsx(f2e,{slugOverride:e}):a.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:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),a.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}const gPt="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",yPt="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",xPt="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",_Pt="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",vPt="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",bPt="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",D$={"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:bPt},"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:gPt},"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:yPt},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:xPt},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:_Pt},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:vPt}},E9t=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function wPt(t){return t&&t in D$?D$[t]:D$["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 m2e({slugOverride:t}={}){var _o;const{slug:e}=bm(),r=t||e,[n]=px(),i=n.get("t"),[o,c]=I.useState(!0),[s,f]=I.useState(null),[p,y]=I.useState(null),_=I.useRef(null),T=I.useRef(null),[E,k]=I.useState(null),[P,R]=I.useState(null),[D,M]=I.useState(!1),[B,V]=I.useState(!1),[G,W]=I.useState(0),[Z,Q]=I.useState(!1),[re,se]=I.useState(""),[ue,_e]=I.useState(""),[we,Ce]=I.useState(""),[Me,Ae]=I.useState(""),[be,me]=I.useState(""),[Pe,Ie]=I.useState(""),[Se,ve]=I.useState(""),[We,rt]=I.useState(""),[at,Et]=I.useState(""),[_t,Vt]=I.useState(""),[pt,Nt]=I.useState(""),[er,vt]=I.useState(""),[or,Sr]=I.useState(""),[nn,cr]=I.useState([]),[xr,tr]=I.useState([]),[_n,lt]=I.useState(""),[At,Mt]=I.useState(""),[dr,ur]=I.useState(""),[hr,Xt]=I.useState([]);I.useEffect(()=>{Pr()},[r,i]);const Pr=async()=>{if(!r)return;c(!0);const{data:Yr,error:hn}=await Re.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(hn||!Yr){Q(!0),c(!1);return}y(Yr),T.current=Yr;const{data:xn}=await Re.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Yr.user_id).single();if(xn){let Zr;if(xn.brokerage_id){const{data:Bn}=await Re.from("brokerages").select("name").eq("id",xn.brokerage_id).single();Zr=(Bn==null?void 0:Bn.name)||void 0}let ui=xn.avatar_url||null;if(!ui){const{data:Bn}=Re.storage.from("avatars").getPublicUrl(`${Yr.user_id}/avatar.jpg`);Bn!=null&&Bn.publicUrl&&(ui=`${Bn.publicUrl}?t=${Date.now()}`)}const Jr={...xn,avatar_url:ui,brokerage_name:Zr};f(Jr),_.current=Jr}if(i)try{console.log("[ConnectPage] Resolving token:",i,"for page:",Yr.id);const{data:Zr,error:ui}=await Re.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:i,page_id:Yr.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Zr,resolveErr:ui}),!ui&&(Zr!=null&&Zr.contact_id)){R(Zr.contact_id);const Jr=Zr.contact;Jr&&(k(Jr),se(Jr.first_name||""),_e(Jr.last_name||""),Ce(Jr.email||""),Ae(Jr.phone||""),me(Jr.address||""),Ie(Jr.city||""),ve(Jr.state||""),rt(Jr.zip||""),Et(Jr.birthday||""),Vt(Jr.home_anniversary||""))}}catch(Zr){console.error("Failed to resolve token:",Zr)}c(!1)},Rn=async()=>{var Yr,hn;if(!re.trim()){Gt.error("Please enter your first name");return}if(!r){Gt.error("Invalid page. Please refresh.");return}V(!0);try{let xn=(Yr=T.current)==null?void 0:Yr.id,Zr=(hn=T.current)==null?void 0:hn.user_id;if(!xn||!Zr){const{data:Bn}=await Re.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!Bn){Gt.error("This page is no longer active. Please contact the agent directly."),V(!1);return}xn=Bn.id,Zr=Bn.user_id}const ui={intake_page_id:xn,agent_user_id:Zr,existing_contact_id:P,first_name:re.trim(),last_name:ue.trim()||null,email:we.trim()||null,phone:Me.trim()||null,address:be.trim()||null,city:Pe.trim()||null,state:Se.trim()||null,zip:We.trim()||null,birthday:at||null,home_anniversary:_t||null,real_estate_interest:pt||null,message:er.trim()||null,life_events:{spouse_name:or.trim()||null,kids:nn.filter(Bn=>Bn.name.trim()),pets:xr.filter(Bn=>Bn.name.trim()),favorite_spots:_n.trim()||null,dream_neighborhood:At.trim()||null,wedding_anniversary:dr||null},referrals:hr.filter(Bn=>Bn.name.trim()&&Bn.contact.trim())},{error:Jr}=await Re.from("contact_intake_submissions").insert(ui);if(console.log("[ConnectPage] Insert result:",{error:Jr}),Jr)throw Jr;i&&await Re.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",i);try{const Bn=[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:Bn,contactEmail:we.trim()||null,contactPhone:Me.trim()||null,slug:r})})}catch(Bn){console.warn("Connect page notification failed (non-blocking):",Bn)}M(!0)}catch(xn){console.error(xn),Gt.error("Something went wrong. Please try again.")}finally{V(!1)}};if(o)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:a.jsx(Ru,{className:"h-8 w-8 animate-spin text-slate-400"})});if(Z)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),a.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(D)return a.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:[a.jsx(Wo,{children:a.jsxs("title",{children:["Thank You | ",s==null?void 0:s.name]})}),a.jsxs(fr.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:[a.jsx(fr.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:a.jsx(ic,{className:"h-10 w-10 text-emerald-600"})}),a.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),a.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."]}),a.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[a.jsx(um,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ci=!!i&&!!E,ti=(p==null?void 0:p.show_little_things)??!0,zi=[{title:ci?"Confirm Your Info":"Let's Get Connected",fields:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),a.jsx("input",{type:"text",value:re,onChange:Yr=>se(Yr.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),a.jsx("input",{type:"text",value:ue,onChange:Yr=>_e(Yr.target.value),placeholder:"Smith",className:"connect-input"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),a.jsx("input",{type:"email",value:we,onChange:Yr=>Ce(Yr.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),a.jsx("input",{type:"tel",value:Me,onChange:Yr=>Ae(Yr.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),a.jsx("input",{type:"text",value:be,onChange:Yr=>me(Yr.target.value),placeholder:"123 Main St",className:"connect-input"})]}),a.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[a.jsxs("div",{className:"col-span-2",children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),a.jsx("input",{type:"text",value:Pe,onChange:Yr=>Ie(Yr.target.value),placeholder:"Austin",className:"connect-input"})]}),a.jsxs("div",{className:"col-span-1",children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),a.jsx("input",{type:"text",value:Se,onChange:Yr=>ve(Yr.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),a.jsxs("div",{className:"col-span-2",children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),a.jsx("input",{type:"text",value:We,onChange:Yr=>rt(Yr.target.value),placeholder:"78701",className:"connect-input"})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),a.jsx("input",{type:"date",value:at,onChange:Yr=>Et(Yr.target.value),className:"connect-input"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),a.jsx("input",{type:"date",value:_t,onChange:Yr=>Vt(Yr.target.value),className:"connect-input"})]})]})]})},...ti?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:a.jsxs("div",{className:"space-y-5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),a.jsx("input",{type:"text",value:or,onChange:Yr=>Sr(Yr.target.value),placeholder:"Alex",className:"connect-input"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),a.jsx("input",{type:"date",value:dr,onChange:Yr=>ur(Yr.target.value),className:"connect-input"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[a.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),a.jsxs("button",{type:"button",onClick:()=>cr(Yr=>[...Yr,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[a.jsx(sm,{className:"h-3 w-3"})," Add"]})]}),a.jsxs("div",{className:"space-y-2",children:[nn.length===0&&a.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),nn.map((Yr,hn)=>a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("input",{type:"text",value:Yr.name,onChange:xn=>cr(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,name:xn.target.value}:ui)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),a.jsx("input",{type:"text",value:Yr.age,onChange:xn=>cr(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,age:xn.target.value}:ui)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),a.jsx("button",{type:"button",onClick:()=>cr(xn=>xn.filter((Zr,ui)=>ui!==hn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:a.jsx(Ds,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[a.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),a.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:[a.jsx(sm,{className:"h-3 w-3"})," Add"]})]}),a.jsxs("div",{className:"space-y-2",children:[xr.length===0&&a.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),xr.map((Yr,hn)=>a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("input",{type:"text",value:Yr.name,onChange:xn=>tr(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,name:xn.target.value}:ui)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),a.jsx("input",{type:"text",value:Yr.kind,onChange:xn=>tr(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,kind:xn.target.value}:ui)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),a.jsx("button",{type:"button",onClick:()=>tr(xn=>xn.filter((Zr,ui)=>ui!==hn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:a.jsx(Ds,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),a.jsx("input",{type:"text",value:_n,onChange:Yr=>lt(Yr.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),a.jsx("input",{type:"text",value:At,onChange:Yr=>Mt(Yr.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),a.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),a.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),hr.length<3&&a.jsxs("button",{type:"button",onClick:()=>Xt(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:[a.jsx(sm,{className:"h-3 w-3"})," Add"]})]}),a.jsx("div",{className:"space-y-2",children:hr.map((Yr,hn)=>a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("input",{type:"text",value:Yr.name,onChange:xn=>Xt(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,name:xn.target.value}:ui)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),a.jsx("input",{type:"text",value:Yr.contact,onChange:xn=>Xt(Zr=>Zr.map((ui,Jr)=>Jr===hn?{...ui,contact:xn.target.value}:ui)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),a.jsx("button",{type:"button",onClick:()=>Xt(xn=>xn.filter((Zr,ui)=>ui!==hn)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:a.jsx(Ds,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))})]})]})}]:[],{title:"One Last Thing",fields:a.jsxs("div",{className:"space-y-5",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",a.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),a.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=>a.jsxs("button",{type:"button",onClick:()=>Nt(pt===Yr.value?"":Yr.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${pt===Yr.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[a.jsx("span",{className:"block text-sm font-medium text-slate-800",children:Yr.label}),a.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Yr.desc})]},Yr.value))})]}),a.jsxs("div",{children:[a.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? ",a.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),a.jsx("textarea",{value:er,onChange:Yr=>vt(Yr.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],wa=zi.length,xi=wPt(p==null?void 0:p.theme),la=SPt(xi,(p==null?void 0:p.accent_color)||null),Cr=(p==null?void 0:p.cover_image_url)||xi.defaultCover,Fn=(p==null?void 0:p.headline)||"Let's stay connected",As=(p==null?void 0:p.subheadline)||(s!=null&&s.brokerage_name?`${s==null?void 0:s.name} · ${s.brokerage_name}`:(s==null?void 0:s.name)||""),Sa=["deep-luxe"].includes((p==null?void 0:p.theme)||"");return a.jsxs("div",{className:"min-h-screen connect-shell",style:la,children:[a.jsxs(Wo,{children:[a.jsxs("title",{children:["Connect with ",(s==null?void 0:s.name)||"Agent"]}),a.jsx("meta",{name:"description",content:`${Fn} — ${(s==null?void 0:s.name)||"your agent"}`}),Cr&&a.jsx("meta",{property:"og:image",content:Cr}),a.jsx("meta",{property:"og:title",content:`Connect with ${(s==null?void 0:s.name)||"me"}`}),a.jsx("meta",{property:"og:description",content:Fn}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),a.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); } `}),a.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[a.jsx(fr.img,{src:Cr,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),a.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),a.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[a.jsx(fr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:xi.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Fn}),As&&a.jsx(fr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:As})]})]}),a.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[a.jsxs(fr.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?a.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)"}}):a.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:xi.accent,color:xi.accentText,border:"4px solid var(--c-surface)"},children:a.jsx("span",{className:"text-3xl font-bold",children:((_o=s==null?void 0:s.name)==null?void 0:_o.charAt(0))||"?"})}),(s==null?void 0:s.title)&&a.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))&&a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(s==null?void 0:s.phone)&&a.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:a.jsx(ai,{className:"h-4 w-4"})}),(s==null?void 0:s.email)&&a.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:a.jsx(Ti,{className:"h-4 w-4"})})]})]}),a.jsx(fr.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:(p==null?void 0:p.welcome_message)||"I'd love to stay in touch — just a few quick details."}),a.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:wa}).map((Yr,hn)=>a.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))}),a.jsxs(fr.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:Sa?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[a.jsx(twe,{mode:"wait",children:a.jsxs(fr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xs,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),a.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:zi[G].title})]}),zi[G].subtitle&&a.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:zi[G].subtitle})]}),zi[G].fields]},G)}),a.jsxs("div",{className:"flex justify-between mt-8",children:[G>0?a.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"}):a.jsx("div",{}),G{if(G===0&&!re.trim()){Gt.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"}):a.jsx("button",{type:"button",onClick:()=>Rn(),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?a.jsxs(a.Fragment,{children:[a.jsx(Ru,{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"})})]}),a.jsx("div",{className:"text-center mt-8",children:a.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[a.jsx(um,{className:"h-3 w-3"}),a.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const TPt=Object.freeze(Object.defineProperty({__proto__:null,default:m2e},Symbol.toStringTag,{value:"Module"}));function EPt(){const e=Bi().pathname.slice(1);return I.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(o=>{document.querySelectorAll(o).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===""?a.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:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),a.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),a.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):a.jsx(m2e,{slugOverride:e})}function APt(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 o=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(o[(f*r+s)*4+3]<250)return!0;return!1}catch{return!0}}const jPt={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function kPt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:o,renderField:c}){const s=t.accent_color||"#E8B84A",f=t.primary_color||"#0F1B3D",p=jPt[t.heading_font||"playfair"],y=t.eyebrow||null,_=t.headline_accent||null,T=Array.isArray(t.trust_pills)?t.trust_pills:[],E=e,k=E.length>5;return a.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:f},children:[t.hero_image_url?a.jsx("img",{src:t.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):a.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${f}, #000)`}}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),a.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:a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[a.jsxs("div",{className:"lg:col-span-3 text-white",children:[t.logo_url&&a.jsx(CPt,{src:t.logo_url}),y&&a.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:y}),a.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:p,letterSpacing:"-0.015em"},children:[t.hero_headline,_&&a.jsxs(a.Fragment,{children:[" ",a.jsx("span",{style:{color:s,fontStyle:"italic"},children:_})]})]}),t.hero_subtext&&a.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:t.hero_subtext}),t.agent_name&&a.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[t.agent_photo_url&&a.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"}),a.jsxs("div",{className:"text-white/90",children:[a.jsx("p",{className:"font-semibold text-sm",children:t.agent_name}),a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[t.agent_phone&&a.jsxs("a",{href:`tel:${t.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[a.jsx(ai,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&a.jsxs("a",{href:`mailto:${t.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[a.jsx(Ti,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]}),a.jsx("div",{className:"lg:col-span-2",children:a.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[a.jsxs("form",{className:"space-y-3",onSubmit:i,children:[a.jsx("div",{className:k?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:E.map(P=>a.jsxs("div",{children:[a.jsxs(Mr,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[P.label,P.is_required&&a.jsx("span",{className:"ml-1",style:{color:s},children:"*"})]}),a.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900 [&_span]:text-white/90 [&_button[role=checkbox]]:border-white/60 [&_button[role=checkbox]]:bg-white/20 [&_button[role=checkbox][data-state=checked]]:bg-white [&_button[role=checkbox][data-state=checked]]:text-neutral-900",children:c(P,r,n,f)})]},P.id))}),a.jsx("button",{type:"submit",disabled:o,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:o?"Submitting...":t.cta_text||"Get Started"})]}),T.length>0&&a.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:T.map((P,R)=>a.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[a.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:s}}),P]},R))})]})})]})})]})}function CPt({src:t}){const[e,r]=I.useState(null),n=a.jsx("img",{src:t,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:i=>r(APt(i.currentTarget)),onError:()=>r(!0)});return e===!1?a.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):a.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}const Ele={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function IPt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:o,renderField:c,activePath:s,setActivePath:f}){const p=I.useRef(null),[y,_]=I.useState(!1),T=t.primary_color||"#406E71",E=t.accent_color||"#2a4c64",k=t.settings||{},P=Ele[t.heading_font]||Ele.playfair,R=Array.isArray(t.trust_pills)?t.trust_pills:[],D={buyerLabel:k.buyer_button_label||"I'm a Buyer",buyerSub:k.buyer_button_subtext||"Find the right home, at the right price",sellerLabel:k.seller_button_label||"I'm a Seller",sellerSub:k.seller_button_subtext||"Get a free, no-obligation home evaluation",buyerTitle:k.buyer_form_title||"Tell me what you’re looking for",buyerSubtitle:k.buyer_form_subtext||"A few quick questions and I’ll send you matching homes.",sellerTitle:k.seller_form_title||"Get your free home evaluation",sellerSubtitle:k.seller_form_subtext||"Tell me about your home and I’ll prepare your value report.",buyerCta:k.buyer_submit_label||"Send me homes",sellerCta:k.seller_submit_label||"Get my home value"},M=I.useMemo(()=>{const W=e.filter(re=>(re.field_group||"default")==="buyer"),Z=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:Z.length?[...Q,...Z]:[...Q]}},[e]),B=s?M[s]:[];I.useEffect(()=>{s&&p.current&&p.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 a.jsxs("div",{className:"min-h-screen bg-neutral-950",children:[a.jsxs("section",{className:"relative min-h-[78vh] flex items-center overflow-hidden",children:[a.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})`}}),a.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%)"}}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40",style:{background:"linear-gradient(180deg, transparent, #0a0a0a)"}}),a.jsxs("div",{className:"relative w-full max-w-6xl mx-auto px-5 py-20 text-center",children:[t.logo_url&&a.jsx("img",{src:t.logo_url,alt:"",className:"h-11 w-auto mx-auto mb-8 drop-shadow-lg"}),t.eyebrow&&a.jsx("p",{className:"text-[11px] md:text-xs uppercase tracking-[0.32em] text-white/70 mb-5",children:t.eyebrow}),a.jsxs("h1",{className:"text-white text-4xl md:text-6xl lg:text-7xl leading-[1.05] tracking-tight",style:{fontFamily:P},children:[t.hero_headline,t.headline_accent&&a.jsxs(a.Fragment,{children:[" ",a.jsx("em",{className:"italic",style:{color:"#fff",opacity:.85},children:t.headline_accent})]})]}),t.hero_subtext&&a.jsx("p",{className:"mt-5 text-base md:text-lg text-white/80 max-w-2xl mx-auto leading-relaxed",children:t.hero_subtext}),a.jsxs("div",{className:"mt-12 grid gap-4 sm:grid-cols-2 max-w-3xl mx-auto",children:[a.jsx(Ale,{active:s==="buyer",icon:a.jsx(Mfe,{className:"h-5 w-5"}),label:D.buyerLabel,sub:D.buyerSub,color:T,onClick:()=>{_(!1),f("buyer")}}),a.jsx(Ale,{active:s==="seller",icon:a.jsx(La,{className:"h-5 w-5"}),label:D.sellerLabel,sub:D.sellerSub,color:E,onClick:()=>{_(!1),f("seller")}})]}),R.length>0&&a.jsx("div",{className:"mt-9 flex flex-wrap items-center justify-center gap-2",children:R.map(W=>a.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:[a.jsx(a9,{className:"h-3 w-3"})," ",W]},W))})]})]}),a.jsx("section",{ref:p,className:"relative bg-neutral-950 px-5 pb-20 pt-2 scroll-mt-4",children:a.jsxs("div",{className:"max-w-3xl mx-auto",children:[s?a.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:[a.jsxs("div",{className:"px-6 md:px-9 py-6",style:{background:`linear-gradient(120deg, ${s==="buyer"?T:E}, ${s==="buyer"?E:T})`},children:[a.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:[a.jsx(Yy,{className:"h-3 w-3"})," Change"]}),a.jsx("h2",{className:"mt-3 text-2xl md:text-3xl text-white leading-tight",style:{fontFamily:P},children:s==="buyer"?D.buyerTitle:D.sellerTitle}),a.jsx("p",{className:"mt-1.5 text-sm text-white/80",children:s==="buyer"?D.buyerSubtitle:D.sellerSubtitle})]}),a.jsxs("form",{onSubmit:G,className:"px-6 md:px-9 py-7 space-y-4",children:[B.length===0&&a.jsx("p",{className:"text-sm text-neutral-500",children:"This form has no questions yet."}),B.map(W=>a.jsxs("div",{children:[a.jsxs(Mr,{className:"text-[13px] font-medium text-neutral-700",children:[W.label,W.is_required&&a.jsx("span",{className:"ml-1",style:{color:T},children:"*"})]}),c(W,r,n,T)]},W.id)),y&&V.length>0&&a.jsxs("p",{className:"text-sm text-red-600",children:["Please fill in: ",V.map(W=>W.label).join(", ")]}),a.jsxs(zt,{type:"submit",disabled:o,className:"w-full h-12 text-white text-base rounded-xl shadow-lg hover:opacity-95",style:{backgroundColor:s==="buyer"?T:E},children:[o?"Sending…":s==="buyer"?D.buyerCta:D.sellerCta,!o&&a.jsx(ra,{className:"h-4 w-4 ml-2"})]})]})]}):a.jsx("p",{className:"text-center text-white/45 text-sm py-10",children:"Choose an option above to get started."}),t.agent_name&&a.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&&a.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"}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-white font-medium",children:t.agent_name}),a.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/65",children:[t.agent_phone&&a.jsxs("a",{href:`tel:${t.agent_phone}`,className:"inline-flex items-center gap-1 hover:text-white",children:[a.jsx(ai,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&a.jsxs("a",{href:`mailto:${t.agent_email}`,className:"inline-flex items-center gap-1 hover:text-white",children:[a.jsx(Ti,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]})})]})}function Ale({active:t,icon:e,label:r,sub:n,color:i,onClick:o}){return a.jsxs("button",{type:"button",onClick:o,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:[a.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}),a.jsx("span",{className:`mt-4 block text-xl font-semibold ${t?"":"text-white"}`,style:t?{color:i}:void 0,children:r}),a.jsx("span",{className:`mt-1 block text-sm ${t?"text-neutral-600":"text-white/70"}`,children:n}),a.jsx(ra,{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 NPt(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),o=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",`${o(n)}/${o(i)}`),r&&c.searchParams.set("location",r),c.toString()}function RPt(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),o=s=>s.toISOString().replace(/[-:]|\.\d{3}/g,""),c=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${o(new Date)}`,`DTSTART:${o(n)}`,`DTEND:${o(i)}`,`SUMMARY:${t}`,r?`LOCATION:${r}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(c)}`}function LPt({startsAt:t,locationName:e,address:r,title:n,accent:i}){const[o,c]=I.useState(Date.now());I.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=NPt(s-o),p=s-o<=0,y=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 a.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:a.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:a.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:i},children:p?"Just happened":"Event starts in"}),p?a.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."}):a.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=>a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:i},children:String(E.v).padStart(2,"0")}),a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:E.l})]},E.l))}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.jsx(Rl,{className:"h-3.5 w-3.5"})," ",y]}),_&&a.jsxs("a",{href:T||"#",target:T?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[a.jsx(qs,{className:"h-3.5 w-3.5"})," ",_]})]})]}),!p&&a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.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:[a.jsx(yo,{className:"h-4 w-4"})," Add to Google"]}),a.jsxs("a",{href:RPt(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:[a.jsx(yo,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function DPt(){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 p2e({slugOverride:t}){var we;const{slug:e}=bm(),r=t||e,[n,i]=I.useState(!1),[o,c]=I.useState({}),[s,f]=I.useState(null),[p,y]=I.useState(0),[_,T]=I.useState(!1),[E,k]=I.useState(""),[P]=I.useState(()=>Date.now()),R=I.useState(()=>DPt())[0],{data:D,isLoading:M}=gr({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:Ce,error:Me}=await Re.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(Me)throw Me;return Ce},enabled:!!r}),{data:B=[]}=gr({queryKey:["public-landing-page-fields",D==null?void 0:D.id],queryFn:async()=>{const{data:Ce,error:Me}=await Re.from("landing_page_fields").select("*").eq("page_id",D.id).order("sort_order");if(Me)throw Me;return Ce},enabled:!!(D!=null&&D.id)});I.useEffect(()=>{D!=null&&D.id&&Re.from("landing_pages").update({view_count:(D.view_count||0)+1}).eq("id",D.id).then(()=>{})},[D==null?void 0:D.id]),I.useEffect(()=>{if(!(D!=null&&D.id))return;const Ce=new URLSearchParams(window.location.search);Re.functions.invoke("landing-page-track",{body:{page_id:D.id,event_type:"view",session_id:R,utm_source:Ce.get("utm_source"),utm_medium:Ce.get("utm_medium"),utm_campaign:Ce.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=kr({mutationFn:async()=>{const Ce=B.find(We=>We.field_type==="text"&&We.label.toLowerCase().includes("name")),Me=B.find(We=>We.field_type==="email"),Ae=B.find(We=>We.field_type==="phone"),be=Ce?String(o[Ce.label]||""):null,me=Me?String(o[Me.label]||""):null,Pe=Ae?String(o[Ae.label]||""):null,Ie=new URLSearchParams(window.location.search),{data:Se,error:ve}=await Re.functions.invoke("landing-page-submit",{body:{page_id:D.id,answers:JSON.parse(JSON.stringify(s?{"I am a":s==="buyer"?"Buyer":"Seller",...o}:o)),contact_name:be,contact_email:me,contact_phone:Pe,session_id:R,honeypot:E,rendered_at:P,utm_source:Ie.get("utm_source"),utm_medium:Ie.get("utm_medium"),utm_campaign:Ie.get("utm_campaign"),referrer:document.referrer||null}});if(ve)throw ve;return Se},onSuccess:Ce=>{i(!0),Ce!=null&&Ce.redirect_url&&setTimeout(()=>{window.location.href=Ce.redirect_url},1500)}}),G=Ce=>{Ce.preventDefault(),!((D==null?void 0:D.page_type)!=="buyer_seller"&&B.filter(Ae=>Ae.is_required&&!o[Ae.label]).length>0)&&V.mutate()};if(M)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!D)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),a.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",Z=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 a.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${W}, ${Z})`},children:a.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[a.jsx(ic,{className:"h-16 w-16 mx-auto mb-4",style:{color:W}}),a.jsx("h2",{className:"text-2xl font-bold mb-2",children:re?"Your download is ready!":"Submitted!"}),a.jsx("p",{className:"text-gray-600",children:D.success_message}),re&&_e&&a.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:[a.jsx(rc,{className:"h-5 w-5"}),"Download ",Q.lead_magnet_file_name||"Your File"]}),D.agent_name&&a.jsxs("div",{className:"mt-6 pt-4 border-t",children:[a.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),a.jsx("p",{className:"font-semibold",children:D.agent_name}),D.agent_phone&&a.jsxs("a",{href:`tel:${D.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[a.jsx(ai,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&a.jsxs("a",{href:`mailto:${D.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[a.jsx(Ti,{className:"h-3 w-3"})," ",D.agent_email]})]})]})});if(se){const Ce=Me=>{const Ae=parseFloat(Me.replace(/[^0-9.]/g,""));return isNaN(Ae)?Me:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ae)};return a.jsxs("div",{className:"min-h-screen bg-gray-50",children:[_&&ue.length>0&&a.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>T(!1),children:[a.jsx("button",{onClick:()=>T(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:a.jsx(Ds,{className:"h-8 w-8"})}),a.jsx("button",{onClick:Me=>{Me.stopPropagation(),y(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:a.jsx(xm,{className:"h-6 w-6"})}),a.jsx("img",{src:ue[p],alt:`Property photo ${p+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Me=>Me.stopPropagation()}),a.jsx("button",{onClick:Me=>{Me.stopPropagation(),y(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:a.jsx(vd,{className:"h-6 w-6"})}),a.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[p+1," / ",ue.length]})]}),ue.length>0&&a.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[a.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?a.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{y(0),T(!0)},children:[a.jsx("img",{src:ue[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),a.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:[a.jsx(vee,{className:"h-4 w-4"})," View"]})]}):ue.length===2?a.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:ue.slice(0,2).map((Me,Ae)=>a.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{y(Ae),T(!0)},children:a.jsx("img",{src:Me,alt:`Property ${Ae+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Ae))}):a.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[a.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{y(0),T(!0)},children:a.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((Me,Ae)=>a.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{y(Ae+1),T(!0)},children:[a.jsx("img",{src:Me,alt:`Property ${Ae+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Ae===3&&ue.length>5&&a.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&&a.jsxs("button",{onClick:()=>{y(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:[a.jsx(vee,{className:"h-4 w-4"})," View all ",ue.length," photos"]})]}),ue.length===0&&a.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}, ${Z})`},children:a.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&a.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),a.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&a.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext})]})}),a.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:a.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[a.jsx("div",{className:"md:col-span-3 space-y-6",children:a.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[Q.property_price&&a.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:W},children:Ce(Q.property_price)}),Q.property_address&&a.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[a.jsx(qs,{className:"h-5 w-5 shrink-0"})," ",Q.property_address]}),a.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[Q.property_beds&&a.jsxs("div",{className:"text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[a.jsx(CS,{className:"h-5 w-5",style:{color:W}})," ",Q.property_beds]}),a.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),Q.property_baths&&a.jsxs("div",{className:"text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[a.jsx(nv,{className:"h-5 w-5",style:{color:W}})," ",Q.property_baths]}),a.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),Q.property_sqft&&a.jsxs("div",{className:"text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[a.jsx(RO,{className:"h-5 w-5",style:{color:W}})," ",Number(Q.property_sqft).toLocaleString()]}),a.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),Q.property_description&&a.jsxs("div",{children:[a.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),a.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:Q.property_description})]})]})}),a.jsx("div",{className:"md:col-span-2",children:a.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[a.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?"}),a.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),D.agent_name&&a.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[D.agent_photo_url&&a.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-semibold text-sm",children:D.agent_name}),a.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[D.agent_phone&&a.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[a.jsx(ai,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&a.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[a.jsx(Ti,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),a.jsxs("form",{onSubmit:G,className:"space-y-3",children:[B.map(Me=>a.jsxs("div",{children:[a.jsxs(Mr,{className:"text-xs font-medium",children:[Me.label,Me.is_required&&a.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),bR(Me,o,c)]},Me.id)),a.jsx(zt,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:V.isPending,children:V.isPending?"Submitting...":"Submit"}),V.isError&&a.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),a.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return D.page_type==="buyer_seller"?a.jsxs(a.Fragment,{children:[a.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:Ce=>k(Ce.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),a.jsx(IPt,{page:D,fields:B,answers:o,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:bR,activePath:s,setActivePath:f}),V.isError&&a.jsx("p",{className:"text-center text-sm text-red-500 pb-8 bg-neutral-950",children:"Something went wrong. Please try again."}),a.jsx("div",{className:"text-center py-6 text-xs text-white/30 bg-neutral-950",children:"Powered by LevelUp"})]}):D.theme_style!=="classic"&&!re?a.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[a.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:Ce=>k(Ce.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),a.jsx(kPt,{page:D,fields:B,answers:o,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:bR}),D.page_type==="event_registration"&&((we=D.settings)==null?void 0:we.event_starts_at)&&a.jsx(LPt,{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&&a.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),a.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):a.jsxs("div",{className:"min-h-screen bg-gray-50",children:[a.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}, ${Z})`},children:a.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&a.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),a.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&a.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext}),re&&Q.lead_magnet_file_name&&a.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:[a.jsx(rc,{className:"h-4 w-4"}),"Free Download: ",Q.lead_magnet_file_name]})]})}),a.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:a.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[re&&a.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&&a.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[D.agent_photo_url&&a.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-semibold",children:D.agent_name}),a.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[D.agent_phone&&a.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[a.jsx(ai,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&a.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[a.jsx(Ti,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),a.jsxs("form",{onSubmit:G,className:"space-y-4",children:[B.map(Ce=>a.jsxs("div",{children:[a.jsxs(Mr,{className:"text-sm font-medium",children:[Ce.label,Ce.is_required&&a.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),bR(Ce,o,c)]},Ce.id)),a.jsx(zt,{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&&a.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),a.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function bR(t,e,r,n){const i=e[t.label]||"",o=Array.isArray(t.options)?t.options:[];switch(t.field_type){case"text":case"email":case"phone":return a.jsx($r,{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 a.jsx(bd,{value:String(i),onChange:c=>r(s=>({...s,[t.label]:c.target.value})),placeholder:t.placeholder||"",rows:3,className:"mt-1"});case"select":return a.jsxs(_a,{value:String(i),onValueChange:c=>r(s=>({...s,[t.label]:c})),children:[a.jsx(aa,{className:"mt-1",children:a.jsx(va,{placeholder:"Select..."})}),a.jsx(oa,{children:o.map(c=>a.jsx(fn,{value:c,children:c},c))})]});case"multiselect":return a.jsx("div",{className:"mt-1 space-y-2",children:o.map(c=>{const s=Array.isArray(i)?i:[];return a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx(wC,{checked:s.includes(c),onCheckedChange:f=>{const p=f?[...s,c]:s.filter(y=>y!==c);r(y=>({...y,[t.label]:p}))}}),a.jsx("span",{className:"text-sm",children:c})]},c)})});case"toggle":return a.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[a.jsx(YS,{checked:!!i,onCheckedChange:c=>r(s=>({...s,[t.label]:c?"Yes":"No"}))}),a.jsx("span",{className:"text-sm text-gray-600",children:i?"Yes":"No"})]});default:return a.jsx($r,{value:String(i),onChange:c=>r(s=>({...s,[t.label]:c.target.value})),className:"mt-1"})}}const MPt=Object.freeze(Object.defineProperty({__proto__:null,default:p2e},Symbol.toStringTag,{value:"Module"}));function OPt(){const e=Bi().pathname.slice(1).split("/")[0];return I.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(o=>{document.querySelectorAll(o).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?a.jsx(p2e,{slugOverride:e}):a.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),a.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const FPt=[{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}],A9t={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"},j9t={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"},jle={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 k9t(t){return jle[t]||jle.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}):FPt,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 C9t=[{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"}],zPt={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]"},$Pt={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 YW(t){return t==="small"||t==="large"||t==="xl"?t:"medium"}function UPt(t){return zPt[YW(t)]}function VPt(t){return $Pt[YW(t)]}const qPt=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 GPt(t){const e=t.toLowerCase().replace(/:\d+$/,"");return!!(qPt.has(e)||e.endsWith(".lovable.app")||e.endsWith(".lovableproject.com")||e.endsWith(".lovable.dev"))}function g2e(){return new URLSearchParams(window.location.search).get("previewSlug")}function HPt(){const t=g2e();if(t)return t;const r=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return r?r[1]:null}function WPt(){const t=HPt(),e=!!g2e(),r=window.location.hostname,n=t?null:Qhe(r),i=!t&&!GPt(r)&&r.includes(".")&&!Xhe(r),o=t||n||(i?r:null),{data:c,isLoading:s,error:f}=gr({queryKey:["lead-site",o,i,e],queryFn:async()=>{var G;if(!o)return null;const y=Re.from("lead_sites").select("*"),_=e?y:y.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:k}=T;if(k)throw k;if(!E)return null;const{data:P}=await Re.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 Re.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:YW(D.headerLogoSize),valuationLabel:M(D.valuationLabel),noMlsMode:E.no_mls_mode===!0,bookingUrl:E.booking_url||null,pageSubtitles:E.page_subtitles||{},agent:P?{id:P.id,full_name:P.name||"",avatar_url:M(D.agentHeadshotUrl)||P.avatar_url,email:P.email,phone:P.phone,title:M(D.agentTitle)||P.title,bio:M(D.agentBio)||P.bio,areas_served:P.areas_served||null,years_experience:P.years_experience??null,instagram_url:P.instagram_url||null,facebook_url:P.facebook_url||null,linkedin_url:P.linkedin_url||null,google_business_url:P.google_business_url||null,zillow_profile_url:P.zillow_profile_url||null,realtor_profile_url:P.realtor_profile_url||null,specialties:P.specialties||null}:void 0,testimonials:Array.isArray(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:!!o,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),p=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:p}}async function KPt(t,e){try{await Re.functions.invoke("lead-site-notify",{body:{lead:e,lead_site_id:t}})}catch(r){console.warn("Lead notification failed:",r)}}function y2e(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 YPt=_x({lead_site_id:Ji().uuid(),name:Ji().trim().min(1).max(160),email:Ji().trim().email().max(255),phone:Ji().max(40).nullable().optional(),message:Ji().max(5e3).nullable().optional(),source_page:Ji().max(2e3).nullable().optional(),lead_type:Ji().max(100),metadata:E9e(Ji(),dV()).nullable().optional()});async function Nk(t){const e=YPt.safeParse(t);if(!e.success)return{error:new Error("Please check your name, email, and message.")};const{error:r}=await Re.rpc("submit_identified_website_lead",{_site_id:e.data.lead_site_id,_token:y2e(e.data.lead_site_id),_lead:e.data});return{error:r}}async function I9t(t,e,r){const{error:n}=await Re.rpc("record_identified_property_view",{_site_id:t,_token:y2e(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 N9t(t,e,r,n,i){return t!=="disabled"&&!e&&!r&&n>i}const x2e=I.createContext(null);function hT(){const t=I.useContext(x2e);if(!t)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return t}function wR({siteConfig:t,children:e}){const[r,n]=I.useState(null),[i,o]=I.useState(null),[c,s]=I.useState(!0);I.useEffect(()=>{let _=!0,T=0;const E=async R=>{var B;const D=++T;let{data:M}=await Re.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 Re.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||(o(M?{...M,email:R.email||""}:null),s(!1))},{data:{subscription:k}}=Re.auth.onAuthStateChange((R,D)=>{const M=(D==null?void 0:D.user)??null;n(M),M?window.setTimeout(()=>void E(M),0):(T+=1,o(null),s(!1))}),P=window.setTimeout(()=>{_&&(console.warn("Lead site auth initialization timed out."),s(!1))},8e3);return()=>{_=!1,window.clearTimeout(P),k.unsubscribe()}},[t.id]),I.useEffect(()=>{const _=new URL(window.location.href),T=_.searchParams.get("signin");T&&(_.searchParams.delete("signin"),window.history.replaceState({},"",_.pathname+_.search+_.hash),Re.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=I.useCallback(async _=>{const T=_.email.toLowerCase().trim(),{data:E,error:k}=await Re.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(k)throw k;let P=!1;if(E!=null&&E.token_hash){const{error:R}=await Re.auth.verifyOtp({type:"email",token_hash:E.token_hash});R?console.error("Instant sign-in after registration failed:",R):P=!0}{const{error:R}=await Nk({lead_site_id:t.id,name:_.name.trim(),email:T,phone:_.phone.trim(),message:P?"Created a website account (signed in)":"Requested a website account; email verification pending",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,verification_pending:!P}});if(R)throw R;KPt(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:P,existing:(E==null?void 0:E.new_account)===!1}},[t.id]),p=I.useCallback(async(_,T)=>{const E=_.toLowerCase().trim(),{data:k,error:P}=await Re.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:E,mode:"signin",redirect_to:window.location.href}});if(P)throw P;let R=!1;if(k!=null&&k.token_hash){const{error:D}=await Re.auth.verifyOtp({type:"email",token_hash:k.token_hash});D||(R=!0,Nk({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]),y=I.useCallback(async()=>{await Re.auth.signOut(),n(null),o(null)},[]);return a.jsx(x2e.Provider,{value:{user:r,profile:i,isLoading:c,signUp:f,signIn:p,signOut:y},children:e})}const _2e=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),v2e=new Set(["tomlois"]);function ax(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||_2e.has(t.id||"")||v2e.has((t.subdomainSlug||"").toLowerCase())||!t.mlsProviderId:!1}function ZPt(t,e){var r;return t?((r=t.themeConfig)==null?void 0:r.referralMode)===!0||_2e.has(t.id||"")||v2e.has((t.subdomainSlug||"").toLowerCase()):!1}function P9t(t,e){return ZPt(t)?"referral":ax(t,e)?"direct":"idx"}function R9t(t){return`Contact ${t.split(" ")[0]||"Me"}`}const XPt="free_luxury",QPt="free_beta";function b2e(t){const e=t==null?void 0:t.planTier;return e===XPt||e===QPt}const L9t={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."}},fT="#c9a96e",JPt="Schedule a Free Consultation",eRt={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function Pp({bookingUrl:t,label:e=JPt,className:r="",variant:n="solid",color:i=fT,size:o="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 ${eRt[o]}`,p=n==="solid"?{backgroundColor:i,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${i}`}:{borderColor:i,color:i,borderWidth:1};return a.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:p,children:[a.jsx(t9,{className:"h-4 w-4 flex-shrink-0"}),a.jsx("span",{children:e})]})}function D9t({bookingUrl:t,agentName:e,accentColor:r=fT,config:n={},luxury:i=!0}){const o=n.bookingUrl||t;if(!o)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.`,p=n.buttonLabel||"Book My Free Consultation",y=[{icon:Rl,title:n.point1Title||"30 Minutes",text:n.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:pDe,title:n.point2Title||"A Personal Call",text:n.point2Text||`${e.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:ic,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 a.jsxs("section",{className:`relative py-24 ${_} overflow-hidden`,children:[a.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${r}, transparent 60%)`}}),a.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:a.jsxs(fr.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[a.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[a.jsx("div",{className:"h-px w-12 bg-white/10"}),a.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:r},children:c}),a.jsx("div",{className:"h-px w-12 bg-white/10"})]}),a.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s}),a.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}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:y.map((T,E)=>a.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[a.jsx(T.icon,{className:"h-5 w-5 mb-4",style:{color:r}}),a.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:T.title}),a.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:T.text})]},E))}),a.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[a.jsx(Pp,{bookingUrl:o,label:p,size:"lg",color:r,source:"home_section"}),a.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function M9t({bookingUrl:t,accentColor:e=fT,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:o="",source:c}){return t?a.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"} ${o}`,children:[a.jsxs("div",{children:[a.jsx("p",{className:`text-lg ${i?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:r}),a.jsx("p",{className:`text-sm mt-1 ${i?"text-white/45":"text-gray-600"}`,children:n})]}),a.jsx(Pp,{bookingUrl:t,label:"Schedule Now",color:e,size:"sm",className:"flex-shrink-0",source:c})]}):null}function tRt({bookingUrl:t,accentColor:e=fT}){const[r,n]=I.useState(!1),[i,o]=I.useState(!1);if(I.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&o(!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"),o(!0)};return a.jsxs(a.Fragment,{children:[a.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:a.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[a.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:[a.jsx(t9,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),a.jsx("button",{onClick:c,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:a.jsx(Ds,{className:"h-4 w-4"})})]})}),a.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:a.jsx(Pp,{bookingUrl:t,label:"Schedule a Free Consultation",size:"sm",color:e,source:"sticky"})})]})}function rRt({bookingUrl:t,agentName:e}){return I.useEffect(()=>{if(t){const r=setTimeout(()=>window.location.replace(t),400);return()=>clearTimeout(r)}},[t]),a.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:a.jsxs("div",{children:[a.jsx(t9,{className:"h-8 w-8 mx-auto mb-6",style:{color:fT}}),a.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"}),a.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&&a.jsx("div",{className:"mt-8",children:a.jsx(Pp,{bookingUrl:t,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}const ZW=` 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 GF(t){return gr({queryKey:["lead-site-exchange-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.from("listings").select(ZW).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 XW(t){return gr({queryKey:["lead-site-sold-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.from("listings").select(ZW).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 O9t(t,e){return gr({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=Re.from("listings").select(ZW).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:o}=await n.maybeSingle();if(o)throw o;return i??null}})}function F9t(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 B9t(t){return t?`$${t.toLocaleString()}`:"Price upon request"}const nRt="b4e0faa0-5246-4b05-8545-18596e7ff784",iRt=_x({name:Ji().trim().min(1,"Please enter your name.").max(160),email:Ji().trim().email("Please enter a valid email.").max(255),phone:Ji().trim().max(40),interest:x3(["Buying a home","Selling a home","Buying and selling","eXp Ready program","Other"]),preferredTime:Ji().trim().max(200),message:Ji().trim().max(4e3)});async function z9t(t,e){const r=iRt.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 Nk({lead_site_id:t,...n,metadata:{interest:r.interest,preferred_contact_time:r.preferredTime}});if(i)throw i;try{const{data:o,error:c}=await Re.functions.invoke("lead-site-notify",{body:{lead_site_id:t,lead:n}});return{emailSent:!c&&(o==null?void 0:o.success)===!0&&(o==null?void 0:o.sent)===1}}catch{return{emailSent:!1}}}const sRt=1,aRt="7e98e197-8135-428c-969f-07023434dec8",oRt="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",lRt="/__l5e/assets-v1/7e98e197-8135-428c-969f-07023434dec8/btb-emblem-white.webp",cRt="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/7e98e197-8135-428c-969f-07023434dec8/btb-emblem-white.webp",uRt="btb-emblem-white.webp",dRt=141720,hRt="image/webp",fRt="2026-10-30T05:18:02Z",mRt={version:sRt,asset_id:aRt,project_id:oRt,url:lRt,r2_key:cRt,original_filename:uRt,size:dRt,content_type:hRt,created_at:fRt},pRt="/assets/hero-Bp0n5rUQ.jpg",gRt="/assets/construction-DRPJW-Zl.jpg",yRt="/assets/design-DQodobBx.jpg",xRt="/assets/realestate-C0vC4CaI.jpg",_Rt="/assets/lexington-BXiMdbEn.jpg",Hh={hero:pRt,construction:gRt,design:yRt,realestate:xRt,lexington:_Rt},Il={name:"Building The Bluegrass",legal:"Building The Bluegrass Realty",phone:"(859) 201-2101",phoneHref:"tel:+18592012101",address:"3320 Clay Mills Rd",cityLine:"Lexington, KY 40503",logoWhite:`https://tile-portal.lovable.app${mRt.url}`,facebook:"https://www.facebook.com/buildingthebluegrass",instagram:"https://www.instagram.com/buildingthebluegrass"},Ya="https://www.buildingthebluegrass.com/wp-content/uploads/",Rq=[{name:"Joey Svec",role:"CEO & Principal Broker",photo:Ya+"fx-gs.jpeg",group:"Leadership",licensed:!0},{name:"Maria Gillette",role:"Principal of Real Estate & REALTOR®",photo:Ya+"maria.jpeg",group:"Leadership",licensed:!0},{name:"Brad Boaz",role:"Landscape Architect & Planner",photo:Ya+"BradBoaz.jpeg",group:"Construction & Design"},{name:"Elizabeth Powell",role:"Senior Associate Designer",photo:Ya+"Elizabeth-headshot.jpg",group:"Construction & Design"},{name:"Jeff Moore",role:"Project Manager",photo:Ya+"Jeff_Moore_Headshot_BW_Square-400x400.jpg",group:"Construction & Design"},{name:"Michael Wilbanks",role:"Project Manager",photo:Ya+"Mike-headshot.jpg",group:"Construction & Design"},{name:"Noah Storkson",role:"Foreman",photo:Ya+"Noah-headshot.jpg",group:"Construction & Design"},{name:"Jane Carter",role:"Estimator & Procurement Specialist",photo:Ya+"Jane-Headshot.jpg",group:"Construction & Design"},{name:"Kristi White",role:"REALTOR®",photo:Ya+"White_Kristi_BW-scaled-e1725038078208.jpg",group:"Real Estate",licensed:!0},{name:"Mary Grenet",role:"REALTOR®",photo:Ya+"Grenet_Mary_BW-scaled-e1725037952355.jpg",group:"Real Estate",licensed:!0},{name:"Jim Cottle",role:"REALTOR®",photo:Ya+"rsz_1jim-e1695063749369.jpg",group:"Real Estate",licensed:!0},{name:"Allison Haas",role:"REALTOR®",photo:Ya+"allison.jpeg",group:"Real Estate",licensed:!0},{name:"Chris Haas",role:"REALTOR®",photo:Ya+"chris.jpeg",group:"Real Estate",licensed:!0},{name:"Randi Mjos",role:"REALTOR®",photo:Ya+"LMP_8523-scaled-e1695063828144.jpg",group:"Real Estate",licensed:!0},{name:"Cindi Baston",role:"REALTOR®",photo:Ya+"Cindi-Baston-BW-scaled-e1725038818587.jpg",group:"Real Estate",licensed:!0},{name:"Valeria Kaidanov",role:"REALTOR®",photo:Ya+"Valeria-headshot-.jpg",group:"Real Estate",licensed:!0},{name:"Joshua Cromwell",role:"REALTOR®",photo:Ya+"Joshua-Cromwell_BW-scaled-e1725038396105.jpg",group:"Real Estate",licensed:!0},{name:"Monica Suetholz",role:"REALTOR®",photo:Ya+"fx-gs5.jpeg",group:"Real Estate",licensed:!0},{name:"Angela Piech",role:"REALTOR®",photo:Ya+"Angela-Piech-headshot.jpeg",group:"Real Estate",licensed:!0},{name:"Shannon Foster",role:"REALTOR®",photo:Ya+"Shannon-headshot.jpg",group:"Real Estate",licensed:!0},{name:"Hampton Johnson",role:"REALTOR®",photo:Ya+"Hampton-Johnson-BW.webp",group:"Real Estate",licensed:!0},{name:"Jodie Fite",role:"Accounting",photo:Ya+"jodie-e1695063894957.png",group:"Operations"},{name:"Samantha Elliot",role:"Executive Assistant & Bookkeeper",photo:Ya+"Sam-headshot.jpg",group:"Operations"}],$C=[{name:"Lexington",county:"Fayette County",blurb:"The heart of the Bluegrass — historic neighborhoods, a lively downtown, the University of Kentucky and horse country minutes away."},{name:"Nicholasville",county:"Jessamine County",blurb:"Just south of Lexington in Jessamine County, with established neighborhoods and new construction."},{name:"Georgetown",county:"Scott County",blurb:"A historic downtown in Scott County with easy access to I-75 and Lexington."},{name:"Versailles",county:"Woodford County",blurb:"Woodford County charm surrounded by farmland and the Kentucky River."},{name:"Winchester",county:"Clark County",blurb:"Clark County’s small-town character east of Lexington."},{name:"Richmond",county:"Madison County",blurb:"Madison County, home to Eastern Kentucky University."}],bS=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,kle=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"relocate",label:"Relocating to the Bluegrass"},{key:"explore",label:"Just exploring"}],w2e="https://wsrv.nl/",vRt=["cdn.photos.sparkplatform.com","images.unsplash.com","cdn.repliers.io","cdn.repliers.com","relzejiswnotikjgvjhz.supabase.co","supabase.co"],bRt={thumb:200,card:600,hero:1200,full:1920},wRt={thumb:70,card:75,hero:80,full:82};function $9t(t,e={}){return""}function SRt(t){if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.startsWith(w2e)||t.includes("/functions/v1/mlsgrid-media")||t.includes("/functions/v1/trestle-media"))return!1;try{const e=new URL(t);return vRt.some(r=>e.hostname===r||e.hostname.endsWith("."+r))}catch{return!1}}function TRt(t,e={}){if(!t)return"";if(!SRt(t))return t;const r=e.variant??"card",n=e.width??bRt[r],i=e.quality??wRt[r],o=t.replace(/^https?:\/\//,""),c=new URLSearchParams({url:o,w:String(n),q:String(i),output:"webp"});return e.height&&c.set("h",String(e.height)),e.fit&&c.set("fit",e.fit),`${w2e}?${c.toString()}`}function a1({siteConfig:t,accentColor:e,sectionTitle:r,cities:n,count:i=12,mode:o,luxuryMode:c=!1}){const s=Gs(),f=I.useRef(null),[p,y]=I.useState(!1),[_,T]=I.useState(!1),{data:E=[],isLoading:k}=gr({queryKey:["lead-site-carousel",t.id,o,n,i,t.agentId],queryFn:async()=>{const B="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/lead-site-search",V={leadSiteId:t.id,pageSize:i,propertyType:"Residential"},G=Q=>{const re=(Q.propertyType||"").toLowerCase().replace(/\s+/g,"");return re?re.startsWith("residential")||re.startsWith("singlefamily")||re.startsWith("condo")||re.startsWith("townhouse")||re.startsWith("townhome")||re.startsWith("multifamily")||re.startsWith("manufactured"):!0},W=async Q=>{const re=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify(Q),signal:AbortSignal.timeout(15e3)});return re.ok?((await re.json()).listings||[]).filter(G).slice(0,i):[]};if(n){const Q=n.split(",").map(re=>re.trim()).filter(Boolean);Q.length>0&&(V.filterCities=Q)}return o==="open_houses"&&(V.openHousesOnly=!0),o==="my_listings"&&(V.agentListings=!0,V.agentId=t.agentId),o==="new_listings"&&(V.sortBy="newest"),await W(V)},staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1,refetchOnMount:!1}),P=()=>{const B=f.current;B&&(y(B.scrollLeft>10),T(B.scrollLeft{const B=f.current;if(B)return P(),B.addEventListener("scroll",P,{passive:!0}),window.addEventListener("resize",P),()=>{B.removeEventListener("scroll",P),window.removeEventListener("resize",P)}},[E]);const R=B=>{const V=f.current;if(!V)return;const G=340;V.scrollBy({left:B==="left"?-G*2:G*2,behavior:"smooth"})},D={new_listings:"New on the Market",open_houses:"Open Houses",my_listings:"My Active Listings"},M={new_listings:"The latest properties just listed",open_houses:"Tour these homes in person",my_listings:"Properties I'm currently representing"};return k?a.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:a.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[a.jsxs("div",{className:"text-center mb-10",children:[a.jsx("div",{className:`h-4 w-20 rounded mx-auto mb-3 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),a.jsx("div",{className:`h-8 w-72 rounded mx-auto mb-2 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),a.jsx("div",{className:`h-4 w-56 rounded mx-auto animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]}),a.jsx("div",{className:"flex gap-5",children:[1,2,3,4].map(B=>a.jsxs("div",{className:`min-w-[320px] rounded-2xl overflow-hidden ${c?"bg-white/5":"bg-gray-100"}`,children:[a.jsx("div",{className:`h-56 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),a.jsxs("div",{className:"p-5 space-y-3",children:[a.jsx("div",{className:`h-5 rounded w-24 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),a.jsx("div",{className:`h-4 rounded w-40 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]})]},B))})]})}):E.length?a.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:a.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[a.jsxs("div",{className:"flex items-end justify-between mb-10",children:[a.jsxs("div",{children:[a.jsx(fr.p,{initial:{opacity:0,y:10},whileInView:{opacity:1,y:0},viewport:{once:!0},className:`text-sm tracking-[0.2em] uppercase font-semibold mb-2 ${c?"tracking-[0.4em]":""}`,style:{color:e},children:o==="open_houses"?"Open Houses":o==="my_listings"?"My Listings":"Just Listed"}),a.jsx(fr.h2,{initial:{opacity:0,y:15},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:.05},className:`text-3xl md:text-4xl tracking-tight ${c?"text-white":"text-gray-900 font-bold"}`,style:c?{fontFamily:"'Playfair Display', Georgia, serif"}:{},children:r||D[o]}),a.jsx(fr.p,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},transition:{delay:.1},className:`mt-1.5 ${c?"text-white/40":"text-gray-500"}`,children:M[o]})]}),a.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[a.jsx("button",{onClick:()=>R("left"),disabled:!p,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:a.jsx(xm,{className:"h-5 w-5"})}),a.jsx("button",{onClick:()=>R("right"),disabled:!_,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:a.jsx(vd,{className:"h-5 w-5"})})]})]}),a.jsxs("div",{className:"relative -mx-6",children:[a.jsxs("div",{ref:f,className:"flex gap-5 overflow-x-auto scrollbar-hide px-6 snap-x snap-mandatory",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:[E.map((B,V)=>{var G,W,Z,Q;return a.jsx(fr.div,{initial:{opacity:0,y:20},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.4,delay:V*.05},onClick:()=>s(`/listing/${B.mlsNumber}`),className:"group min-w-[300px] sm:min-w-[320px] max-w-[340px] flex-shrink-0 snap-start cursor-pointer",children:a.jsxs("div",{className:`overflow-hidden h-full flex flex-col ${c?"bg-[#161312] hover:bg-[#1a1715] transition-all duration-500":"bg-white rounded-2xl shadow-[0_2px_20px_-4px_rgba(0,0,0,0.08)] hover:shadow-[0_8px_40px_-8px_rgba(0,0,0,0.15)] transition-all duration-500"}`,children:[a.jsxs("div",{className:"relative h-56 overflow-hidden",children:[a.jsx("img",{src:TRt(((G=B.photos)==null?void 0:G[0])||"https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=600&q=75",{variant:"card"}),alt:B.address,className:"w-full h-full object-cover group-hover:scale-[1.06] transition-transform duration-700 ease-out",loading:"lazy",decoding:"async"}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"}),a.jsx("div",{className:"absolute top-3 left-3 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide uppercase text-white backdrop-blur-md",style:{backgroundColor:`${e}cc`},children:o==="open_houses"?"Open House":B.status||"Active"}),a.jsx("div",{className:"absolute bottom-3 left-3",children:a.jsxs("p",{className:"text-2xl font-bold text-white drop-shadow-lg",children:["$",(W=B.price)==null?void 0:W.toLocaleString()]})}),((Z=B.photos)==null?void 0:Z.length)>1&&a.jsxs("div",{className:"absolute bottom-3 right-3 px-2.5 py-1 bg-black/40 backdrop-blur-sm rounded-full text-[11px] text-white font-medium",children:[B.photos.length," photos"]})]}),a.jsxs("div",{className:"p-4 flex-1 flex flex-col",children:[a.jsx("p",{className:`font-semibold text-[15px] leading-snug mb-1 truncate ${c?"text-white/80":"text-gray-900"}`,children:B.address}),a.jsxs("p",{className:`text-sm mb-3 truncate ${c?"text-white/30":"text-gray-500"}`,children:[B.city,", ",B.state," ",B.zip]}),a.jsxs("div",{className:`flex items-center gap-4 mt-auto pt-3 border-t ${c?"border-white/5":"border-gray-100"}`,children:[a.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[a.jsx(CS,{className:"h-3.5 w-3.5"}),a.jsx("span",{className:"text-sm font-medium",children:B.bedrooms})]}),a.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[a.jsx(nv,{className:"h-3.5 w-3.5"}),a.jsx("span",{className:"text-sm font-medium",children:B.bathrooms})]}),a.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[a.jsx(lDe,{className:"h-3.5 w-3.5"}),a.jsxs("span",{className:"text-sm font-medium",children:[(Q=B.sqft)==null?void 0:Q.toLocaleString()," sqft"]})]})]})]})]})},B.mlsNumber)}),a.jsx(fr.div,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},onClick:()=>s(o==="open_houses"?"/search?openHouses=1":"/search"),className:"min-w-[200px] flex-shrink-0 snap-start cursor-pointer flex items-center justify-center",children:a.jsxs("div",{className:"text-center group",children:[a.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3 transition-transform group-hover:scale-110",style:{backgroundColor:`${e}15`},children:a.jsx(ra,{className:"h-6 w-6",style:{color:e}})}),a.jsx("p",{className:`text-sm font-semibold transition-colors ${c?"text-white/50 group-hover:text-white":"text-gray-700 group-hover:text-gray-900"}`,children:"View All"})]})})]}),a.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-12 bg-gradient-to-l pointer-events-none md:hidden ${c?"from-[#0d0b0a]":"from-white"} to-transparent`})]})]})}):null}function mT(){I.useEffect(()=>{const t=document.querySelectorAll(".btb-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.12});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}const Cle=[{label:"Buy",to:"/buy",children:[{label:"Search All Homes",to:"/search"},{label:"Buying With Us",to:"/buy"},{label:"Land & Farms",to:"/search?propertyType=Land"},{label:"My Saved Homes",to:"/dashboard"}]},{label:"Sell",to:"/sell",children:[{label:"Selling With Us",to:"/sell"},{label:"What’s My Home Worth?",to:"/sell#value"}]},{label:"Communities",to:"/communities",children:[...$C.map(t=>({label:t.name,to:bS(t.name)})),{label:"All Communities",to:"/communities"}]},{label:"Agents",to:"/team"},{label:"Journal",to:"/blog"},{label:"About",to:"/about",children:[{label:"Our Story",to:"/about"},{label:"Our Team",to:"/team"},{label:"Join the Team",to:"/join"},{label:"Contact",to:"/contact"}]}];function ERt({children:t}){const{pathname:e}=Bi(),r=e==="/",[n,i]=I.useState(!1),[o,c]=I.useState(!1);I.useEffect(()=>{const f=()=>i(window.scrollY>40);return f(),window.addEventListener("scroll",f,{passive:!0}),()=>window.removeEventListener("scroll",f)},[]),I.useEffect(()=>c(!1),[e]);const s=r&&!n&&!o;return a.jsxs("div",{className:"btb-site min-h-screen",children:[a.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-colors duration-300 ${s?"btb-light":"btb-bg-ink shadow-sm"}`,children:[a.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${s?"h-24":"h-[72px]"} transition-all`,children:[a.jsxs(mn,{to:"/",className:"flex items-center gap-3","aria-label":"Building The Bluegrass home",children:[a.jsx("img",{src:Il.logoWhite,alt:"",className:"h-11 w-11 object-contain"}),a.jsx("span",{className:"btb-serif text-xl leading-none hidden sm:block",children:"Building The Bluegrass"})]}),a.jsx("nav",{className:"hidden xl:flex items-center gap-8","aria-label":"Main",children:Cle.map(f=>a.jsxs("div",{className:"group relative",children:[a.jsxs(mn,{to:f.to,className:"flex items-center gap-1 text-[0.8rem] tracking-[0.14em] uppercase py-6 opacity-90 hover:opacity-100",children:[f.label,f.children&&a.jsx(wc,{className:"h-3 w-3"})]}),f.children&&a.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[220px] btb-bg-paper btb-ink border btb-line py-3",children:f.children.map(p=>a.jsx(mn,{to:p.to,className:"block px-5 py-2.5 text-sm hover:btb-accent",children:p.label},p.label))})]},f.label))}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("a",{href:Il.phoneHref,className:"hidden md:flex items-center gap-2 text-sm opacity-90",children:[a.jsx(ai,{className:"h-4 w-4"}),Il.phone]}),a.jsxs(mn,{to:"/search",className:"btb-btn btb-btn-light !py-3 !px-4",children:[a.jsx(hd,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden sm:inline",children:"Search Homes"})]}),a.jsx("button",{className:"xl:hidden p-2",onClick:()=>c(!o),"aria-label":o?"Close menu":"Open menu","aria-expanded":o,children:o?a.jsx(Ds,{className:"h-6 w-6"}):a.jsx(IS,{className:"h-6 w-6"})})]})]}),o&&a.jsxs("div",{className:"xl:hidden btb-bg-ink border-t btb-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsx(mn,{to:"/search",className:"btb-btn btb-btn-light justify-center",children:"Search Homes"}),a.jsx(mn,{to:"/contact",className:"btb-btn btb-btn-ghost justify-center",children:"Contact"})]}),Cle.map(f=>a.jsxs("div",{children:[a.jsx(mn,{to:f.to,className:"btb-serif text-2xl block",children:f.label}),f.children&&a.jsx("div",{className:"mt-2 pl-1 space-y-1.5",children:f.children.map(p=>a.jsx(mn,{to:p.to,className:"block text-sm opacity-75",children:p.label},p.label))})]},f.label)),a.jsxs("a",{href:Il.phoneHref,className:"flex items-center gap-2 text-sm",children:[a.jsx(ai,{className:"h-4 w-4"}),Il.phone]})]})]}),a.jsx("main",{className:r?"":"pt-[72px]",children:t}),a.jsx(ARt,{})]})}function ARt(){return a.jsxs("footer",{className:"btb-bg-ink",children:[a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-12 md:grid-cols-12",children:[a.jsxs("div",{className:"md:col-span-5",children:[a.jsx("img",{src:Il.logoWhite,alt:"Building The Bluegrass",className:"h-16 w-16 object-contain mb-6"}),a.jsx("p",{className:"btb-serif text-3xl leading-tight max-w-sm",children:"Home, the Bluegrass way."}),a.jsxs("p",{className:"mt-6 text-sm opacity-70 leading-relaxed",children:[Il.address,a.jsx("br",{}),Il.cityLine,a.jsx("br",{}),a.jsx("a",{href:Il.phoneHref,children:Il.phone})]})]}),[["Real Estate",[["Search Homes","/search"],["Buy","/buy"],["Sell","/sell"],["Home Value","/sell#value"]]],["Explore",[...$C.slice(0,3).map(t=>[t.name,bS(t.name)]),["All Communities","/communities"],["Journal","/blog"]]],["Company",[["Our Story","/about"],["Our Team","/team"],["Join the Team","/join"],["Contact","/contact"]]]].map(([t,e])=>a.jsxs("div",{className:"md:col-span-2",children:[a.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:t}),a.jsx("ul",{className:"space-y-3 text-sm",children:e.map(([r,n])=>a.jsx("li",{children:a.jsx(mn,{to:n,className:"opacity-85 hover:opacity-100",children:r})},r))})]},t)),a.jsxs("div",{className:"md:col-span-1",children:[a.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"Follow"}),a.jsxs("ul",{className:"space-y-3 text-sm",children:[a.jsx("li",{children:a.jsx("a",{href:Il.facebook,target:"_blank",rel:"noreferrer",children:"Facebook"})}),a.jsx("li",{children:a.jsx("a",{href:Il.instagram,target:"_blank",rel:"noreferrer",children:"Instagram"})})]})]})]}),a.jsx("div",{className:"border-t btb-line-light",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 flex flex-col md:flex-row gap-3 justify-between",children:[a.jsxs("p",{children:["© ",new Date().getFullYear()," ",Il.legal,". All rights reserved. Equal Housing Opportunity."]}),a.jsx("p",{children:"Listing data provided courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function AL({compact:t=!1}){const e=Gs(),[r,n]=I.useState(""),[i,o]=I.useState(""),[c,s]=I.useState(""),f=p=>{p.preventDefault();const y=new URLSearchParams;r.trim()&&y.set("q",r.trim()),i&&y.set("maxPrice",i),c&&y.set("beds",c),e(`/search?${y.toString()}`)};return a.jsxs("form",{onSubmit:f,className:`btb-bg-paper btb-ink grid gap-0 md:grid-cols-[1fr_180px_140px_auto] ${t?"":"shadow-2xl"}`,role:"search",children:[a.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[a.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Location"}),a.jsx("input",{value:r,onChange:p=>n(p.target.value),placeholder:"City, neighborhood, address or MLS #",className:"w-full bg-transparent outline-none text-base"})]}),a.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[a.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Max price"}),a.jsxs("select",{value:i,onChange:p=>o(p.target.value),className:"w-full bg-transparent outline-none",children:[a.jsx("option",{value:"",children:"Any"}),[3e5,45e4,6e5,8e5,1e6,15e5].map(p=>a.jsxs("option",{value:p,children:["$",(p/1e3).toLocaleString(),"k"]},p))]})]}),a.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[a.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Beds"}),a.jsxs("select",{value:c,onChange:p=>s(p.target.value),className:"w-full bg-transparent outline-none",children:[a.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(p=>a.jsxs("option",{value:p,children:[p,"+"]},p))]})]}),a.jsxs("button",{type:"submit",className:"btb-btn justify-center !py-5",children:[a.jsx(hd,{className:"h-4 w-4"}),"Search"]})]})}function UC({eyebrow:t,title:e,intro:r,image:n}){return a.jsxs("section",{className:"relative h-[62vh] min-h-[440px] overflow-hidden btb-light",children:[a.jsx("img",{src:n,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),a.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-16",children:[a.jsx("p",{className:"btb-eyebrow mb-5 opacity-90",children:t}),a.jsx("h1",{className:"btb-serif text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:e}),a.jsx("p",{className:"mt-6 max-w-xl text-lg opacity-90",children:r})]})]})}function Ix({title:t,description:e}){return a.jsxs(Wo,{children:[a.jsx("title",{children:t}),a.jsx("meta",{name:"description",content:e}),a.jsx("meta",{property:"og:title",content:t}),a.jsx("meta",{property:"og:description",content:e})]})}function Nx({siteConfig:t,defaultIntent:e="explore",heading:r="What are you imagining?"}){var k;const{pathname:n}=Bi(),[i,o]=I.useState(e),[c,s]=I.useState({name:"",email:"",phone:"",message:""}),[f,p]=I.useState("idle"),[y,_]=I.useState(""),T=((k=kle.find(P=>P.key===i))==null?void 0:k.label)||"Explore my options",E=async P=>{if(P.preventDefault(),_(""),!c.name.trim()||!c.email.trim()){_("Please add your name and email.");return}p("sending");const{error:R}=await Nk({lead_site_id:t.id,name:c.name.trim(),email:c.email.trim(),phone:c.phone.trim()||null,message:`[${T}] ${c.message.trim()}`.trim(),source_page:n,lead_type:i==="sell"||i==="value"?"seller":i==="buy"?"buyer":"contact",metadata:{intent:i,intent_label:T,division:"real_estate"}});if(R){p("error"),_(R.message||"Something went wrong. Please try again or call us.");return}p("sent")};return a.jsx("section",{id:"inquire",className:"btb-bg-stone",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-14 lg:grid-cols-2",children:[a.jsxs("div",{className:"btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Start a conversation"}),a.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:r}),a.jsx("p",{className:"mt-6 btb-soft text-lg max-w-md",children:"Tell us where you are in the journey. A Building The Bluegrass agent will follow up personally — no pressure, just good advice."}),a.jsx("div",{className:"mt-10 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:kle.map(P=>a.jsx("button",{type:"button",role:"radio","aria-checked":i===P.key,onClick:()=>o(P.key),className:`px-4 py-2.5 text-sm border transition ${i===P.key?"btb-bg-ink border-transparent":"btb-line hover:btb-bg-paper"}`,children:P.label},P.key))})]}),f==="sent"?a.jsxs("div",{className:"btb-bg-paper p-10 md:p-14 flex flex-col justify-center",role:"status",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"Received"}),a.jsxs("p",{className:"btb-serif text-4xl",children:["Thank you, ",c.name.split(" ")[0],"."]}),a.jsxs("p",{className:"mt-4 btb-soft",children:["Your note about “",T.toLowerCase(),"” is with our team. For anything urgent, call ",Il.phone,"."]})]}):a.jsxs("form",{onSubmit:E,className:"btb-bg-paper p-8 md:p-12 space-y-6",noValidate:!0,children:[a.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[a.jsxs("label",{className:"block",children:[a.jsx("span",{className:"btb-eyebrow btb-soft",children:"Name *"}),a.jsx("input",{className:"btb-input",value:c.name,onChange:P=>s({...c,name:P.target.value}),autoComplete:"name",required:!0})]}),a.jsxs("label",{className:"block",children:[a.jsx("span",{className:"btb-eyebrow btb-soft",children:"Phone"}),a.jsx("input",{className:"btb-input",value:c.phone,onChange:P=>s({...c,phone:P.target.value}),autoComplete:"tel",type:"tel"})]})]}),a.jsxs("label",{className:"block",children:[a.jsx("span",{className:"btb-eyebrow btb-soft",children:"Email *"}),a.jsx("input",{className:"btb-input",type:"email",value:c.email,onChange:P=>s({...c,email:P.target.value}),autoComplete:"email",required:!0})]}),a.jsxs("label",{className:"block",children:[a.jsx("span",{className:"btb-eyebrow btb-soft",children:"Tell us a little more"}),a.jsx("textarea",{className:"btb-input min-h-[110px] resize-none",value:c.message,onChange:P=>s({...c,message:P.target.value}),placeholder:i==="sell"||i==="value"?"Property address and timing…":"Neighborhoods, price range, timing…"})]}),y&&a.jsx("p",{className:"text-sm text-destructive",role:"alert",children:y}),a.jsx("button",{type:"submit",disabled:f==="sending",className:"btb-btn w-full justify-center",children:f==="sending"?"Sending…":a.jsxs(a.Fragment,{children:["Send to our team ",a.jsx(ra,{className:"h-4 w-4"})]})})]})]})})}function jRt({siteConfig:t}){mT();const[e,r]=I.useState(0),n=Rq.filter(o=>o.group==="Leadership"),i=Rq.filter(o=>o.group==="Real Estate").slice(0,6);return a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Building The Bluegrass Realty | Lexington, KY Homes for Sale",description:"Search every home for sale in Lexington and Central Kentucky. Boutique real estate service for buyers and sellers from Building The Bluegrass Realty."}),a.jsxs("section",{className:"relative h-[92svh] md:h-[100svh] min-h-[600px] overflow-hidden btb-light",children:[a.jsx("img",{src:Hh.hero,alt:"Kentucky farmhouse at sunset (temporary placeholder image)",width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),a.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-10 md:pb-14",children:[a.jsx("p",{className:"btb-eyebrow mb-6 opacity-90",children:"Building The Bluegrass Realty · Lexington, Kentucky"}),a.jsxs("h1",{className:"btb-serif text-[2.9rem] leading-[0.98] sm:text-7xl lg:text-[7.5rem] max-w-5xl",children:["Find your place",a.jsx("br",{}),a.jsx("em",{className:"font-normal",children:"in the Bluegrass."})]}),a.jsx("p",{className:"mt-7 max-w-xl text-lg opacity-90",children:"Boutique real estate for Lexington and Central Kentucky — every home on the market, and agents who know these communities by heart."}),a.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[a.jsx(mn,{to:"/search",className:"btb-btn btb-btn-light",children:"Search Homes"}),a.jsx(mn,{to:"/sell#value",className:"btb-btn btb-btn-ghost",children:"What’s My Home Worth?"})]}),a.jsx("div",{className:"mt-14 hidden md:block",children:a.jsx(AL,{})}),a.jsxs("div",{className:"mt-4 hidden md:flex flex-wrap gap-x-6 gap-y-2 text-sm opacity-85",children:[["Lexington","Nicholasville","Georgetown","Versailles"].map(o=>a.jsx(mn,{to:bS(o),className:"hover:underline",children:o},o)),a.jsx(mn,{to:"/search?propertyType=Land",className:"hover:underline",children:"Land & Lots"})]})]})]}),a.jsx("section",{className:"md:hidden px-5 py-8 btb-bg-ink",children:a.jsx(AL,{compact:!0})}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12 items-center",children:[a.jsx("div",{className:"lg:col-span-6 btb-reveal btb-img-zoom overflow-hidden aspect-[4/5]",children:a.jsx("img",{src:Hh.design,alt:"Warm, light-filled kitchen (temporary placeholder image)",loading:"lazy",width:1200,height:1504,className:"h-full w-full object-cover"})}),a.jsxs("div",{className:"lg:col-span-5 lg:col-start-8 btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"A boutique brokerage"}),a.jsxs("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.04]",children:["Local knowledge.",a.jsx("br",{}),"A more personal experience."]}),a.jsx("p",{className:"mt-8 btb-soft text-lg leading-relaxed",children:"With more than 100 years of combined experience, our REALTORS® treat every client as if they are our only client — thoughtful pricing, honest guidance and steady negotiation from the first showing to the closing table."}),a.jsx("p",{className:"mt-5 btb-soft leading-relaxed",children:"Our vision is simple: be your trusted property professional through relationships and excellence in service."}),a.jsx(mn,{to:"/about",className:"btb-link mt-10 inline-block",children:"Our story"})]})]}),a.jsxs("section",{id:"paths",className:"btb-bg-ink",children:[a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-24 pb-10",children:[a.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"How we can help"}),a.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-3xl leading-[1.05]",children:"Wherever you are in the move, start here."})]}),a.jsx("div",{className:"grid md:grid-cols-3",children:[{k:"Buy",h:"Find the place for your next chapter.",b:"Search every listing across Central Kentucky, save favorites, get alerts and tour with an agent who knows the neighborhood.",to:"/buy",img:Hh.realestate,cta:"Start your search"},{k:"Sell",h:"Present your home at its best.",b:"Thoughtful pricing, strong presentation and a marketing plan built to bring the right buyer to your door.",to:"/sell",img:Hh.design,cta:"Talk about selling"},{k:"Communities",h:"Get to know the Bluegrass.",b:"Local guides, market snapshots and live homes for sale in Lexington and the towns around it.",to:"/communities",img:Hh.lexington,cta:"Explore communities"}].map((o,c)=>a.jsxs(mn,{to:o.to,className:"group relative block h-[78vh] min-h-[520px] overflow-hidden btb-img-zoom btb-light",children:[a.jsx("img",{src:o.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),a.jsxs("div",{className:"relative flex h-full flex-col justify-between p-8 md:p-10",children:[a.jsxs("span",{className:"btb-eyebrow opacity-80",children:["0",c+1," — ",o.k]}),a.jsxs("div",{children:[a.jsx("h3",{className:"btb-serif text-4xl leading-tight",children:o.h}),a.jsx("p",{className:"mt-4 opacity-85 max-w-sm",children:o.b}),a.jsxs("span",{className:"btb-link mt-8 inline-flex items-center gap-2",children:[o.cta," ",a.jsx(kfe,{className:"h-4 w-4"})]})]})]})]},o.k))})]}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-10 md:grid-cols-12 items-end",children:[a.jsxs("div",{className:"md:col-span-7 btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"The Journal"}),a.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:"Market notes, neighborhood stories and advice from our agents."})]}),a.jsxs("div",{className:"md:col-span-4 md:col-start-9 btb-reveal",children:[a.jsx("p",{className:"btb-soft text-lg",children:"What’s selling, where prices are heading and what to know before you make a move in Central Kentucky."}),a.jsx(mn,{to:"/blog",className:"btb-link mt-8 inline-block",children:"Read the Journal"})]})]}),a.jsx("section",{className:"btb-bg-paper border-y btb-line",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-10 lg:grid-cols-12 items-center",children:[a.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Homes across the Bluegrass"}),a.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Explore every home on the market."}),a.jsx("p",{className:"mt-6 btb-soft text-lg",children:"Search live listings from Lexington to the surrounding counties — save favorites, set alerts, and request a showing with our agents."}),a.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[a.jsx(mn,{to:"/search",className:"btb-btn",children:"Explore all homes"}),a.jsx(mn,{to:"/search?propertyType=Land",className:"btb-btn btb-btn-ghost",children:"Land & Lots"})]})]}),a.jsx("div",{className:"lg:col-span-6 lg:col-start-7 btb-reveal",children:a.jsx(AL,{compact:!0})})]})}),a.jsx("section",{className:"btb-bg-paper py-6",children:a.jsxs("div",{children:[a.jsx(a1,{siteConfig:t,accentColor:"#406E71",mode:"new_listings",sectionTitle:"Just Listed in the Bluegrass",count:12}),a.jsx(a1,{siteConfig:t,accentColor:"#406E71",mode:"open_houses",sectionTitle:"Upcoming Open Houses",count:12})]})}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12",children:[a.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Discover the Bluegrass"}),a.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Places we know by heart."}),a.jsx("div",{className:"mt-10 border-t btb-line",children:$C.map((o,c)=>a.jsxs("div",{className:"border-b btb-line",children:[a.jsxs("button",{className:"flex w-full items-center justify-between py-5 text-left",onClick:()=>r(c),"aria-expanded":e===c,children:[a.jsx("span",{className:"btb-serif text-3xl",children:o.name}),a.jsx(wc,{className:`h-5 w-5 transition ${e===c?"rotate-180":""}`})]}),e===c&&a.jsxs("div",{className:"pb-6",children:[a.jsx("p",{className:"btb-soft",children:o.blurb}),a.jsxs("div",{className:"mt-4 flex gap-6",children:[a.jsxs(mn,{to:bS(o.name),className:"btb-link",children:["Homes in ",o.name]}),a.jsx("a",{href:"#inquire",className:"btb-link",children:"Ask an agent"})]})]})]},o.name))})]}),a.jsx("div",{className:"lg:col-span-6 lg:col-start-7 overflow-hidden min-h-[420px] btb-reveal",children:a.jsx("img",{src:Hh.lexington,alt:"Bluegrass horse farm (temporary placeholder image)",loading:"lazy",className:"h-full w-full object-cover"})})]}),a.jsx("section",{className:"btb-bg-green",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32",children:[a.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6 mb-14",children:[a.jsxs("div",{children:[a.jsx("p",{className:"btb-eyebrow opacity-70 mb-5",children:"The people behind the possibilities"}),a.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-2xl leading-[1.05]",children:"REALTORS® who know the Bluegrass."})]}),a.jsx(mn,{to:"/team",className:"btb-link",children:"Meet our agents"})]}),a.jsx("div",{className:"grid gap-10 md:grid-cols-2 mb-14",children:n.map(o=>a.jsxs("div",{className:"flex gap-6 items-end btb-reveal",children:[a.jsx("img",{src:o.photo,alt:o.name,loading:"lazy",className:"w-40 h-52 object-cover object-top grayscale"}),a.jsxs("div",{children:[a.jsx("p",{className:"btb-serif text-3xl",children:o.name}),a.jsx("p",{className:"opacity-75 text-sm mt-1",children:o.role}),a.jsx("p",{className:"btb-eyebrow mt-3 opacity-60",children:"Brokerage leadership"})]})]},o.name))}),a.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-4",children:i.map(o=>a.jsxs("div",{children:[a.jsx("img",{src:o.photo,alt:o.name,loading:"lazy",className:"aspect-[3/4] w-full object-cover object-top grayscale"}),a.jsx("p",{className:"mt-2 text-sm",children:o.name}),a.jsx("p",{className:"text-xs opacity-65",children:o.role})]},o.name))})]})}),a.jsx(Nx,{siteConfig:t})]})}function S2e({steps:t}){return a.jsx("div",{className:"grid gap-px md:grid-cols-4 btb-bg-stone",children:t.map(([e,r],n)=>a.jsxs("div",{className:"btb-bg p-8 btb-reveal",children:[a.jsx("p",{className:"btb-serif text-5xl btb-accent",children:n+1}),a.jsx("p",{className:"mt-4 btb-serif text-2xl",children:e}),a.jsx("p",{className:"mt-2 btb-soft text-sm",children:r})]},e))})}function kRt(){return a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"Popular communities"}),a.jsx("div",{className:"flex flex-wrap gap-3",children:$C.map(t=>a.jsx(mn,{to:bS(t.name),className:"px-5 py-3 border btb-line hover:btb-bg-paper btb-serif text-xl",children:t.name},t.name))})]})}function CRt({siteConfig:t}){return mT(),a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Buy a Home in Lexington, KY | Building The Bluegrass Realty",description:"Search homes, land and new construction in Lexington and Central Kentucky with a boutique team of local REALTORS®."}),a.jsx(UC,{eyebrow:"Buy",title:"Find the place for your next chapter.",intro:"Every home on the market across Central Kentucky, and an agent who will tell you honestly what each one is — and isn’t.",image:Hh.realestate}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 -mt-10 relative z-10",children:a.jsx(AL,{})}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How buying with us works"}),a.jsx(S2e,{steps:[["Plan","Your goals, budget, timing and must-haves."],["Search","Live MLS listings, saved favorites and instant alerts."],["Tour & offer","Private showings and a strong, well-priced offer."],["Close","Inspections, appraisal and closing day, handled."]]})]}),a.jsx(kRt,{}),a.jsx(Nx,{siteConfig:t,defaultIntent:"buy",heading:"Let’s find your place."})]})}function IRt({siteConfig:t}){return mT(),a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Sell Your Home in Lexington, KY | Building The Bluegrass Realty",description:"Pricing, presentation and marketing that bring the right buyer. Request a free home value from Building The Bluegrass Realty."}),a.jsx(UC,{eyebrow:"Sell",title:"Present your home at its best.",intro:"Thoughtful pricing, beautiful presentation and steady negotiation — with a boutique team that treats your sale like it’s our only one.",image:Hh.design}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How selling with us works"}),a.jsx(S2e,{steps:[["Price","A clear, local market analysis of your home."],["Prepare","Practical advice on what’s worth fixing, and what isn’t."],["Market","Professional photography, MLS and targeted promotion."],["Negotiate","Offers, inspections and closing, handled for you."]]})]}),a.jsx("div",{id:"value",className:"scroll-mt-24",children:a.jsx(Nx,{siteConfig:t,defaultIntent:"value",heading:"What’s your home worth?"})})]})}function NRt({siteConfig:t}){return mT(),a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Our Story | Building The Bluegrass",description:"A Lexington real estate brokerage built on relationships, service and faith — giving 10% of all profits to charity."}),a.jsx(UC,{eyebrow:"Our story",title:"To be your trusted property professional.",intro:"A Lexington brokerage built to be the local expert through relationships, with excellence in service to our clients.",image:Hh.lexington}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:[["We Connect","Passions and gifts to serve clients through a trustworthy, fulfilling and educational experience."],["We Believe","Leadership provides the opportunity to serve others; whoever brings blessings will be enriched."],["We Give","Time and resources to others, giving 10% of all profits to charities."]].map(([e,r])=>a.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[a.jsx("p",{className:"btb-serif text-4xl",children:e}),a.jsx("p",{className:"mt-4 btb-soft leading-relaxed",children:r})]},e))}),a.jsxs("section",{className:"mx-auto max-w-3xl px-5 pb-24 btb-reveal",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"Foundational principles"}),a.jsx("div",{className:"space-y-10",children:[["Relationship","Matthew 6:28–34","A vertical relationship needs to be established before we can make a horizontal impact — serving clients and having true relationships with others."],["Worth","Genesis 1:27 & Ephesians 3:6","Rather than chasing a leaderboard, we ask where you find your worth — made in God’s image, with Him all things are possible."],["Revenue","Malachi 3:8–12","Finances are a tool to strengthen the Kingdom. We give a 10 percent tithe first, and stay faithful to that principle."],["Generational","Exodus 20:5–6","Building a stable, influential company for the community, meant to last for generations to come."]].map(([e,r,n])=>a.jsxs("div",{className:"border-t btb-line pt-6",children:[a.jsxs("div",{className:"flex justify-between gap-4",children:[a.jsx("h3",{className:"btb-serif text-3xl",children:e}),a.jsx("span",{className:"btb-soft text-sm italic",children:r})]}),a.jsx("p",{className:"mt-3 btb-soft leading-relaxed",children:n})]},e))})]}),a.jsx(Nx,{siteConfig:t})]})}function PRt({siteConfig:t}){mT();const e=["Leadership","Real Estate","Operations"];return a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Our Team | Building The Bluegrass",description:"Meet the REALTORS® and staff of Building The Bluegrass in Lexington, KY."}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-6",children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Our team"}),a.jsx("h1",{className:"btb-serif text-6xl md:text-7xl max-w-3xl leading-[1.02]",children:"The people behind the possibilities."})]}),e.map(r=>a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[a.jsxs("div",{className:"flex items-baseline justify-between border-b btb-line pb-4 mb-10",children:[a.jsx("h2",{className:"btb-serif text-4xl",children:r}),r==="Real Estate"&&a.jsx("span",{className:"btb-eyebrow btb-soft",children:"Licensed REALTORS®"})]}),a.jsx("div",{className:`grid gap-8 ${r==="Leadership"?"sm:grid-cols-2 lg:grid-cols-3":"grid-cols-2 sm:grid-cols-3 lg:grid-cols-5"}`,children:Rq.filter(n=>n.group===r).map(n=>a.jsxs("div",{className:"btb-reveal",children:[a.jsx("div",{className:"overflow-hidden aspect-[3/4]",children:a.jsx("img",{src:n.photo,alt:n.name,loading:"lazy",className:"h-full w-full object-cover object-top grayscale hover:grayscale-0 transition duration-700"})}),a.jsx("p",{className:`btb-serif mt-4 ${r==="Leadership"?"text-3xl":"text-2xl"}`,children:n.name}),a.jsx("p",{className:"btb-soft text-sm",children:n.role})]},n.name))})]},r)),a.jsx(Nx,{siteConfig:t})]})}function RRt({siteConfig:t}){return a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Join the Team | Building The Bluegrass",description:"Real estate careers at Building The Bluegrass in Lexington, KY."}),a.jsx(UC,{eyebrow:"Join the team",title:"Build a career with purpose.",intro:"REALTORS® who want to serve clients well, grow together and give back to the community.",image:Hh.construction}),a.jsx(Nx,{siteConfig:t,defaultIntent:"explore",heading:"Tell us about yourself."})]})}function LRt({siteConfig:t}){return mT(),a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Central Kentucky Communities | Building The Bluegrass",description:"Local guides to Lexington, Nicholasville, Georgetown, Versailles, Winchester and Richmond with live homes for sale."}),a.jsx(UC,{eyebrow:"Communities",title:"Discover the Bluegrass.",intro:"Guides to the places our agents know and serve — market snapshots, local favorites and live homes for sale.",image:Hh.lexington}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:$C.map(e=>a.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[a.jsx("h2",{className:"btb-serif text-4xl",children:e.name}),a.jsx("p",{className:"mt-4 btb-soft",children:e.blurb}),a.jsx("p",{className:"btb-eyebrow btb-soft mt-2",children:e.county}),a.jsxs(mn,{to:bS(e.name),className:"btb-link mt-6 inline-block",children:["Homes in ",e.name]})]},e.name))}),a.jsx(Nx,{siteConfig:t,defaultIntent:"buy"})]})}function DRt({siteConfig:t}){const[e]=px();return a.jsxs(a.Fragment,{children:[a.jsx(Ix,{title:"Contact | Building The Bluegrass",description:"Contact Building The Bluegrass at 3320 Clay Mills Rd, Lexington, KY 40503 — (859) 201-2101."}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-4 grid gap-10 md:grid-cols-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Contact"}),a.jsx("h1",{className:"btb-serif text-6xl md:text-7xl leading-[1.02]",children:"Let’s talk."})]}),a.jsxs("div",{className:"md:pt-10 btb-soft text-lg space-y-2",children:[a.jsxs("p",{children:[Il.address,a.jsx("br",{}),Il.cityLine]}),a.jsx("p",{children:a.jsx("a",{href:Il.phoneHref,className:"btb-ink",children:Il.phone})})]})]}),a.jsx(Nx,{siteConfig:t,defaultIntent:e.get("intent")||"explore"})]})}function Kg({children:t}){const e=I.useRef(null);return a.jsx("div",{ref:e,className:"btb-bg-paper min-h-[70vh]",children:t})}function QW(t){return gr({queryKey:["org-site-roster",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.rpc("get_org_site_roster",{p_site_id:t});if(r)throw r;return e||[]}})}function U9t(t,e=!1){return gr({queryKey:["org-site-listings",t,e],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:r,error:n}=await Re.rpc("get_org_site_listings",{p_site_id:t,p_sold:e});if(n)throw n;return r||[]}})}function V9t(t){return t?`$${Math.round(t).toLocaleString()}`:"Price upon request"}const MRt="/assets/hero-kv4I0DLE.jpg",ORt="/assets/lexington-DDS8S5Ti.jpg",FRt="/assets/georgetown-CDefc5Gd.jpg",BRt="/assets/winchester-BRay9GI-.jpg",zRt="/assets/interior-BGPkmSFt.jpg",Pl={hero:MRt,lexington:ORt,georgetown:FRt,winchester:BRt,interior:zRt},Wc={name:"RE/MAX Creative Realty",phone:"(859) 422-2000",phoneHref:"tel:+18594222000",tollFree:"(800) 860-7468",founded:1987,broker:"Sarith “Sari” Lawrence, Principal Broker"},M$=t=>`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(t)}`,Pk=[{key:"lexington",name:"Lexington",address:"2808 Palumbo Dr, Unit 100",cityLine:"Lexington, KY 40509",hours:"Mon–Fri · 8:30am–5:30pm",image:"lexington",note:"Our main office on the corner of Man o’ War and Palumbo, just off I-75 at exit 108.",map:M$("2808 Palumbo Dr Unit 100, Lexington, KY 40509")},{key:"georgetown",name:"Georgetown",address:"128 Edwards Ave",cityLine:"Georgetown, KY 40324",hours:"Flexible hours — call ahead",image:"georgetown",note:"Serving Scott County and the I-75 corridor north of Lexington.",map:M$("128 Edwards Ave, Georgetown, KY 40324")},{key:"winchester",name:"Winchester",address:"804 Bypass Rd",cityLine:"Winchester, KY 40391",hours:"By appointment — call ahead",image:"winchester",note:"Home base for Clark County and the eastern Bluegrass.",map:M$("804 Bypass Rd, Winchester, KY 40391")}],QM=[{name:"Lexington",county:"Fayette County",image:"lexington",blurb:"Historic neighborhoods, a lively downtown, the University of Kentucky and horse farms minutes away."},{name:"Georgetown",county:"Scott County",image:"georgetown",blurb:"A walkable historic downtown, Georgetown College and an easy I-75 commute."},{name:"Winchester",county:"Clark County",image:"winchester",blurb:"Small-town character, rolling farmland and room to breathe east of Lexington."},{name:"Nicholasville",county:"Jessamine County",image:"interior",blurb:"Established neighborhoods and new construction just south of Lexington."},{name:"Versailles",county:"Woodford County",image:"hero",blurb:"Horse country charm along the Kentucky River."},{name:"Richmond",county:"Madison County",image:"winchester",blurb:"Home to Eastern Kentucky University and growing neighborhoods."},{name:"Frankfort",county:"Franklin County",image:"georgetown",blurb:"Kentucky’s capital city, with historic homes and river views."},{name:"Lawrenceburg",county:"Anderson County",image:"hero",blurb:"Bourbon country living with a close-knit feel."}],Rk=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,O$=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"relocate",label:"Moving to Kentucky"},{key:"join",label:"Join RE/MAX Creative"}];function T2e(t){const e=(t||"").replace(/\D/g,""),r=e.length===11&&e.startsWith("1")?e.slice(1):e;return r.length!==10?null:{phone:`(${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`,phoneHref:`tel:+1${r}`}}const Ud=t=>typeof t=="string"&&t.trim()?t.trim():null;function E2e(t){const e=t.ownerType==="brokerage"?"brokerage":t.ownerType==="team"?"team":"agent";if(e==="brokerage")return{mode:e,name:Wc.name,first:Wc.name,phone:Wc.phone,phoneHref:Wc.phoneHref,email:null,photo:null,title:"Real estate brokerage",bio:null};const r=t.themeConfig||{},n=t.agent||{},i=Ud((t.siteTitle||"").split("|")[0]),o=e==="team"?Ud(t.orgName)||i||"Our Team":Ud(n.full_name)||i||"Your Agent",c=T2e(Ud(r.agentPhone)||n.phone)||{phone:Wc.phone,phoneHref:Wc.phoneHref};return{mode:e,name:o,first:e==="agent"?o.split(/\s+/)[0]:o,...c,email:Ud(r.agentEmail)||Ud(n.email),photo:Ud(r.agentHeadshotUrl)||Ud(n.avatar_url),title:Ud(r.agentTitle)||Ud(n.title)||(e==="team"?"Real estate team":"REALTOR®"),bio:Ud(r.agentBio)||Ud(n.bio)}}const $Rt=1,URt="46dc71ce-4743-4cc2-b8f2-7899c82a15ba",VRt="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",qRt="/__l5e/assets-v1/46dc71ce-4743-4cc2-b8f2-7899c82a15ba/remax-balloon-mark.webp",GRt="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/46dc71ce-4743-4cc2-b8f2-7899c82a15ba/remax-balloon-mark.webp",HRt="remax-balloon-mark.webp",WRt=23912,KRt="image/webp",YRt="2026-10-31T00:58:57Z",o1={version:$Rt,asset_id:URt,project_id:VRt,url:qRt,r2_key:GRt,original_filename:HRt,size:WRt,content_type:KRt,created_at:YRt},Lq="Lexington, Georgetown, Winchester, Nicholasville, Versailles, Richmond";function HF(){I.useEffect(()=>{const t=document.querySelectorAll(".rmc-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.1});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}function ox({title:t,description:e}){return a.jsxs(Wo,{children:[a.jsx("title",{children:t}),a.jsx("meta",{name:"description",content:e}),a.jsx("meta",{property:"og:title",content:t}),a.jsx("meta",{property:"og:description",content:e})]})}const A2e=I.createContext(E2e({ownerType:"brokerage"})),Am=()=>I.useContext(A2e);function j2e({light:t=!0}){const e=Am();return e.mode!=="brokerage"?a.jsxs("span",{className:"flex items-center gap-3",children:[a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),a.jsxs("span",{className:"leading-none",children:[a.jsx("span",{className:`block text-lg md:text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:e.name}),a.jsxs("span",{className:"block text-[0.6rem] tracking-[0.28em] uppercase opacity-80 mt-1",children:["RE",a.jsx("span",{className:"rmc-red",children:"/"}),"MAX Creative Realty"]})]})]}):a.jsxs("span",{className:"flex items-center gap-3",children:[a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),a.jsxs("span",{className:"leading-none",children:[a.jsxs("span",{className:`block text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:["RE",a.jsx("span",{className:"rmc-red",children:"/"}),"MAX"]}),a.jsx("span",{className:"block text-[0.62rem] tracking-[0.32em] uppercase opacity-80 mt-1",children:"Creative Realty"})]})]})}const Ile=[{label:"Buy",to:"/buy",children:[{label:"Search All Homes",to:"/search"},{label:"Buying With Us",to:"/buy"},{label:"Farms & Land",to:"/search?propertyType=Land"},{label:"My Saved Homes",to:"/dashboard"}]},{label:"Sell",to:"/sell",children:[{label:"Selling With Us",to:"/sell"},{label:"What’s My Home Worth?",to:"/sell#inquire"}]},{label:"Communities",to:"/communities",children:[...QM.slice(0,6).map(t=>({label:t.name,to:Rk(t.name)})),{label:"All Communities",to:"/communities"}]},{label:"Agents",to:"/agents"},{label:"Offices",to:"/offices"},{label:"About",to:"/about",children:[{label:"Our Story",to:"/about"},{label:"Join Our Team",to:"/join"},{label:"Market Blog",to:"/blog"},{label:"Contact",to:"/contact"}]}];function ZRt(t){return t==="brokerage"?Ile:Ile.map(e=>e.label==="About"?{...e,children:e.children.filter(r=>r.to!=="/join")}:e).filter(e=>t==="team"||e.label!=="Agents").map(e=>e.label==="Agents"?{...e,label:"Our Team"}:e)}function XRt({children:t,siteConfig:e}){const r=I.useMemo(()=>E2e(e),[e]),n=ZRt(r.mode),{pathname:i}=Bi(),o=i==="/",[c,s]=I.useState(!1),[f,p]=I.useState(!1);I.useEffect(()=>{const _=()=>s(window.scrollY>40);return _(),window.addEventListener("scroll",_,{passive:!0}),()=>window.removeEventListener("scroll",_)},[]),I.useEffect(()=>p(!1),[i]);const y=o&&!c&&!f;return a.jsx(A2e.Provider,{value:r,children:a.jsxs("div",{className:"rmc-site min-h-screen",children:[a.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-all duration-300 ${y?"rmc-light":"rmc-bg-navy shadow-lg"}`,children:[!y&&a.jsx("div",{className:"rmc-stripe"}),a.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${y?"h-24":"h-[72px]"} transition-all`,children:[a.jsx(mn,{to:"/","aria-label":`${r.name} home`,children:a.jsx(j2e,{})}),a.jsx("nav",{className:"hidden xl:flex items-center gap-7","aria-label":"Main",children:n.map(_=>a.jsxs("div",{className:"group relative",children:[a.jsxs(mn,{to:_.to,className:"flex items-center gap-1 text-[0.8rem] font-semibold tracking-[0.12em] uppercase py-6 opacity-90 hover:opacity-100",children:[_.label,_.children&&a.jsx(wc,{className:"h-3 w-3"})]}),_.children&&a.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[230px] rmc-card py-3 text-[hsl(var(--rmc-ink))]",children:_.children.map(T=>a.jsx(mn,{to:T.to,className:"block px-5 py-2.5 text-sm hover:rmc-red",children:T.label},T.label))})]},_.label))}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("a",{href:r.phoneHref,className:"hidden md:flex items-center gap-2 text-sm font-semibold",children:[a.jsx(ai,{className:"h-4 w-4"}),r.phone]}),a.jsxs(mn,{to:"/search",className:"rmc-btn !py-3 !px-4",children:[a.jsx(hd,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden sm:inline",children:"Search"})]}),a.jsx("button",{className:"xl:hidden p-2",onClick:()=>p(!f),"aria-label":f?"Close menu":"Open menu","aria-expanded":f,children:f?a.jsx(Ds,{className:"h-6 w-6"}):a.jsx(IS,{className:"h-6 w-6"})})]})]}),f&&a.jsxs("div",{className:"xl:hidden rmc-bg-navy border-t rmc-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[n.map(_=>a.jsxs("div",{children:[a.jsx(mn,{to:_.to,className:"rmc-display text-2xl block",children:_.label}),_.children&&a.jsx("div",{className:"mt-2 space-y-1.5",children:_.children.map(T=>a.jsx(mn,{to:T.to,className:"block text-sm opacity-75",children:T.label},T.label))})]},_.label)),a.jsxs("a",{href:r.phoneHref,className:"flex items-center gap-2 text-sm",children:[a.jsx(ai,{className:"h-4 w-4"}),r.phone]})]})]}),a.jsx("main",{className:o?"":"pt-[76px]",children:t}),a.jsx(QRt,{})]})})}function QRt(){const t=Am();return a.jsxs("footer",{className:"rmc-bg-navy",children:[a.jsx("div",{className:"rmc-stripe"}),a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-16 grid gap-12 lg:grid-cols-12",children:[a.jsxs("div",{className:"lg:col-span-4",children:[a.jsx(j2e,{}),a.jsx("p",{className:"rmc-display text-3xl mt-6 max-w-xs leading-tight",children:t.mode==="brokerage"?a.jsxs(a.Fragment,{children:["Central Kentucky’s original RE/MAX — since ",Wc.founded,"."]}):a.jsx(a.Fragment,{children:"Your Bluegrass home, handled with care."})}),t.email&&a.jsxs("a",{href:`mailto:${t.email}`,className:"mt-3 flex items-center gap-2 text-sm opacity-85",children:[a.jsx(Ti,{className:"h-4 w-4"}),t.email]}),a.jsxs("a",{href:t.phoneHref,className:"mt-6 inline-flex items-center gap-2 font-semibold",children:[a.jsx(ai,{className:"h-4 w-4"}),t.phone]})]}),a.jsx("div",{className:"lg:col-span-5 grid gap-8 sm:grid-cols-3",children:Pk.map(e=>a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"rmc-eyebrow opacity-60 mb-3",children:e.name}),a.jsxs("p",{className:"opacity-85 leading-relaxed",children:[e.address,a.jsx("br",{}),e.cityLine]}),a.jsx("a",{href:e.map,target:"_blank",rel:"noreferrer",className:"mt-2 inline-block text-xs underline opacity-70",children:"Directions"})]},e.key))}),a.jsxs("div",{className:"lg:col-span-3 grid grid-cols-2 gap-6 text-sm",children:[a.jsx("ul",{className:"space-y-2.5",children:[["Search Homes","/search"],["Buy","/buy"],["Sell","/sell"],["Communities","/communities"]].map(([e,r])=>a.jsx("li",{children:a.jsx(mn,{to:r,className:"opacity-85 hover:opacity-100",children:e})},e))}),a.jsx("ul",{className:"space-y-2.5",children:(t.mode==="brokerage"?[["Our Agents","/agents"],["Offices","/offices"],["Join Us","/join"],["Contact","/contact"]]:[[t.mode==="team"?"Our Team":"About",t.mode==="team"?"/agents":"/about"],["Offices","/offices"],["Blog","/blog"],["Contact","/contact"]]).map(([e,r])=>a.jsx("li",{children:a.jsx(mn,{to:r,className:"opacity-85 hover:opacity-100",children:e})},e))})]})]}),a.jsx("div",{className:"border-t rmc-line-light",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 space-y-1.5",children:[a.jsxs("p",{children:["© ",new Date().getFullYear()," ",t.mode==="brokerage"?"":`${t.name} · `,"RE/MAX Creative Realty. Each office independently owned and operated. ",Wc.broker,". Equal Housing Opportunity."]}),a.jsx("p",{children:"Listing data courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function JRt(){const t=Gs(),[e,r]=I.useState(""),[n,i]=I.useState(""),[o,c]=I.useState(""),s=f=>{f.preventDefault();const p=new URLSearchParams;e.trim()&&p.set("q",e.trim()),n&&p.set("maxPrice",n),o&&p.set("beds",o),t(`/search?${p.toString()}`)};return a.jsxs("form",{onSubmit:s,role:"search",className:"rmc-card text-[hsl(var(--rmc-ink))] p-2 grid gap-1 md:grid-cols-[1fr_170px_120px_auto] md:rounded-full",children:[a.jsxs("label",{className:"px-5 py-2.5",children:[a.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Where"}),a.jsx("input",{value:e,onChange:f=>r(f.target.value),placeholder:"City, ZIP, address or MLS #",className:"w-full bg-transparent outline-none"})]}),a.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[a.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Max price"}),a.jsxs("select",{value:n,onChange:f=>i(f.target.value),className:"w-full bg-transparent outline-none",children:[a.jsx("option",{value:"",children:"Any"}),[25e4,4e5,6e5,8e5,1e6,2e6].map(f=>a.jsxs("option",{value:f,children:["$",(f/1e3).toLocaleString(),"k"]},f))]})]}),a.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[a.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Beds"}),a.jsxs("select",{value:o,onChange:f=>c(f.target.value),className:"w-full bg-transparent outline-none",children:[a.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(f=>a.jsxs("option",{value:f,children:[f,"+"]},f))]})]}),a.jsxs("button",{type:"submit",className:"rmc-btn justify-center",children:[a.jsx(hd,{className:"h-4 w-4"}),"Search"]})]})}function Q_({eyebrow:t,title:e,intro:r,image:n}){return a.jsxs("section",{className:"relative h-[56vh] min-h-[420px] overflow-hidden rmc-light",children:[a.jsx("img",{src:n,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),a.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-14",children:[a.jsx("p",{className:"rmc-eyebrow mb-4",children:t}),a.jsx("h1",{className:"rmc-display text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:e}),a.jsx("p",{className:"mt-5 max-w-xl text-lg opacity-90",children:r})]})]})}function jL({eyebrow:t,title:e,intro:r,center:n=!1}){return a.jsxs("div",{className:`rmc-reveal mb-12 ${n?"text-center mx-auto max-w-2xl":"max-w-2xl"}`,children:[a.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:t}),a.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e}),r&&a.jsx("p",{className:"mt-5 rmc-soft text-lg",children:r})]})}function lx({siteConfig:t,defaultIntent:e="buy",heading:r="How can we help you move?"}){var M;const n=Am(),i=n.mode==="brokerage"?O$:O$.filter(B=>B.key!=="join"),{pathname:o}=Bi(),[c,s]=I.useState(e),[f,p]=I.useState("lexington"),[y,_]=I.useState({name:"",email:"",phone:"",message:""}),[T,E]=I.useState("idle"),[k,P]=I.useState(""),R=((M=O$.find(B=>B.key===c))==null?void 0:M.label)||"General question",D=async B=>{var W;if(B.preventDefault(),P(""),!y.name.trim()||!y.email.trim()){P("Please add your name and email.");return}E("sending");const V=(W=Pk.find(Z=>Z.key===f))==null?void 0:W.name,{error:G}=await Nk({lead_site_id:t.id,name:y.name.trim(),email:y.email.trim(),phone:y.phone.trim()||null,message:`[${R}${n.mode==="brokerage"?` · ${V} office`:""}] ${y.message.trim()}`.trim(),source_page:o,lead_type:c==="sell"||c==="value"?"seller":c==="buy"||c==="relocate"?"buyer":"contact",metadata:{intent:c,intent_label:R,office:f}});if(G){E("error"),P(G.message||`Something went wrong. Please call ${n.phone}.`);return}E("sent")};return a.jsx("section",{id:"inquire",className:"rmc-bg-mist",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-14 lg:grid-cols-2 items-center",children:[a.jsxs("div",{className:"rmc-reveal",children:[a.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:"Talk to a local expert"}),a.jsx("h2",{className:"rmc-display text-5xl md:text-6xl leading-[1.05]",children:r}),a.jsx("p",{className:"mt-5 rmc-soft text-lg max-w-md",children:n.mode==="agent"?"Tell me what you need and I’ll reach out personally — usually the same day.":n.mode==="team"?"Tell us what you need and someone from our team will reach out — usually the same day.":"Tell us what you need and the right agent from the nearest office will reach out — usually the same day."}),a.jsx("div",{className:"mt-8 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:i.map(B=>a.jsx("button",{type:"button",role:"radio","aria-checked":c===B.key,onClick:()=>s(B.key),className:`px-4 py-2.5 rounded-full text-sm font-medium border transition ${c===B.key?"rmc-bg-blue border-transparent":"rmc-line rmc-bg-paper"}`,children:B.label},B.key))})]}),T==="sent"?a.jsxs("div",{className:"rmc-card p-12",role:"status",children:[a.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:"Got it"}),a.jsxs("p",{className:"rmc-display text-4xl",children:["Thank you, ",y.name.split(" ")[0],"!"]}),a.jsxs("p",{className:"mt-4 rmc-soft",children:[n.mode==="brokerage"?"A RE/MAX Creative agent":n.mode==="agent"?n.first:"Our team"," will follow up shortly. Need us now? Call ",n.phone,"."]})]}):a.jsxs("form",{onSubmit:D,className:"rmc-card p-8 md:p-10 space-y-4",noValidate:!0,children:[a.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[a.jsx("input",{className:"rmc-input",placeholder:"Name *","aria-label":"Name",value:y.name,onChange:B=>_({...y,name:B.target.value}),autoComplete:"name"}),a.jsx("input",{className:"rmc-input",placeholder:"Phone","aria-label":"Phone",type:"tel",value:y.phone,onChange:B=>_({...y,phone:B.target.value}),autoComplete:"tel"})]}),a.jsx("input",{className:"rmc-input",placeholder:"Email *","aria-label":"Email",type:"email",value:y.email,onChange:B=>_({...y,email:B.target.value}),autoComplete:"email"}),n.mode==="brokerage"&&a.jsx("select",{className:"rmc-input","aria-label":"Nearest office",value:f,onChange:B=>p(B.target.value),children:Pk.map(B=>a.jsxs("option",{value:B.key,children:[B.name," office"]},B.key))}),a.jsx("textarea",{className:"rmc-input min-h-[110px] resize-none",placeholder:c==="sell"||c==="value"?"Property address and timing…":"Areas, price range, timing…","aria-label":"Message",value:y.message,onChange:B=>_({...y,message:B.target.value})}),k&&a.jsx("p",{className:"text-sm text-destructive",role:"alert",children:k}),a.jsx("button",{type:"submit",disabled:T==="sending",className:"rmc-btn w-full justify-center",children:T==="sending"?"Sending…":a.jsxs(a.Fragment,{children:["Send message ",a.jsx(ra,{className:"h-4 w-4"})]})})]})]})})}function k2e(t){return(t||"?").split(/\s+/).map(e=>e[0]).slice(0,2).join("").toUpperCase()}function JM({a:t}){var r;const e=t.agent_site_slug?`https://${t.agent_site_slug}.thelocalmove.com`:null;return a.jsxs("div",{className:"rmc-card overflow-hidden group flex flex-col",children:[a.jsxs("div",{className:"aspect-[4/5] rmc-bg-mist overflow-hidden rmc-zoom relative",children:[t.avatar_url?a.jsx("img",{src:t.avatar_url,alt:t.full_name||"",loading:"lazy",className:"h-full w-full object-cover"}):a.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-5xl rmc-blue",children:k2e(t.full_name)}),t.team_name&&a.jsx("span",{className:"absolute left-3 top-3 rounded-full rmc-bg-navy px-3 py-1 text-[0.65rem] font-semibold uppercase tracking-wider",children:t.team_name})]}),a.jsxs("div",{className:"p-5 flex-1 flex flex-col",children:[a.jsx("p",{className:"font-semibold text-lg leading-tight",children:t.full_name}),a.jsx("p",{className:"text-sm rmc-soft mt-0.5",children:t.title||"REALTOR®"}),a.jsxs("div",{className:"mt-4 space-y-1.5 text-sm",children:[t.phone&&a.jsxs("a",{href:`tel:${t.phone.replace(/[^\d+]/g,"")}`,className:"flex items-center gap-2 hover:rmc-red",children:[a.jsx(ai,{className:"h-3.5 w-3.5"}),((r=T2e(t.phone))==null?void 0:r.phone)||t.phone]}),t.email&&a.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 hover:rmc-red truncate",children:[a.jsx(Ti,{className:"h-3.5 w-3.5 shrink-0"}),a.jsx("span",{className:"truncate",children:t.email})]})]}),e&&a.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",className:"mt-auto pt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Visit website ",a.jsx(kfe,{className:"h-3.5 w-3.5"})]})]})]})}function C2e({roster:t}){const e=Am(),r=(e.bio||"").split(/\n\s*\n/).map(n=>n.trim()).filter(Boolean);return e.mode==="team"?a.jsx("section",{className:"rmc-bg-paper",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[a.jsx(jL,{eyebrow:"Meet the team",title:`The ${e.name}.`,intro:r[0]||"Local experts who share the work — so you always have someone ready to help."}),a.jsxs(mn,{to:"/agents",className:"rmc-btn mb-12",children:["Meet everyone ",a.jsx(ra,{className:"h-4 w-4"})]})]}),t.length>0&&a.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:t.slice(0,8).map(n=>a.jsx(JM,{a:n},n.user_id))})]})}):a.jsx("section",{className:"rmc-bg-paper",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-12 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] items-center",children:[a.jsxs("div",{className:"rmc-reveal relative",children:[a.jsx("div",{className:"aspect-[4/5] overflow-hidden rounded-[1.5rem] rmc-bg-mist",children:e.photo?a.jsx("img",{src:e.photo,alt:e.name,loading:"lazy",className:"h-full w-full object-cover"}):a.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-7xl rmc-blue",children:k2e(e.name)})}),a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"absolute -right-4 -bottom-6 h-24 w-auto drop-shadow-lg"})]}),a.jsxs("div",{className:"rmc-reveal",children:[a.jsxs("p",{className:"rmc-eyebrow rmc-red mb-4",children:["Meet ",e.first]}),a.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e.name}),a.jsxs("p",{className:"mt-2 rmc-soft",children:[e.title," · RE/MAX Creative Realty"]}),a.jsx("div",{className:"mt-6 space-y-4 text-lg rmc-soft max-w-2xl",children:(r.length?r.slice(0,2):["I help Central Kentucky buyers and sellers move with clarity and confidence — with local market knowledge and the reach of RE/MAX behind every move."]).map((n,i)=>a.jsx("p",{children:n},i))}),a.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[a.jsxs("a",{href:e.phoneHref,className:"rmc-btn",children:[a.jsx(ai,{className:"h-4 w-4"}),e.phone]}),e.email&&a.jsxs("a",{href:`mailto:${e.email}`,className:"rmc-btn rmc-btn-blue",children:[a.jsx(Ti,{className:"h-4 w-4"}),"Email ",e.first]}),a.jsxs(mn,{to:"/about",className:"rmc-btn rmc-btn-ghost",children:["My story ",a.jsx(ra,{className:"h-4 w-4"})]})]})]})]})})}function eLt({siteConfig:t}){var c;HF();const e=Am(),r=e.mode==="brokerage",{data:n=[]}=QW(e.mode==="agent"?null:t.id),i=(r?n.filter(s=>s.avatar_url):n).slice(0,8),o=((c=t.themeConfig)==null?void 0:c.heroImageUrl)||Pl.hero;return a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:r?"RE/MAX Creative Realty | Lexington, Georgetown & Winchester KY Homes for Sale":`${e.name} | RE/MAX Creative Realty | Central Kentucky Homes for Sale`,description:r?"Search every Central Kentucky home for sale. RE/MAX Creative Realty has served the Bluegrass since 1987 with offices in Lexington, Georgetown and Winchester.":`Search every Central Kentucky home for sale with ${e.name} of RE/MAX Creative Realty.`}),a.jsxs("section",{className:"relative h-[100svh] min-h-[640px] overflow-hidden rmc-light",children:[a.jsx("img",{src:r?Pl.hero:o,alt:"Kentucky horse farm at sunrise",width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[9%] top-[22%] h-28 w-auto drop-shadow-lg"}),a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[21%] top-[36%] h-14 w-auto opacity-80 drop-shadow",style:{animationDelay:"-3s"}}),a.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-12 md:pb-16",children:[a.jsx("p",{className:"rmc-eyebrow mb-5",children:r?"Lexington · Georgetown · Winchester":`${e.name} · RE/MAX Creative Realty`}),a.jsxs("h1",{className:"rmc-display text-[3rem] leading-[0.98] sm:text-7xl lg:text-[7rem] max-w-5xl",children:["Your Bluegrass home ",a.jsx("em",{className:"rmc-red not-italic",children:"starts here."})]}),a.jsx("p",{className:"mt-6 max-w-xl text-lg opacity-90",children:r?"Central Kentucky’s original RE/MAX. Three offices, 70+ local REALTORS®, and every home on the market — searchable right here.":e.mode==="team"?"Local REALTORS® who work together for you — and every home on the market, searchable right here.":`Local guidance from ${e.first}, backed by RE/MAX Creative Realty — and every home on the market, searchable right here.`}),a.jsx("div",{className:"mt-10 max-w-4xl",children:a.jsx(JRt,{})}),a.jsx("div",{className:"mt-5 flex flex-wrap gap-x-5 gap-y-2 text-sm opacity-90",children:QM.slice(0,6).map(s=>a.jsx(mn,{to:Rk(s.name),className:"hover:underline",children:s.name},s.name))})]})]}),r&&a.jsx("section",{className:"rmc-bg-blue",children:a.jsx("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-12 grid grid-cols-2 md:grid-cols-4 gap-8",children:[[Ww,`Since ${Wc.founded}`,"Serving Central Kentucky"],[ul,n.length?`${n.length}+`:"70+","Local REALTORS®"],[go,"3","Offices in the Bluegrass"],[La,"8+","Counties we cover"]].map(([s,f,p])=>a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(s,{className:"h-8 w-8 opacity-80 shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"rmc-display text-4xl leading-none",children:f}),a.jsx("p",{className:"text-sm opacity-80 mt-1",children:p})]})]},p))})}),!r&&a.jsx(C2e,{siteConfig:t,roster:n}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsx(jL,{eyebrow:"Fresh on the market",title:"Just listed in Central Kentucky.",intro:"Live from Imagine MLS — updated throughout the day."}),a.jsxs("div",{className:"space-y-6",children:[e.mode==="agent"&&a.jsx(a1,{siteConfig:t,accentColor:"#003DA5",mode:"my_listings",sectionTitle:`${e.first}’s Listings`,count:12}),a.jsx(a1,{siteConfig:t,accentColor:"#DC1C2E",cities:Lq,mode:"new_listings",sectionTitle:"Newest Listings",count:12}),a.jsx(a1,{siteConfig:t,accentColor:"#003DA5",cities:Lq,mode:"open_houses",sectionTitle:"Open Houses This Week",count:12})]}),a.jsx("div",{className:"mt-10",children:a.jsxs(mn,{to:"/search",className:"rmc-btn rmc-btn-blue",children:["See every home ",a.jsx(ra,{className:"h-4 w-4"})]})})]}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24 grid gap-6 md:grid-cols-2",children:[{to:"/buy",img:Pl.interior,eyebrow:"Buying",title:"Find the one.",copy:"Search like an insider with saved searches, instant alerts and an agent who knows every street."},{to:"/sell",img:Pl.lexington,eyebrow:"Selling",title:"Sell for more.",copy:"Pricing backed by live MLS data, marketing with the reach of the RE/MAX network."}].map(s=>a.jsxs(mn,{to:s.to,className:"rmc-reveal relative overflow-hidden rounded-[1.5rem] h-[440px] rmc-zoom rmc-light group",children:[a.jsx("img",{src:s.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),a.jsxs("div",{className:"absolute bottom-0 p-8 md:p-10",children:[a.jsx("p",{className:"rmc-eyebrow mb-3",children:s.eyebrow}),a.jsx("p",{className:"rmc-display text-5xl",children:s.title}),a.jsx("p",{className:"mt-3 max-w-sm opacity-90",children:s.copy}),a.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold uppercase tracking-wider",children:["Learn more ",a.jsx(ra,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]},s.to))}),a.jsx("section",{className:"rmc-bg-navy",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsxs("div",{className:"rmc-reveal mb-12 max-w-2xl",children:[a.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:r?"Three offices":"RE/MAX Creative offices"}),a.jsx("h2",{className:"rmc-display text-4xl md:text-6xl",children:"Close to home, wherever home is."})]}),a.jsx("div",{className:"grid gap-6 md:grid-cols-3",children:Pk.map(s=>a.jsxs("div",{className:"rmc-reveal rounded-[1.25rem] overflow-hidden bg-[hsl(var(--rmc-cream)/0.06)] border rmc-line-light",children:[a.jsx("div",{className:"h-48 overflow-hidden rmc-zoom",children:a.jsx("img",{src:Pl[s.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),a.jsxs("div",{className:"p-6",children:[a.jsx("p",{className:"rmc-display text-3xl",children:s.name}),a.jsxs("p",{className:"mt-3 text-sm opacity-85 flex gap-2",children:[a.jsx(qs,{className:"h-4 w-4 shrink-0 mt-0.5"}),s.address,", ",s.cityLine]}),a.jsxs("p",{className:"mt-2 text-sm opacity-70 flex gap-2",children:[a.jsx(Rl,{className:"h-4 w-4 shrink-0 mt-0.5"}),s.hours]}),a.jsxs("div",{className:"mt-5 flex gap-3",children:[a.jsx("a",{href:s.map,target:"_blank",rel:"noreferrer",className:"rmc-btn !py-2.5 !px-4 !text-[0.7rem]",children:"Directions"}),a.jsx("a",{href:Wc.phoneHref,className:"rmc-btn rmc-btn-ghost !py-2.5 !px-4 !text-[0.7rem]",children:"Call"})]})]})]},s.key))})]})}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsx(jL,{eyebrow:"Explore the Bluegrass",title:"Communities we call home."}),a.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-4",children:QM.slice(0,4).map((s,f)=>a.jsxs(mn,{to:Rk(s.name),className:`rmc-reveal relative overflow-hidden rounded-[1.25rem] rmc-zoom rmc-light ${f===0?"lg:col-span-2 lg:row-span-2 h-[300px] lg:h-full min-h-[300px]":"h-[300px]"}`,children:[a.jsx("img",{src:Pl[s.image],alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),a.jsxs("div",{className:"absolute bottom-0 p-6",children:[a.jsx("p",{className:"rmc-eyebrow opacity-80",children:s.county}),a.jsx("p",{className:"rmc-display text-4xl",children:s.name})]})]},s.name))}),a.jsx("div",{className:"mt-8",children:a.jsxs(mn,{to:"/communities",className:"rmc-btn rmc-btn-blue",children:["All communities ",a.jsx(ra,{className:"h-4 w-4"})]})})]}),r&&i.length>0&&a.jsx("section",{className:"rmc-bg-paper",children:a.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[a.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[a.jsx(jL,{eyebrow:"Our people",title:"Meet a few of our agents."}),a.jsxs(mn,{to:"/agents",className:"rmc-btn mb-12",children:["All ",n.length," agents ",a.jsx(ra,{className:"h-4 w-4"})]})]}),a.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:i.map(s=>a.jsx(JM,{a:s},s.user_id))})]})}),r&&a.jsxs("section",{className:"relative overflow-hidden rmc-bg-blue",children:[a.jsx("img",{src:o1.url,alt:"","aria-hidden":!0,className:"rmc-balloon left-[6%] top-10 h-32 w-auto opacity-30"}),a.jsxs("div",{className:"relative mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-8 md:grid-cols-[1fr_auto] items-center",children:[a.jsxs("div",{children:[a.jsx("p",{className:"rmc-eyebrow mb-3 opacity-80",children:"Careers"}),a.jsx("p",{className:"rmc-display text-4xl md:text-5xl max-w-2xl",children:"Grow your business with the most recognized name in real estate."})]}),a.jsxs(mn,{to:"/join",className:"rmc-btn",children:["Join our team ",a.jsx(ra,{className:"h-4 w-4"})]})]})]}),a.jsx(lx,{siteConfig:t})]})}function tLt({siteConfig:t}){const e=Am(),{data:r=[],isLoading:n}=QW(e.mode==="agent"?null:t.id),[i,o]=I.useState(""),[c,s]=I.useState(""),f=I.useMemo(()=>r.filter(p=>{const y=(p.full_name||"").toLowerCase();return!(i&&!y.includes(i.toLowerCase())&&!(p.team_name||"").toLowerCase().includes(i.toLowerCase())||c&&!(y.split(" ").pop()||"").startsWith(c.toLowerCase()))}),[r,i,c]);return e.mode==="agent"?a.jsx(li,{to:"/about",replace:!0}):e.mode==="team"?a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:`Our Team | ${e.name}`,description:`Meet the REALTORS® of ${e.name}, RE/MAX Creative Realty.`}),a.jsx(Q_,{eyebrow:"Our team",title:`Meet the ${e.name}.`,intro:"Local REALTORS® who work together for you.",image:Pl.lexington}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[a.jsx("p",{className:"text-sm rmc-soft",children:n?"Loading team…":`${r.length} team member${r.length===1?"":"s"}`}),a.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:r.map(p=>a.jsx(JM,{a:p},p.user_id))})]}),a.jsx(lx,{siteConfig:t,heading:"Talk to our team."})]}):a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:"Our Agents | RE/MAX Creative Realty",description:"Find a RE/MAX Creative Realty REALTOR® in Lexington, Georgetown or Winchester, Kentucky."}),a.jsx(Q_,{eyebrow:"Agent directory",title:"Find your agent.",intro:`${r.length||"70+"} REALTORS® across Lexington, Georgetown and Winchester.`,image:Pl.lexington}),a.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[a.jsxs("div",{className:"rmc-card p-4 flex flex-col md:flex-row gap-4 md:items-center",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(hd,{className:"h-4 w-4 absolute left-4 top-1/2 -translate-y-1/2 rmc-soft"}),a.jsx("input",{className:"rmc-input !pl-11",placeholder:"Search by name or team",value:i,onChange:p=>o(p.target.value),"aria-label":"Search agents"})]}),a.jsx("div",{className:"flex flex-wrap gap-1","aria-label":"Filter by last name",children:["",..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")].map(p=>a.jsx("button",{onClick:()=>s(p),className:`h-8 min-w-8 px-2 rounded-full text-xs font-semibold ${c===p?"rmc-bg-blue":"hover:rmc-bg-mist"}`,children:p||"All"},p||"all"))})]}),a.jsx("p",{className:"mt-6 text-sm rmc-soft",children:n?"Loading agents…":`${f.length} agent${f.length===1?"":"s"}`}),a.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:f.map(p=>a.jsx(JM,{a:p},p.user_id))})]}),a.jsx(lx,{siteConfig:t,heading:"Not sure who to call?"})]})}function rLt({siteConfig:t}){return a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:"Offices | RE/MAX Creative Realty",description:"Visit RE/MAX Creative Realty in Lexington, Georgetown or Winchester, Kentucky."}),a.jsx(Q_,{eyebrow:"Visit us",title:"Three offices. One team.",intro:`Call any office at ${Wc.phone}.`,image:Pl.georgetown}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 space-y-10",children:Pk.map((e,r)=>a.jsxs("div",{className:`rmc-card overflow-hidden grid md:grid-cols-2 ${r%2?"md:[&>*:first-child]:order-2":""}`,children:[a.jsx("div",{className:"h-72 md:h-auto overflow-hidden",children:a.jsx("img",{src:Pl[e.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),a.jsxs("div",{className:"p-10 md:p-14",children:[a.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:r===0?"Main office":"Branch office"}),a.jsx("h2",{className:"rmc-display text-5xl",children:e.name}),a.jsx("p",{className:"mt-4 rmc-soft",children:e.note}),a.jsxs("div",{className:"mt-6 space-y-2 text-sm",children:[a.jsxs("p",{className:"flex gap-2",children:[a.jsx(qs,{className:"h-4 w-4 rmc-blue mt-0.5"}),e.address,", ",e.cityLine]}),a.jsxs("p",{className:"flex gap-2",children:[a.jsx(Rl,{className:"h-4 w-4 rmc-blue mt-0.5"}),e.hours]}),a.jsxs("p",{className:"flex gap-2",children:[a.jsx(ai,{className:"h-4 w-4 rmc-blue mt-0.5"}),a.jsx("a",{href:Wc.phoneHref,children:Wc.phone})]})]}),a.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[a.jsx("a",{href:e.map,target:"_blank",rel:"noreferrer",className:"rmc-btn",children:"Get directions"}),a.jsxs(mn,{to:Rk(e.name),className:"rmc-btn rmc-btn-blue",children:["Homes in ",e.name]})]})]})]},e.key))}),a.jsx(lx,{siteConfig:t})]})}function nLt({siteConfig:t}){return HF(),a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:"Central Kentucky Communities | RE/MAX Creative Realty",description:"Explore homes for sale in Lexington, Georgetown, Winchester, Nicholasville, Versailles, Richmond, Frankfort and Lawrenceburg."}),a.jsx(Q_,{eyebrow:"Communities",title:"Explore the Bluegrass.",intro:"Neighborhood guides, market snapshots and every listing in the towns we serve.",image:Pl.hero}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:QM.map(e=>a.jsxs(mn,{to:Rk(e.name),className:"rmc-reveal rmc-card overflow-hidden group",children:[a.jsx("div",{className:"h-56 overflow-hidden rmc-zoom",children:a.jsx("img",{src:Pl[e.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),a.jsxs("div",{className:"p-6",children:[a.jsx("p",{className:"rmc-eyebrow rmc-red",children:e.county}),a.jsx("p",{className:"rmc-display text-3xl mt-1",children:e.name}),a.jsx("p",{className:"mt-2 text-sm rmc-soft",children:e.blurb}),a.jsxs("span",{className:"mt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Homes for sale ",a.jsx(ra,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},e.name))}),a.jsx(lx,{siteConfig:t,defaultIntent:"relocate",heading:"Moving to Central Kentucky?"})]})}function WF({siteConfig:t,seo:e,hero:r,points:n,intent:i,heading:o,children:c}){HF();const s=Am(),f=s.mode==="brokerage"?"RE/MAX Creative Realty":`${s.name} | RE/MAX Creative Realty`;return a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:e[0].replace("RE/MAX Creative Realty",f),description:e[1]}),a.jsx(Q_,{...r}),a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 md:grid-cols-3",children:n.map(([p,y],_)=>a.jsxs("div",{className:"rmc-reveal rmc-card p-8",children:[a.jsx("span",{className:`inline-flex h-10 w-10 items-center justify-center rounded-full text-sm font-bold ${_%2?"rmc-bg-blue":"bg-[hsl(var(--rmc-red))] text-[hsl(var(--rmc-paper))]"}`,children:_+1}),a.jsx("p",{className:"rmc-display text-2xl mt-5",children:p}),a.jsx("p",{className:"mt-2 rmc-soft text-sm leading-relaxed",children:y})]},p))}),c,a.jsx(lx,{siteConfig:t,defaultIntent:i,heading:o})]})}function iLt({siteConfig:t}){return a.jsx(WF,{siteConfig:t,intent:"buy",heading:"Ready to start looking?",seo:["Buy a Home in Central Kentucky | RE/MAX Creative Realty","Search every Central Kentucky listing and buy with a local RE/MAX Creative agent."],hero:{eyebrow:"Buying",title:"Find the one.",intro:"Every MLS listing, instant alerts and an agent who knows the neighborhood.",image:Pl.interior},points:[["Search everything","Every home listed in Imagine MLS, updated throughout the day, with saved searches and alerts."],["Local guidance","Schools, commutes, farms and neighborhoods — from agents who live here."],["Negotiate with confidence","Offer strategy and a QSC service guarantee from the first showing to closing."]],children:a.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-20",children:a.jsx(a1,{siteConfig:t,accentColor:"#DC1C2E",cities:Lq,mode:"new_listings",sectionTitle:"Newest Listings",count:12})})})}function sLt({siteConfig:t}){return a.jsx(WF,{siteConfig:t,intent:"value",heading:"What’s your home worth?",seo:["Sell Your Home in Central Kentucky | RE/MAX Creative Realty","Get a free home value and sell with RE/MAX Creative Realty."],hero:{eyebrow:"Selling",title:"Sell smarter. Net more.",intro:"Pricing from live MLS data, and marketing with the reach of the RE/MAX network.",image:Pl.winchester},points:[["Price it right","A comparative market analysis built on today’s sales, not last quarter’s headlines."],["Market it everywhere","Professional photography, MLS syndication and the global RE/MAX network."],["Close with care","Offer review, negotiation and a team that sees every detail through to closing."]]})}function aLt({siteConfig:t}){var n;const e=Am(),{data:r=[]}=QW(e.mode==="team"?t.id:null);if(HF(),e.mode!=="brokerage"){const i=(e.bio||"").split(/\n\s*\n/).map(o=>o.trim()).filter(Boolean);return a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:`About ${e.name} | RE/MAX Creative Realty`,description:`Get to know ${e.name} of RE/MAX Creative Realty, serving Central Kentucky.`}),a.jsx(Q_,{eyebrow:e.mode==="team"?"About the team":`About ${e.first}`,title:e.name,intro:`${e.title} · RE/MAX Creative Realty`,image:((n=t.themeConfig)==null?void 0:n.heroImageUrl)||Pl.hero}),a.jsx(C2e,{siteConfig:t,roster:r}),i.length>2&&e.mode==="agent"&&a.jsx("section",{className:"mx-auto max-w-3xl px-5 lg:px-10 pb-20 space-y-4 text-lg rmc-soft",children:i.slice(2).map((o,c)=>a.jsx("p",{children:o},c))}),a.jsx(lx,{siteConfig:t,heading:"Let’s talk."})]})}return a.jsx(WF,{siteConfig:t,intent:"buy",heading:"Let’s talk.",seo:["About RE/MAX Creative Realty | Lexington, KY","Central Kentucky’s original RE/MAX brokerage, serving the Bluegrass since 1987."],hero:{eyebrow:"Our story",title:`Rooted in the Bluegrass since ${Wc.founded}.`,intro:"Central Kentucky’s original RE/MAX firm — three offices and 70+ REALTORS® ready to work for you.",image:Pl.hero},points:[["Local since 1987","For more than 35 years we have helped families buy, sell and invest across Central Kentucky."],["Quality Service Certified","Our agents earn the QSC designation and put their service guarantee in writing."],["Giving back","Our agents support Children’s Miracle Network, Habitat for Humanity, CASA and many more causes close to home."]]})}function oLt({siteConfig:t}){return Am().mode!=="brokerage"?a.jsx(li,{to:"/contact",replace:!0}):a.jsx(WF,{siteConfig:t,intent:"join",heading:"Let’s talk about your career.",seo:["Join RE/MAX Creative Realty | Real Estate Careers in Kentucky","Grow your real estate career with Central Kentucky’s original RE/MAX brokerage."],hero:{eyebrow:"Careers",title:"Build your business here.",intro:"The most recognized brand in real estate, with local leadership in your corner.",image:Pl.georgetown},points:[["A global brand","The RE/MAX balloon opens doors — and referrals — around the world."],["Three offices","Work from Lexington, Georgetown or Winchester with real support staff."],["Modern tools","Your own IDX website, CRM, marketing and video tools through LevelUp."]]})}function lLt({siteConfig:t}){const e=Am(),r=e.mode==="brokerage";return a.jsxs(a.Fragment,{children:[a.jsx(ox,{title:`Contact ${e.name}`,description:`Call ${e.phone} or send a message to ${e.name}.`}),a.jsx(Q_,{eyebrow:"Contact",title:e.mode==="agent"?"Let’s talk.":"We’re here to help.",intro:r?`Call ${e.phone} · toll-free ${Wc.tollFree}`:`Call ${e.phone}${e.email?` · ${e.email}`:""}`,image:Pl.lexington}),a.jsx(lx,{siteConfig:t,heading:"Send us a message."})]})}function cLt({children:t}){return a.jsx("div",{className:"rmc-bg-paper min-h-[70vh]",children:t})}function JW({open:t,mode:e,siteConfig:r,onComplete:n,onSkip:i,theme:o="default",accentColor:c}){var Pe;const{signUp:s,signIn:f}=hT(),[p,y]=I.useState(!1),[_,T]=I.useState(""),[E,k]=I.useState(""),[P,R]=I.useState(""),[D,M]=I.useState(!1),[B,V]=I.useState(""),[G,W]=I.useState(!1),[Z,Q]=I.useState(!1),[re,se]=I.useState(!1),ue=e==="required",_e=o==="luxury",we=c||(_e?"#c9a96e":"#2563eb"),Ce=((Pe=r.agent)==null?void 0:Pe.full_name)||"the agent",Me={borderColor:`${we}66`,"--tw-ring-color":`${we}66`},Ae=async Ie=>{if(Ie.preventDefault(),V(""),!E.trim()||!p&&!P.trim()){V("Email and phone number are required.");return}if(!p&&!_.trim()){V("Name is required.");return}const Se=P.replace(/\D/g,"");if(!p&&Se.length<7){V("Please enter a valid phone number.");return}M(!0);try{const ve=p?await f(E,P):await s({name:_,email:E,phone:P});ve!=null&&ve.instant?Q(!0):(se(!p&&!!(ve!=null&&ve.existing)),W(!0))}catch(ve){const We=String((ve==null?void 0:ve.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)}},be="w-full",me=_e?Me:void 0;return a.jsx(io,{open:t,onOpenChange:ue?void 0:Ie=>{Ie||i()},children:a.jsxs(Ua,{className:"sm:max-w-md bg-background text-foreground",onPointerDownOutside:ue?Ie=>Ie.preventDefault():void 0,onEscapeKeyDown:ue?Ie=>Ie.preventDefault():void 0,children:[a.jsxs(ml,{children:[a.jsx(Ko,{className:"text-xl",style:_e?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:p?"Welcome Back":ue?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),a.jsx(gd,{children:p?"Receive a secure sign-in link by email. No password needed.":`Create a free account to save favorites, get alerts, and connect with ${Ce}.`})]}),Z?a.jsxs("div",{className:"space-y-4 py-4",children:[a.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."]}),a.jsx(zt,{className:"w-full",onClick:n,children:"Start browsing"})]}):G?a.jsxs("div",{className:"space-y-4 py-4",children:[a.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."}),a.jsx(zt,{className:"w-full",onClick:n,children:"Continue browsing"})]}):a.jsxs("form",{onSubmit:Ae,className:"space-y-3 mt-2",children:[!p&&a.jsx($r,{type:"text",required:!0,placeholder:"Your name",value:_,onChange:Ie=>T(Ie.target.value),className:be,style:me}),a.jsx($r,{type:"email",required:!0,placeholder:"Email address",value:E,onChange:Ie=>k(Ie.target.value),className:be,style:me}),!p&&a.jsx("div",{children:a.jsx($r,{type:"tel",required:!0,placeholder:"Phone number",value:P,onChange:Ie=>R(Ie.target.value),className:be,style:me})}),B&&a.jsx("p",{className:"text-destructive text-sm",children:B}),a.jsx(zt,{type:"submit",disabled:D,className:"w-full",children:D?p?"Sending link...":"Creating account...":p?"Email Sign-In Link":"Create Account"}),a.jsx(zt,{variant:"ghost",type:"button",onClick:()=>{y(!p),V("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",children:p?"Don't have an account? Sign up":"Already have an account? Sign in"}),!ue&&!p&&a.jsx(zt,{variant:"ghost",type:"button",onClick:i,className:"w-full text-muted-foreground",children:"Skip for now"})]}),a.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 I2e=[{tab:"saved",label:"Saved Homes",icon:um},{tab:"searches",label:"Saved Searches & Alerts",icon:hd},{tab:"viewed",label:"Recently Viewed",icon:CO},{tab:"profile",label:"Profile & Preferences",icon:s9}];function N2e(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",o=(r?r.split(" ").map(c=>c[0]).slice(0,2).join(""):n[0]||"A").toUpperCase();return{name:r||i,first:i,email:n,initials:o}}function eK({triggerClassName:t,avatarClassName:e,showSaved:r=!0,savedClassName:n}){const{user:i,profile:o,signOut:c}=hT(),s=Gs();if(!i)return null;const f=N2e(o,i.email);return a.jsxs("div",{className:"flex items-center gap-1",children:[r&&a.jsxs(mn,{to:"/account?tab=saved",className:n,"aria-label":"Saved homes",children:[a.jsx(um,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),a.jsxs(mC,{modal:!1,children:[a.jsxs(pC,{className:t,"aria-label":"Your account",children:[a.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}),a.jsx("span",{className:"hidden max-w-[8rem] truncate lg:inline",children:f.first}),a.jsx(wc,{className:"h-3.5 w-3.5 opacity-70"})]}),a.jsxs(qS,{align:"end",className:"z-[80] w-64",children:[a.jsxs(Oye,{className:"font-normal",children:[a.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed in as"}),a.jsx("p",{className:"truncate text-sm font-semibold",children:f.name}),f.email&&a.jsx("p",{className:"truncate text-xs text-muted-foreground",children:f.email})]}),a.jsx(Dj,{}),I2e.map(({tab:p,label:y,icon:_})=>a.jsxs(Eu,{onSelect:()=>s(`/account?tab=${p}`),className:"cursor-pointer gap-2",children:[a.jsx(_,{className:"h-4 w-4"}),y]},p)),a.jsx(Dj,{}),a.jsxs(Eu,{onSelect:async()=>{await c(),s("/")},className:"cursor-pointer gap-2",children:[a.jsx(NO,{className:"h-4 w-4"}),"Sign Out"]})]})]})]})}function tK({onNavigate:t,dark:e}){const{user:r,profile:n,signOut:i}=hT(),o=Gs();if(!r)return null;const c=N2e(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 a.jsxs("div",{className:`mt-3 rounded-xl border p-2 ${e?"border-white/15":"border-gray-200"}`,children:[a.jsxs("div",{className:"flex items-center gap-3 px-2 py-2",children:[a.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}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:`truncate text-sm font-semibold ${e?"text-white":"text-gray-900"}`,children:c.name}),c.email&&a.jsx("p",{className:`truncate text-xs ${e?"text-white/50":"text-gray-500"}`,children:c.email})]})]}),I2e.map(({tab:f,label:p,icon:y})=>a.jsxs("button",{className:s,onClick:()=>{o(`/account?tab=${f}`),t()},children:[a.jsx(y,{className:"h-4 w-4"}),p]},f)),a.jsxs("button",{className:s,onClick:async()=>{await i(),t(),o("/")},children:[a.jsx(NO,{className:"h-4 w-4"}),"Sign Out"]})]})}function rK(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 uLt(t,e){const r=rK(t,e),n=(e||"").trim(),i=[n,n?`${n} Realtor`:"",(t||"").trim()].map(o=>o.trim()).filter(o=>o&&o.toLowerCase()!==r.toLowerCase());return Array.from(new Set(i))}function nK({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",o=!ax(t),s=(r.areas_served||"").split(/,|;|\|/).map(Q=>Q.trim()).filter(Boolean),f=s[0]||"",[p,y]=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||[],k=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,P=[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:"$$",...P.length&&{sameAs:P},...t.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:t.brokerageLegalName,...t.brokerageLicenseNumber&&{identifier:t.brokerageLicenseNumber}}},...t.agentLicenseNumber&&{identifier:t.agentLicenseNumber},...p&&{address:{"@type":"PostalAddress",addressLocality:p,...y&&{addressRegion:y},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}}}})},...k&&{aggregateRating:k},...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"}},...P.length&&{sameAs:P},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=rK(t.siteTitle,r.full_name),V=uLt(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`},...o&&{potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}}},W=[...o?[{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"},...o?[{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"}]:[],{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${r.full_name}${t.brokerageLegalName?` and ${t.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],Z={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:W.map((Q,re)=>({"@type":"SiteNavigationElement",position:re+1,name:Q.name,description:Q.description,url:`${n}${Q.path}`}))};return a.jsxs(Wo,{children:[a.jsx("script",{type:"application/ld+json",children:JSON.stringify(D)}),a.jsx("script",{type:"application/ld+json",children:JSON.stringify(M)}),a.jsx("script",{type:"application/ld+json",children:JSON.stringify(G)}),a.jsx("script",{type:"application/ld+json",children:JSON.stringify(Z)})]})}function q9t({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,o)=>({"@type":"ListItem",position:o+1,name:i.name,item:`${r}${i.path}`}))};return a.jsx(Wo,{children:a.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function G9t({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 a.jsx(Wo,{children:a.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function dLt({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 a.jsx(Wo,{children:a.jsx("script",{type:"application/ld+json",children:JSON.stringify(e)})})}function H9t({title:t,description:e,publishedAt:r,modifiedAt:n,imageUrl:i,slug:o,siteConfig:c}){const s=c.customDomain?`https://${c.customDomain}`:`https://${c.subdomainSlug}.thelocalmove.com`,f=c.agent,p={"@context":"https://schema.org","@type":"Article",headline:t,description:e,url:`${s}/blog/${o}`,datePublished:r,dateModified:n||r,...i&&{image:i},author:f?{"@type":"Person",name:f.full_name,url:s}:void 0,publisher:{"@type":"Organization",name:c.siteTitle||(f==null?void 0:f.full_name)||"Agent",url:s}};return a.jsx(Wo,{children:a.jsx("script",{type:"application/ld+json",children:JSON.stringify(p)})})}function W9t({videoId:t,title:e,description:r,thumbnailUrl:n,uploadDate:i,durationSeconds:o}){const c=o&&o>0?o: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 a.jsx(Wo,{children:a.jsx("script",{type:"application/ld+json",children:JSON.stringify(f)})})}const hLt="Home Valuation";function fLt(t){return(t.valuationLabel||"").trim()||hLt}function mLt(t){return t.split(" ").map(e=>e.length>1&&e===e.toUpperCase()?e:e.toLowerCase()).join(" ")}function iK({siteConfig:t}){var R;const e=Bi(),r=t.agent,n=/faq|frequently-asked/i.test(e.pathname);if(!r||!n)return null;const i=r.full_name,o=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,p=r.phone||"",y=r.email,_=t.agentLicenseNumber,T=!ax(t),E=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],k=[...new Set(E.map(D=>D.toUpperCase()))],P=[{question:`Who is ${i}?`,answer:`${i} is a ${r.title||"REALTOR®"} with ${o}${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 ${p?`phone at ${p}, `:""}email at ${y}, or by booking a consultation directly through this website.`},...k.length?[{question:`What real estate designations does ${i} hold?`,answer:`${i} holds the following professional designations: ${k.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 ${o}.`}]:[],...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 ${mLt(fLt(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 a.jsx(dLt,{faqs:P})}const Nle="ls_visitor_geo",pLt=1e3*60*60,F$="lu_lc_attrib_v1",gLt=1e3*60*60*24*90;function yLt(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 xLt(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 _Lt(){try{const t=localStorage.getItem(Nle);if(t){const e=JSON.parse(t);if(Date.now()-e.ts{o.current||(o.current=!0,_Lt().then(c=>{i.current=c}))},[]),I.useEffect(()=>{if(!(t!=null&&t.id))return;const c=r.pathname;if(c===n.current)return;n.current=c;const s=yLt(c),f=xLt(c,s),p=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,y=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(F$,JSON.stringify({contact_id:E,ts:Date.now()}))}catch{}return E}const k=T.get("lc");if(k&&/^[0-9a-f-]{36}$/i.test(k)){const{data:P}=await Re.from("listing_email_recipients").select("contact_id").eq("id",k).maybeSingle(),R=P==null?void 0:P.contact_id;if(R){try{localStorage.setItem(F$,JSON.stringify({contact_id:R,ts:Date.now()}))}catch{}return R}}try{const P=localStorage.getItem(F$);if(P){const R=JSON.parse(P);if(R!=null&&R.contact_id&&Date.now()-(R.ts||0){Re.from("lead_site_page_views").insert({lead_site_id:t.id,page_type:s,page_path:c,page_title:f,visitor_fingerprint:p,auth_user_id:e||null,contact_id:T,visitor_city:(y==null?void 0:y.city)||null,visitor_region:(y==null?void 0:y.region)||null,visitor_country:(y==null?void 0:y.country)||null,visitor_lat:(y==null?void 0:y.lat)||null,visitor_lng:(y==null?void 0:y.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 vLt=3e4;function aK(t,e){const r=Bi(),n=I.useRef(null),i=I.useRef(null),o=I.useRef(0),c=r.pathname,s=bLt(c),f=wLt(c,s),p=s==="listing"&&c.split("/listing/")[1]||null;I.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;s==="listing"&&(o.current+=1);const y=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,_=async()=>{const{data:T,error:E}=await Re.from("lead_site_active_visitors").upsert({lead_site_id:t.id,auth_user_id:e,visitor_fingerprint:y,current_page_path:c,current_page_title:f,current_mls_number:p,last_seen_at:new Date().toISOString(),listing_views_count:o.current},{onConflict:"lead_site_id,session_key"}).select("id, notified_agent").single();!E&&T&&(n.current=T.id,o.current>=2&&!T.notified_agent&&Re.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(_,vLt),()=>{i.current&&clearInterval(i.current)}},[t==null?void 0:t.id,e,c]),I.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;const y=()=>{n.current&&Re.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[t==null?void 0:t.id,e])}function bLt(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 wLt(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 pn=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},SLt=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=TLt},TLt=Number.MAX_SAFE_INTEGER||9007199254740991;let Dn=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}({}),Jt=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}({}),je=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 Hi={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Tn={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ow{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 ELt{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 ow(e),this.fast_=new ow(r),this.defaultTTFB_=i,this.ttfb_=new ow(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:o}=this;n.halfLife!==e&&(this.slow_=new ow(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new ow(r,i.getEstimate(),i.getTotalWeight())),o.halfLife!==e&&(this.ttfb_=new ow(e,o.getEstimate(),o.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,o=n/i;this.fast_.sample(i,o),this.slow_.sample(i,o)}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 ALt(t,e,r){return(e=kLt(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xs(){return Xs=Object.assign?Object.assign.bind():function(t){for(var e=1;e`):cy}function Rle(t,e,r){return e[t]?e[t].bind(e):ILt(t,r)}const Mq=Dq();function NLt(t,e,r){const n=Dq();if(typeof console=="object"&&t===!0||typeof t=="object"){const i=["debug","log","info","warn","error"];i.forEach(o=>{n[o]=Rle(o,t,r)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return Dq()}i.forEach(o=>{Mq[o]=Rle(o,t)})}else Xs(Mq,n);return n}const Us=Mq;function cx(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function PLt(t){return typeof self<"u"&&t===self.ManagedMediaSource}function P2e(t,e){const r=Object.keys(t),n=Object.keys(e),i=r.length,o=n.length;return!i||!o||i===o&&!r.some(c=>n.indexOf(c)===-1)}function cd(t,e=!1){if(typeof TextDecoder<"u"){const p=new TextDecoder("utf-8").decode(t);if(e){const y=p.indexOf("\0");return y!==-1?p.substring(0,y):p}return p.replace(/\0/g,"")}const r=t.length;let n,i,o,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++],o=t[s++],c+=String.fromCharCode((n&15)<<12|(i&63)<<6|(o&63)<<0);break}}return c}function Kl(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(!pn(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return jo(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,o,c=!1){const{elementaryStreams:s}=this,f=s[e];if(!f){s[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:o,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,o)}}class DLt extends L2e{constructor(e,r,n,i,o){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,o),o&&(this.fragOffset=o.fragOffset+o.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 D2e(t,e){const r=Object.getPrototypeOf(t);if(r){const n=Object.getOwnPropertyDescriptor(r,e);return n||D2e(r,e)}}function MLt(t,e){const r=D2e(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}const Dle=Math.pow(2,32)-1,OLt=[].push,M2e={video:1,audio:2,id3:3,text:4};function al(t){return String.fromCharCode.apply(null,t)}function O2e(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function yi(t,e){const r=F2e(t,e);return r<0?4294967296+r:r}function Mle(t,e){let r=yi(t,e);return r*=Math.pow(2,32),r+=yi(t,e+4),r}function F2e(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function FLt(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 qi(t,e){const r=[];if(!e.length)return r;const n=t.byteLength;for(let i=0;i1?i+o:n;if(c===e[0])if(e.length===1)r.push(t.subarray(i+8,s));else{const f=qi(t.subarray(i+8,s),e.slice(1));f.length&&OLt.apply(r,f)}i=s}return r}function BLt(t){const e=[],r=t[0];let n=8;const i=yi(t,n);n+=4;let o=0,c=0;r===0?(o=yi(t,n),c=yi(t,n+4),n+=8):(o=Mle(t,n),c=Mle(t,n+8),n+=16),n+=2;let s=t.length+c;const f=O2e(t,n);n+=2;for(let p=0;p>>31===1)return Us.warn("SIDX has hierarchical references (not supported)"),null;const k=yi(t,y);y+=4,e.push({referenceSize:T,subsegmentDuration:k,info:{duration:k/i,start:s,end:s+T-1}}),s+=T,y+=4,n=y}return{earliestPresentationTime:o,timescale:i,version:r,referencesCount:f,references:e}}function B2e(t){const e=[],r=qi(t,["moov","trak"]);for(let i=0;i{const o=yi(i,4),c=e[o];c&&(c.default={duration:yi(i,12),flags:yi(i,20)})}),e}function zLt(t){const e=t.subarray(8),r=e.subarray(86),n=al(e.subarray(4,8));let i=n,o;const c=n==="enca"||n==="encv";if(c){const p=qi(e,[n])[0].subarray(n==="enca"?28:78);qi(p,["sinf"]).forEach(_=>{const T=qi(_,["schm"])[0];if(T){const E=al(T.subarray(4,8));if(E==="cbcs"||E==="cenc"){const k=qi(_,["frma"])[0];k&&(i=al(k))}}})}const s=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const f=qi(r,["avcC"])[0];f&&f.length>3&&(i+="."+TR(f[1])+TR(f[2])+TR(f[3]),o=SR(s==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const f=qi(e,[n])[0],p=qi(f.subarray(28),["esds"])[0];if(p&&p.length>7){let y=4;if(p[y++]!==3)break;y=$$(p,y),y+=2;const _=p[y++];if(_&128&&(y+=2),_&64&&(y+=p[y++]),p[y++]!==4)break;y=$$(p,y);const T=p[y++];if(T===64)i+="."+TR(T);else break;if(y+=12,p[y++]!==5)break;y=$$(p,y);const E=p[y++];let k=(E&248)>>3;k===31&&(k+=1+((E&7)<<3)+((p[y]&224)>>5)),i+="."+k}break}case"hvc1":case"hev1":{const f=qi(r,["hvcC"])[0];if(f&&f.length>12){const p=f[1],y=["","A","B","C"][p>>6],_=p&31,T=yi(f,2),E=(p&32)>>5?"H":"L",k=f[12],P=f.subarray(6,12);i+="."+y+_,i+="."+$Lt(T).toString(16).toUpperCase(),i+="."+E+k;let R="";for(let D=P.length;D--;){const M=P[D];(M||R)&&(R="."+M.toString(16).toUpperCase()+R)}i+=R}o=SR(s=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=SR(i,r)||i;break}case"vp09":{const f=qi(r,["vpcC"])[0];if(f&&f.length>6){const p=f[4],y=f[5],_=f[6]>>4&15;i+="."+$f(p)+"."+$f(y)+"."+$f(_)}break}case"av01":{const f=qi(r,["av1C"])[0];if(f&&f.length>2){const p=f[1]>>>5,y=f[1]&31,_=f[2]>>>7?"H":"M",T=(f[2]&64)>>6,E=(f[2]&32)>>5,k=p===2&&T?E?12:10:T?10:8,P=(f[2]&16)>>4,R=(f[2]&8)>>3,D=(f[2]&4)>>2,M=f[2]&3;i+="."+p+"."+$f(y)+_+"."+$f(k)+"."+P+"."+R+D+M+"."+$f(1)+"."+$f(1)+"."+$f(1)+"."+0,o=SR("dav1",r)}break}}return{codec:i,encrypted:c,supplemental:o}}function SR(t,e){const r=qi(e,["dvvC"]),n=r.length?r[0]:qi(e,["dvcC"])[0];if(n){const i=n[2]>>1&127,o=n[2]<<5&32|n[3]>>3&31;return t+"."+$f(i)+"."+$f(o)}}function $Lt(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}function $$(t,e){const r=e+5;for(;t[e++]&128&&e{const o=n.subarray(8,24);o.some(c=>c!==0)||(Us.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Kl(o)} -> ${Kl(r)}`),n.set(r,8))})}function VLt(t){const e=[];return z2e(t,r=>e.push(r.subarray(8,24))),e}function z2e(t,e){qi(t,["moov","trak"]).forEach(n=>{const i=qi(n,["mdia","minf","stbl","stsd"])[0];if(!i)return;const o=i.subarray(8);let c=qi(o,["enca"]);const s=c.length>0;s||(c=qi(o,["encv"])),c.forEach(f=>{const p=s?f.subarray(28):f.subarray(78);qi(p,["sinf"]).forEach(_=>{const T=$2e(_);T&&e(T,s)})})})}function $2e(t){const e=qi(t,["schm"])[0];if(e){const r=al(e.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=qi(t,["schi","tenc"])[0];if(n)return n}}}function qLt(t,e,r){const n={},i=qi(t,["moof","traf"]);for(let o=0;on[o].duration)){let o=1/0,c=0;const s=qi(t,["sidx"]);for(let f=0;f_+T.info.duration||0,0);c=Math.max(c,y+p.earliestPresentationTime/p.timescale)}}c&&pn(c)&&Object.keys(n).forEach(f=>{n[f].duration||(n[f].duration=c*n[f].timescale-n[f].start)})}return n}function GLt(t){const e={valid:null,remainder:null},r=qi(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 oh(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function Ole(t,e){const r=[],n=e.samples,i=e.timescale,o=e.id;let c=!1;return qi(n,["moof"]).map(f=>{const p=f.byteOffset-8;qi(f,["traf"]).map(_=>{const T=qi(_,["tfdt"]).map(E=>{const k=E[0];let P=yi(E,4);return k===1&&(P*=Math.pow(2,32),P+=yi(E,8)),P/i})[0];return T!==void 0&&(t=T),qi(_,["tfhd"]).map(E=>{const k=yi(E,4),P=yi(E,0)&16777215,R=(P&1)!==0,D=(P&2)!==0,M=(P&8)!==0;let B=0;const V=(P&16)!==0;let G=0;const W=(P&32)!==0;let Z=8;k===o&&(R&&(Z+=8),D&&(Z+=4),M&&(B=yi(E,Z),Z+=4),V&&(G=yi(E,Z),Z+=4),W&&(Z+=4),e.type==="video"&&(c=KF(e.codec)),qi(_,["trun"]).map(Q=>{const re=Q[0],se=yi(Q,0)&16777215,ue=(se&1)!==0;let _e=0;const we=(se&4)!==0,Ce=(se&256)!==0;let Me=0;const Ae=(se&512)!==0;let be=0;const me=(se&1024)!==0,Pe=(se&2048)!==0;let Ie=0;const Se=yi(Q,4);let ve=8;ue&&(_e=yi(Q,ve),ve+=4),we&&(ve+=4);let We=_e+p;for(let rt=0;rt>1&63;return r===39||r===40}else return(e&31)===6}function cK(t,e,r,n){const i=U2e(t);let o=0;o+=e;let c=0,s=0,f=0;for(;o=i.length)break;f=i[o++],c+=f}while(f===255);s=0;do{if(o>=i.length)break;f=i[o++],s+=f}while(f===255);const p=i.length-o;let y=o;if(sp){Us.error(`Malformed SEI payload. ${s} is too small, only ${p} bytes left to parse.`);break}if(c===4){if(i[y++]===181){const T=O2e(i,y);if(y+=2,T===49){const E=yi(i,y);if(y+=4,E===1195456820){const k=i[y++];if(k===3){const P=i[y++],R=31&P,D=64&P,M=D?2+R*3:0,B=new Uint8Array(M);if(D){B[0]=P;for(let V=1;V16){const _=[];for(let k=0;k<16;k++){const P=i[y++].toString(16);_.push(P.length==1?"0"+P:P),(k===3||k===5||k===7||k===9)&&_.push("-")}const T=s-16,E=new Uint8Array(T);for(let k=0;k>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=n&255,o.set(t,4),i=0,n=8;i0?(o=new Uint8Array(4),e.length>0&&new DataView(o.buffer).setUint32(0,e.length,!1)):o=new Uint8Array;const c=new Uint8Array(4);return r.byteLength>0&&new DataView(c.buffer).setUint32(0,r.byteLength,!1),KLt([112,115,115,104],new Uint8Array([n,0,0,0]),t,o,i,c,r)}function ZLt(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>>24;if(o!==0&&o!==1)return{offset:r,size:e};const c=t.buffer,s=Kl(new Uint8Array(c,r+12,16));let f=null,p=null,y=0;if(o===0)y=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),wS={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 uK(t,e){const r=wS[e];return!!r&&!!r[t.slice(0,4)]}function Lk(t,e,r=!0){return!t.split(",").some(n=>!dK(n,e,r))}function dK(t,e,r=!0){var n;const i=cx(r);return(n=i==null?void 0:i.isTypeSupported(Dk(t,e)))!=null?n:!1}function Dk(t,e){return`${e}/mp4;codecs=${t}`}function Fle(t){if(t){const e=t.substring(0,4);return wS.video[e]}return 2}function eO(t){const e=V2e();return t.split(",").reduce((r,n)=>{const o=e&&KF(n)?9:wS.video[n];return o?(o*2+r)/(r?3:2):(wS.audio[n]+r)/(r?2:1)},0)}const U$={};function QLt(t,e=!0){if(U$[t])return U$[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let i=0;iQLt(r.toLowerCase(),e))}function eDt(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)&&(Ble(t,"audio")||Ble(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 Ble(t,e){return uK(t,e)&&dK(t,e)}function tDt(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 rDt(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 zle(t){const e=cx(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 Oq(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const nDt={supported:!0,powerEfficient:!0,smooth:!0},iDt={supported:!1,smooth:!1,powerEfficient:!1},q2e={supported:!0,configurations:[],decodingInfoResults:[nDt]};function G2e(t,e){return{supported:!1,configurations:e,decodingInfoResults:[iDt],error:t}}function sDt(t,e,r,n,i,o){const c=t.videoCodec,s=t.audioCodec?t.audioGroups:null,f=o==null?void 0:o.audioCodec,p=o==null?void 0:o.channels,y=p?parseInt(p):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 k=e.groups[E];if(!k)throw new Error(`Audio track group ${E} not found`);Object.keys(k.channels).forEach(P=>{T[P]=(T[P]||0)+k.channels[P]})}return T},{2:0})}catch{return!0}return c!==void 0&&(c.split(",").some(T=>KF(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))||!!_&&pn(y)&&Object.keys(_).some(T=>parseInt(T)>y)}function H2e(t,e,r,n={}){const i=t.videoCodec;if(!i&&!t.audioCodec||!r)return Promise.resolve(q2e);const o=[],c=aDt(t),s=c.length,f=oDt(t,e,s>0),p=f.length;for(let y=s||1*p||1;y--;){const _={type:"media-source"};if(s&&(_.video=c[y%s]),p){_.audio=f[y%p];const T=_.audio.bitrate;_.video&&T&&(_.video.bitrate-=T)}o.push(_)}if(i){const y=navigator.userAgent;if(i.split(",").some(_=>KF(_))&&V2e())return Promise.resolve(G2e(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${y})`),o))}return Promise.all(o.map(y=>{const _=cDt(y);return n[_]||(n[_]=r.decodingInfo(y))})).then(y=>({supported:!y.some(_=>!_.supported),configurations:o,decodingInfoResults:y})).catch(y=>({supported:!1,configurations:o,decodingInfoResults:[],error:y}))}function aDt(t){var e;const r=(e=t.videoCodec)==null?void 0:e.split(","),n=W2e(t),i=t.width||640,o=t.height||480,c=t.frameRate||30,s=t.videoRange.toLowerCase();return r?r.map(f=>{const p={contentType:Dk(rDt(f),"video"),width:i,height:o,bitrate:n,framerate:c};return s!=="sdr"&&(p.transferFunction=s),p}):[]}function oDt(t,e,r){var n;const i=(n=t.audioCodec)==null?void 0:n.split(","),o=W2e(t);return i&&t.audioGroups?t.audioGroups.reduce((c,s)=>{var f;const p=s?(f=e.groups[s])==null?void 0:f.tracks:null;return p?p.reduce((y,_)=>{if(_.groupId===s){const T=parseFloat(_.channels||"");i.forEach(E=>{const k={contentType:Dk(E,"audio"),bitrate:r?lDt(E,o):o};T&&(k.channels=""+T),y.push(k)})}return y},c):c},[]):[]}function lDt(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 W2e(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function cDt(t){let e="";const{audio:r,video:n}=t;if(n){const i=Oq(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=Oq(r.contentType);e+=`${n?"_":""}${i}_c${r.channels}`}return e}const Fq=["NONE","TYPE-0","TYPE-1",null];function uDt(t){return Fq.indexOf(t)>-1}const rO=["SDR","PQ","HLG"];function dDt(t){return!!t&&rO.indexOf(t)>-1}var CL={No:"",Yes:"YES",v2:"v2"};function $le(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 Vle(this._audioGroups,e)}hasSubtitleGroup(e){return Vle(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 Vle(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function hDt(){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 fDt(t,e){let r=!1,n=[];if(t&&(r=t!=="SDR",n=[t]),e){n=e.allowedVideoRanges||rO.slice(0);const i=n.join("")!=="SDR"&&!e.videoCodec;r=e.preferHDR!==void 0?e.preferHDR:i&&hDt(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const mDt=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}},sa=(t,e)=>JSON.stringify(t,mDt(e));function pDt(t,e,r,n,i){const o=Object.keys(t),c=n==null?void 0:n.channels,s=n==null?void 0:n.audioCodec,f=i==null?void 0:i.videoCodec,p=c&&parseInt(c)===2;let y=!1,_=!1,T=1/0,E=1/0,k=1/0,P=1/0,R=0,D=[];const{preferHDR:M,allowedVideoRanges:B}=fDt(e,i);for(let Q=o.length;Q--;){const re=t[o[Q]];y||(y=re.channels[2]>0),T=Math.min(T,re.minHeight),E=Math.min(E,re.minFramerate),k=Math.min(k,re.minBitrate),B.filter(ue=>re.videoRanges[ue]>0).length>0&&(_=!0)}T=pn(T)?T:0,E=pn(E)?E:0;const V=Math.max(1080,T),G=Math.max(30,E);k=pn(k)?k:r,r=Math.max(k,r),_||(e=void 0);const W=o.length>1;return{codecSet:o.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 Mf(re,`min bitrate of ${se.minBitrate} > current estimate of ${r}`),Q;if(!se.hasDefaultAudio)return Mf(re,"no renditions with default or auto-select sound found"),Q;if(s&&re.indexOf(s.substring(0,4))%5!==0)return Mf(re,`audio codec preference "${s}" not found`),Q;if(c&&!p){if(!se.channels[c])return Mf(re,`no renditions with ${c} channel sound found (channels options: ${Object.keys(se.channels)})`),Q}else if((!s||p)&&y&&se.channels[2]===0)return Mf(re,"no renditions with stereo sound found"),Q;if(se.minHeight>V)return Mf(re,`min resolution of ${se.minHeight} > maximum of ${V}`),Q;if(se.minFramerate>G)return Mf(re,`min framerate of ${se.minFramerate} > maximum of ${G}`),Q;if(!D.some(ue=>se.videoRanges[ue]>0))return Mf(re,`no variants with VIDEO-RANGE of ${sa(D)} found`),Q;if(f&&re.indexOf(f.substring(0,4))%5!==0)return Mf(re,`video codec preference "${f}" not found`),Q;if(se.maxScore=eO(Q)||se.fragmentError>t[Q].fragmentError)?Q:(P=se.minIndex,R=se.maxScore,re)},void 0),videoRanges:D,preferHDR:M,minFramerate:E,minBitrate:k,minIndex:P}}function Mf(t,e){Us.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function K2e(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 gDt(t,e,r,n){return t.slice(r,n+1).reduce((i,o,c)=>{if(!o.codecSet)return i;const s=o.audioGroups;let f=i[o.codecSet];f||(i[o.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,o.bitrate);const p=Math.min(o.height,o.width);return f.minHeight=Math.min(f.minHeight,p),f.minFramerate=Math.min(f.minFramerate,o.frameRate),f.minIndex=Math.min(f.minIndex,c),f.maxScore=Math.max(f.maxScore,o.score),f.fragmentError+=o.fragmentError,f.videoRanges[o.videoRange]=(f.videoRanges[o.videoRange]||0)+1,s&&s.forEach(y=>{if(!y)return;const _=e.groups[y];_&&(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 qle(t){if(!t)return t;const{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:o}=t;return{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:o}}function em(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 r_(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 _Dt(t,e,r,n,i){const o=e[n],s=e.reduce((T,E,k)=>{const P=E.uri;return(T[P]||(T[P]=[])).push(k),T},{})[o.uri];s.length>1&&(n=Math.max.apply(Math,s));const f=o.videoRange,p=o.frameRate,y=o.codecSet.substring(0,4),_=Gle(e,n,T=>{if(T.videoRange!==f||T.frameRate!==p||T.codecSet.substring(0,4)!==y)return!1;const E=T.audioGroups,k=r.filter(P=>!E||E.indexOf(P.groupId)!==-1);return em(t,k,i)>-1});return _>-1?_:Gle(e,n,T=>{const E=T.audioGroups,k=r.filter(P=>!E||E.indexOf(P.groupId)!==-1);return em(t,k,i)>-1})}function Gle(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:o,hls:c}=this,{autoLevelEnabled:s,media:f}=c;if(!i||!f)return;const p=performance.now(),y=o?o.stats:i.stats,_=o?o.duration:i.duration,T=p-y.loading.start,E=c.minAutoLevel,k=i.level,P=this._nextAutoLevel;if(y.aborted||y.loaded&&y.loaded===y.total||k<=E){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s)return;const R=P>-1&&P!==k,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=y.loading.first?y.loading.first-y.loading.start:-1,Z=y.loaded&&W>-1,Q=this.getBwEstimate(),re=c.levels,se=re[k],ue=Math.max(y.loaded,Math.round(_*(i.bitrate||se.averageBitrate)/8));let _e=Z?T-W:T;_e<1&&Z&&(_e=Math.min(T,y.loaded*8/Q));const we=Z?y.loaded*1e3/_e:0,Ce=B/1e3,Me=we?(ue-y.loaded)/we:ue*8/Q+Ce;if(Me<=G)return;const Ae=we?we*8:Q,be=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,me=this.hls.config.abrBandWidthUpFactor;let Pe=Number.POSITIVE_INFINITY,Ie;for(Ie=k-1;Ie>E;Ie--){const rt=re[Ie].maxBitrate,at=!re[Ie].details||be;if(Pe=this.getTimeToLoadFrag(Ce,Ae,_*rt,at),Pe=Me||Pe>_*10)return;Z?this.bwEstimator.sample(T-Math.min(B,W),y.loaded):this.bwEstimator.sampleTTFB(T);const Se=re[Ie].maxBitrate;this.getBwEstimate()*me>Se&&this.resetEstimator(Se);const ve=this.findBestLevel(Se,E,Ie,0,G,1,1);ve>-1&&(Ie=ve),this.warn(`Fragment ${i.sn}${o?" part "+o.index:""} of level ${k} is loading too slowly; Fragment duration: ${i.duration.toFixed(3)} Time to underbuffer: ${G.toFixed(3)} s Estimated load time for current fragment: ${Me.toFixed(3)} s Estimated load time for down switch fragment: ${Pe.toFixed(3)} s TTFB estimate: ${W|0} ms Current BW estimate: ${pn(Q)?Q|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${Ie} @ ${Se|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||Me>Pe*2?We():this.timer=self.setInterval(We,Pe*1e3),c.trigger(je.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:o,stats:y})},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 ELt(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.FRAG_LOADING,this.onFragLoading,this),e.on(je.FRAG_LOADED,this.onFragLoaded,this),e.on(je.FRAG_BUFFERED,this.onFragBuffered,this),e.on(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(je.LEVEL_LOADED,this.onLevelLoaded,this),e.on(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(je.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.FRAG_LOADING,this.onFragLoading,this),e.off(je.FRAG_LOADED,this.onFragLoaded,this),e.off(je.FRAG_BUFFERED,this.onFragBuffered,this),e.off(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(je.LEVEL_LOADED,this.onLevelLoaded,this),e.off(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(je.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(je.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 Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Jt.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:o}=this;if(n&&i&&n.sn===i.sn&&n.level===i.level){const c=performance.now(),s=o?o.stats:n.stats,f=c-s.loading.start,p=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&p>-1){const _=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(f-Math.min(_,p),s.loaded)}else this.bwEstimator.sampleTTFB(f)}break}}}getTimeToLoadFrag(e,r,n,i){const o=e+n/r,c=i?e+this.lastLevelLoadSec:0;return o+c}onLevelLoaded(e,r){const n=this.hls.config,{loading:i}=r.stats,o=i.end-i.first;pn(o)&&(this.lastLevelLoadSec=o/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===Tn.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 o=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)+o;c.loaded={bytes:s,duration:f},c.realBitrate=Math.round(8*s/f)}if(r.bitrateTest){const o={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered(je.FRAG_BUFFERED,o),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,r){const{frag:n,part:i}=r,o=i!=null&&i.stats.loaded?i.stats:n.stats;if(o.aborted||this.ignoreFragment(n))return;const c=o.parsing.end-o.loading.start-Math.min(o.loading.first-o.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(c,o.loaded),o.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=c/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Tn.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,o=this.findBestLevel(n,r,e,0,i,1,1);if(o>-1)return o;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 o=n&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const c=this.hls.levels;if(c.length>Math.max(e,o)&&c[e].loadError<=c[o].loadError)return e}return this._nextAutoLevel=o,this.nextAutoLevelKey=this.getAutoLevelKey(),o}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:o,minAutoLevel:c}=n,s=r?r.duration:e?e.duration:0,f=this.getBwEstimate(),p=this.getStarvationDelay();let y=o.abrBandWidthFactor,_=o.abrBandWidthUpFactor;if(p){const R=this.findBestLevel(f,c,i,p,0,y,_);if(R>=0)return this.rebufferNotice=-1,R}let T=s?Math.min(s,o.maxStarvationDelay):o.maxStarvationDelay;if(!p){const R=this.bitrateTestDelay;R&&(T=(s?Math.min(s,o.maxLoadingDelay):o.maxLoadingDelay)-R,this.info(`bitrate test took ${Math.round(1e3*R)}ms, set first fragment max fetchDuration to ${Math.round(1e3*T)} ms`),y=_=1)}const E=this.findBestLevel(f,c,i,p,T,y,_);if(this.rebufferNotice!==E&&(this.rebufferNotice=E,this.info(`${p?"rebuffering expected":"buffer is empty"}, optimal quality level ${E}`)),E>-1)return E;const k=n.levels[c],P=n.loadLevelObj;return P&&(k==null?void 0:k.bitrate)=r;Ae--){var Me;const be=k[Ae],me=Ae>_;if(!be)continue;if(D.useMediaCapabilities&&!be.supportedResult&&!be.supportedPromise){const at=navigator.mediaCapabilities;typeof(at==null?void 0:at.decodingInfo)=="function"&&sDt(be,se,W,Z,e,Q)?(be.supportedPromise=H2e(be,se,at,this.supportedCache),be.supportedPromise.then(Et=>{if(!this.hls)return;be.supportedResult=Et;const _t=this.hls.levels,Vt=_t.indexOf(be);Et.error?this.warn(`MediaCapabilities decodingInfo error: "${Et.error}" for level ${Vt} ${sa(Et)}`):Et.supported?Et.decodingInfoResults.some(pt=>pt.smooth===!1||pt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Vt} not smooth or powerEfficient: ${sa(Et)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Vt} ${sa(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}`)})):be.supportedResult=q2e}if((G&&be.codecSet!==G||W&&be.videoRange!==W||me&&Z>be.frameRate||!me&&Z>0&&Zat.smooth===!1))&&(!V||Ae!==ue)){Ce.push(Ae);continue}const Pe=be.details,Ie=(E?Pe==null?void 0:Pe.partTarget:Pe==null?void 0:Pe.averagetargetduration)||_e;let Se;me?Se=s*e:Se=c*e;const ve=_e&&i>=_e*2&&o===0?be.averageBitrate:be.maxBitrate,We=this.getTimeToLoadFrag(we,Se,ve*Ie,Pe===void 0);if(Se>=ve&&(Ae===y||be.loadError===0&&be.fragmentError===0)&&(We<=we||!pn(We)||B&&!this.bitrateTestDelay||We${Ae} adjustedbw(${Math.round(Se)})-bitrate=${Math.round(Se-ve)} ttfb:${we.toFixed(1)} avgDuration:${Ie.toFixed(1)} maxFetchDuration:${p.toFixed(1)} fetchDuration:${We.toFixed(1)} firstSelection:${V} codecSet:${be.codecSet} videoRange:${be.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 Y2e={search:function(t,e){let r=0,n=t.length-1,i=null,o=null;for(;r<=n;){i=(r+n)/2|0,o=t[i];const c=e(o);if(c>0)r=i+1;else if(c<0)n=i-1;else return o}return null}};function bDt(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!pn(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 o=0;o0&&s<15e-7&&(r+=15e-7),o&&t.level!==o.level&&o.end<=t.end&&(o=e[2+t.sn-e[0].sn]||null)}else r===0&&e[0].start===0&&(o=e[0]);if(o&&((!t||t.level===o.level)&&Hle(r,n,o)===0||wDt(o,t,Math.min(i,n))))return o;const c=Y2e.search(e,Hle.bind(null,r,n));return c&&(c!==t||!o)?c:o}function wDt(t,e,r){if(e&&e.start===0&&e.level0){const n=e.tagList.reduce((i,o)=>(o[0]==="INF"&&(i+=parseFloat(o[1])),i),r);return t.start<=n}return!1}function Hle(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 SDt(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function Z2e(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 o;return Y2e.search(n,c=>c.cce?-1:(o=c,c.end<=r?1:c.start>r?-1:0)),o||null}return null}function iO(t){switch(t.details){case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_TIMEOUT:case Jt.LEVEL_LOAD_TIMEOUT:case Jt.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function X2e(t){return t.details.startsWith("key")}function Q2e(t){return X2e(t)&&!!t.frag&&!t.frag.decryptdata}function Wle(t,e){const r=iO(e);return t.default[`${r?"timeout":"error"}Retry`]}function hK(t,e){const r=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Kle(t){return zs(zs({},t),{errorRetry:null,timeoutRetry:null})}function sO(t,e,r,n){if(!t)return!1;const i=n==null?void 0:n.code,o=e499)}function Bq(t){return t===0&&navigator.onLine===!1}var Gl={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Yu={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class EDt extends hh{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(je.ERROR,this.onError,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(je.ERROR,this.onError,this),e.off(je.ERROR,this.onErrorOut,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.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)===Tn.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,o=r.context;switch(r.details){case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case Jt.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=l1();return}case Jt.FRAG_GAP:case Jt.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=Gl.SendAlternateToPenaltyBox;return}case Jt.LEVEL_EMPTY_ERROR:case Jt.LEVEL_PARSING_ERROR:{var c;const f=r.parent===Tn.MAIN?r.level:i.loadLevel;r.details===Jt.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 Jt.LEVEL_LOAD_ERROR:case Jt.LEVEL_LOAD_TIMEOUT:typeof(o==null?void 0:o.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,o.level));return;case Jt.AUDIO_TRACK_LOAD_ERROR:case Jt.AUDIO_TRACK_LOAD_TIMEOUT:case Jt.SUBTITLE_LOAD_ERROR:case Jt.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const f=i.loadLevelObj;if(f&&(o.type===Hi.AUDIO_TRACK&&f.hasAudioGroup(o.groupId)||o.type===Hi.SUBTITLE_TRACK&&f.hasSubtitleGroup(o.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.loadLevel),r.errorAction.action=Gl.SendAlternateToPenaltyBox,r.errorAction.flags=Yu.MoveAllAlternatesMatchingHost;return}}return;case Jt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:Gl.SendAlternateToPenaltyBox,flags:Yu.MoveAllAlternatesMatchingHDCP};return;case Jt.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Jt.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Jt.KEY_SYSTEM_NO_SESSION:r.errorAction={action:Gl.SendAlternateToPenaltyBox,flags:Yu.MoveAllAlternatesMatchingKey};return;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.REMUX_ALLOC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(!r.errorAction){var s;r.errorAction=this.getLevelSwitchAction(r,(s=r.level)!=null?s:i.loadLevel)}return;case Jt.INTERNAL_EXCEPTION:case Jt.BUFFER_APPENDING_ERROR:case Jt.BUFFER_FULL_ERROR:case Jt.LEVEL_SWITCH_ERROR:case Jt.BUFFER_STALLED_ERROR:case Jt.BUFFER_SEEK_OVER_HOLE:case Jt.BUFFER_NUDGE_ON_STALL:r.errorAction=l1();return}r.type===Dn.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=l1())}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=Wle(n.config.playlistLoadPolicy,e),o=this.playlistError++;if(sO(i,o,iO(e),e.response))return{action:Gl.RetryRequest,flags:Yu.None,retryConfig:i,retryCount:o};const s=this.getLevelSwitchAction(e,r);return i&&(s.retryConfig=i,s.retryCount=o),s}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:o,keyLoadPolicy:c}=r.config,s=Wle(X2e(e)?c:o,e),f=r.levels.reduce((y,_)=>y+_.fragmentError,0);if(i&&(e.details!==Jt.FRAG_GAP&&i.fragmentError++,!Q2e(e)&&sO(s,f,iO(e),e.response)))return{action:Gl.RetryRequest,flags:Yu.None,retryConfig:s,retryCount:f};const p=this.getLevelSwitchAction(e,n);return s&&(p.retryConfig=s,p.retryCount=f),p}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var o,c;const p=e.details;i.loadError++,p===Jt.BUFFER_APPEND_ERROR&&i.fragmentError++;let y=-1;const{levels:_,loadLevel:T,minAutoLevel:E,maxAutoLevel:k}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const P=(o=e.frag)==null?void 0:o.type,D=(P===Tn.AUDIO&&p===Jt.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(p===Jt.BUFFER_ADD_CODEC_ERROR||p===Jt.BUFFER_APPEND_ERROR))&&_.some(({audioCodec:W})=>i.audioCodec!==W),B=e.sourceBufferName==="video"&&(p===Jt.BUFFER_ADD_CODEC_ERROR||p===Jt.BUFFER_APPEND_ERROR)&&_.some(({codecSet:W,audioCodec:Z})=>i.codecSet!==W&&i.audioCodec===Z),{type:V,groupId:G}=(c=e.context)!=null?c:{};for(let W=_.length;W--;){const Z=(W+T)%_.length;if(Z!==T&&Z>=E&&Z<=k&&_[Z].loadError===0){var s,f;const Q=_[Z];if(p===Jt.FRAG_GAP&&P===Tn.MAIN&&e.frag){const re=_[Z].details;if(re){const se=J_(e.frag,re.fragments,e.frag.start);if(se!=null&&se.gap)continue}}else{if(V===Hi.AUDIO_TRACK&&Q.hasAudioGroup(G)||V===Hi.SUBTITLE_TRACK&&Q.hasSubtitleGroup(G))continue;if(P===Tn.AUDIO&&(s=i.audioGroups)!=null&&s.some(re=>Q.hasAudioGroup(re))||P===Tn.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}y=Z;break}}if(y>-1&&n.loadLevel!==y)return e.levelRetry=!0,this.playlistError=0,{action:Gl.SendAlternateToPenaltyBox,flags:Yu.None,nextAutoLevel:y}}return{action:Gl.SendAlternateToPenaltyBox,flags:Yu.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case Gl.DoNothing:break;case Gl.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==Jt.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,o=n.nextAutoLevel;switch(i){case Yu.None:this.switchLevel(e,o);break;case Yu.MoveAllAlternatesMatchingHDCP:{const f=this.getVariantLevelIndex(e.frag),p=r.levels[f],y=p==null?void 0:p.attrs["HDCP-LEVEL"];if(n.hdcpLevel=y,y==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(y){r.maxHdcpLevel=Fq[Fq.indexOf(y)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case Yu.MoveAllAlternatesMatchingKey:{const f=e.decryptdata;if(f){const p=this.hls.levels,y=p.length;for(let T=y;T--;)if(this.variantHasKey(p[T],f)){var c,s;this.log(`Banned key found in level ${T} (${p[T].bitrate}bps) or audio group "${(c=p[T].audioGroups)==null?void 0:c.join(",")}" (${(s=e.frag)==null?void 0:s.type} fragment) ${Kl(f.keyId||[])}`),p[T].fragmentError++,p[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||o)){f.body.type===n&&this.removeFragment(f.body);return}const p=f.range[e];if(p){if(p.time.length===0){this.removeFragment(f.body);return}p.time.some(y=>{const _=!this.isTimeBuffered(y.startPTS,y.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=lw(n),o=this.fragments[i];if(!o||o.buffered&&n.gap)return;const c=!n.relurl;Object.keys(r).forEach(s=>{const f=n.elementaryStreams[s];if(!f)return;const p=r[s],y=c||f.partial===!0;o.range[s]=this.getBufferedTimes(n,e.part,y,p)}),o.loaded=null,Object.keys(o.range).length?(this.bufferedEnd(o,n),ER(o)||this.removeParts(n.sn-1,n.type)):this.removeFragment(o.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]=Yle(n,i=>i.fragment.sn>=e))}fragBuffered(e,r){const n=lw(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 o={time:[],partial:n},c=e.start,s=e.end,f=e.minEndPTS||s,p=e.maxStartPTS||c;for(let y=0;y=_&&f<=T){o.time.push({startPTS:Math.max(c,i.start(y)),endPTS:Math.min(s,i.end(y))});break}else if(c_){const E=Math.max(c,i.start(y)),k=Math.min(s,i.end(y));k>E&&(o.partial=!0,o.time.push({startPTS:E,endPTS:k}))}else if(s<=_)break}return o}getPartialFragment(e){let r=null,n,i,o,c=0;const{bufferPadding:s,fragments:f}=this;return Object.keys(f).forEach(p=>{const y=f[p];y&&ER(y)&&(i=y.body.start-s,o=y.body.end+s,e>=i&&e<=o&&(n=Math.min(e-i,o-e),c<=n&&(r=y.body,c=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||ER(r))}getState(e){const r=lw(e),n=this.fragments[r];return n?n.buffered?ER(n)?ll.PARTIAL:ll.OK:ll.APPENDING:ll.NOT_LOADED}isTimeBuffered(e,r,n){let i,o;for(let c=0;c=i&&r<=o)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,o=lw(n);this.fragments[o]={body:n,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,r){const{frag:n,part:i,timeRanges:o,type:c}=r;if(n.sn==="initSegment")return;const s=n.type;if(i){let p=this.activePartLists[s];p||(this.activePartLists[s]=p=[]),p.push(i)}this.timeRanges=o;const f=o[c];this.detectEvictedFragments(c,f,s,i)}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=lw(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 o=r[n[i]];if((o==null?void 0:o.body.type)===e)return!0}return!1}hasParts(e){var r;return!!((r=this.activePartLists[e])!=null&&r.length)}removeFragmentsInRange(e,r,n,i,o){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||o)&&this.removeFragment(f)})}removeFragment(e){const r=lw(e);e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=Yle(n,o=>o.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 ER(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 lw(t){return`${t.type}_${t.level}_${t.sn}`}function Yle(t,e){return t.filter(r=>{const n=e(r);return n||r.clearElementaryStreamInfo(),n})}var ux={cbc:0,ctr:1};class jDt{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 ux.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e);case ux.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 kDt(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}class CDt{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],o=n[1],c=n[2],s=n[3],f=this.invSubMix,p=f[0],y=f[1],_=f[2],T=f[3],E=new Uint32Array(256);let k=0,P=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=P^P<<1^P<<2^P<<3^P<<4;D=D>>>8^D&255^99,e[k]=D,r[D]=k;const M=E[k],B=E[M],V=E[B];let G=E[D]*257^D*16843008;i[k]=G<<24|G>>>8,o[k]=G<<16|G>>>16,c[k]=G<<8|G>>>24,s[k]=G,G=V*16843009^B*65537^M*257^k*16843008,p[D]=G<<24|G>>>8,y[D]=G<<16|G>>>16,_[D]=G<<8|G>>>24,T[D]=G,k?(k=M^E[E[E[V^M]]],P^=E[E[P]]):k=P=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?o(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:o,currentResult:c,remainderData:s}=this;if(i!==ux.cbc||r.byteLength!==16)return Us.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=oh(s,e),this.remainderData=null);const f=this.getValidChunk(e);if(!f.length)return null;o&&(n=o);let p=this.softwareDecrypter;p||(p=this.softwareDecrypter=new CDt),p.expandKey(r);const y=c;return this.currentResult=p.decrypt(f.buffer,0,n),this.currentIV=f.slice(-16).buffer,y||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 IDt(this.subtle,r,i)}return this.fastAesKey.expandKey().then(o=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new jDt(this.subtle,new Uint8Array(n),i).decrypt(e.buffer,o)):Promise.reject(new Error("web crypto not initialized"))).catch(o=>(Us.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${o.name}: ${o.message}`),this.onWebCryptoError(e,r,n,i)))}onWebCryptoError(e,r,n,i){const o=this.enableSoftwareAES;if(o){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"+(o?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let r=e;const n=e.length-e.length%PDt;return n!==e.length&&(r=e.slice(0,n),this.remainderData=e.slice(n)),r}logOnce(e){this.logEnabled&&(Us.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Zle=Math.pow(2,17);class RDt{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 pp({type:Dn.NETWORK_ERROR,details:Jt.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,o=i.fLoader,c=i.loader;return new Promise((s,f)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(k=>k[0]==="GAP")){f(Qle(e));return}else e.gap=!1;const p=this.loader=o?new o(i):new c(i),y=Xle(e);e.loader=p;const _=Kle(i.fragLoadPolicy.default),T={loadPolicy:_,timeout:_.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zle};e.stats=p.stats;const E={onSuccess:(k,P,R,D)=>{this.resetLoader(e,p);let M=k.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:(k,P,R,D)=>{this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:zs({url:n,data:void 0},k),error:new Error(`HTTP Error ${k.code} ${k.text}`),networkDetails:R,stats:D}))},onAbort:(k,P,R)=>{this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:R,stats:k}))},onTimeout:(k,P,R)=>{this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:R,stats:k}))}};r&&(E.onProgress=(k,P,R,D)=>r({frag:e,part:null,payload:R,networkDetails:D})),p.load(y,T,E)})}loadPart(e,r,n){this.abort();const i=this.config,o=i.fLoader,c=i.loader;return new Promise((s,f)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){f(Qle(e,r));return}const p=this.loader=o?new o(i):new c(i),y=Xle(e,r);e.loader=p;const _=Kle(i.fragLoadPolicy.default),T={loadPolicy:_,timeout:_.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zle};r.stats=p.stats,p.load(y,T,{onSuccess:(E,k,P,R)=>{this.resetLoader(e,p),this.updateStatsFromPart(e,r);const D={frag:e,part:r,payload:E.data,networkDetails:R};n(D),s(D)},onError:(E,k,P,R)=>{this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:zs({url:y.url,data:void 0},E),error:new Error(`HTTP Error ${E.code} ${E.text}`),networkDetails:P,stats:R}))},onAbort:(E,k,P)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:P,stats:E}))},onTimeout:(E,k,P)=>{this.resetLoader(e,p),f(new pp({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:P,stats:E}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,o=i.total;if(n.loaded+=i.loaded,o){const f=Math.round(e.duration/r.duration),p=Math.min(Math.round(n.loaded/o),f),_=(f-p)*Math.round(n.loaded/p);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 Xle(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,o=r.byteRangeEndOffset;if(pn(i)&&pn(o)){var c;let s=i,f=o;if(t.sn==="initSegment"&&LDt((c=t.decryptdata)==null?void 0:c.method)){const p=o-i;p%16&&(f=o+(16-p%16)),i!==0&&(n.resetIV=!0,s=i-16)}n.rangeStart=s,n.rangeEnd=f}return n}function Qle(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:Dn.MEDIA_ERROR,details:Jt.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new pp(n)}function LDt(t){return t==="AES-128"||t==="AES-256"}class pp extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class J2e extends hh{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 mK{constructor(e,r,n,i=0,o=-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=AR(),this.buffering={audio:AR(),video:AR(),audiovideo:AR()},this.level=e,this.sn=r,this.id=n,this.size=i,this.part=o,this.partial=c}}function AR(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jle={length:0,start:()=>0,end:()=>0};class Si{static isBuffered(e,r){if(e){const n=Si.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=Si.getBuffered(e);return Si.timeRangesToArray(r)}return[]}static timeRangesToArray(e){const r=[];for(let n=0;n1&&e.sort((y,_)=>y.start-_.start||_.end-y.end);let i=-1,o=[];if(n)for(let y=0;y=e[y].start&&r<=e[y].end&&(i=y);const _=o.length;if(_){const T=o[_-1].end;e[y].start-TT&&(o[_-1].end=e[y].end):o.push(e[y])}else o.push(e[y])}else o=e;let c=0,s,f=r,p=r;for(let y=0;y=_&&r<=T&&(i=y),r+n>=_&&r{const i=n.substring(2,n.length-1),o=r==null?void 0:r[i];return o===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):o})}return e}function tce(t,e,r){let n=t.variableList;n||(t.variableList=n={});let i,o;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const c=new self.URL(r).searchParams;if(c.has(i))o=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,o=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=o||""}function DDt(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 MDt=/^(\d+)x(\d+)$/,rce=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Za{constructor(e,r){typeof e=="string"&&(e=Za.parseAttrList(e,r)),Xs(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,o)=>(i[o.toLowerCase()]=!0,i),r)}bool(e){return this[e]==="YES"}decimalResolution(e){const r=MDt.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={},o='"';for(rce.lastIndex=0;(n=rce.exec(e))!==null;){const c=n[1].trim();let s=n[2];const f=s.indexOf(o)===0&&s.lastIndexOf(o)===s.length-1;let p=!1;if(f)s=s.slice(1,-1);else switch(c){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":p=!0}if(r&&(f||p))s=zq(r,s);else if(!p&&!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":Us.warn(`${e}: attribute ${c} is missing quotes`)}i[c]=s}return i}}const ODt="com.apple.hls.interstitial";function FDt(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function BDt(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class tAe{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 o=r.attr;for(const c in o)if(Object.prototype.hasOwnProperty.call(e,c)&&e[c]!==o[c]){Us.warn(`DATERANGE tag attribute: "${c}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=c;break}e=Xs(new Za({}),o,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 o=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);pn(o.getTime())&&(this._endDate=o)}}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?(Us.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(pn(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===ODt}get isValid(){return!!this.id&&!this._badValueForSameId&&pn(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 zDt=10;class $Dt{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?pn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||zDt}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 aO(t,e){return t.length===e.length?!t.some((r,n)=>r!==e[n]):!1}function nce(t,e){return!t&&!e?!0:!t||!e?!1:aO(t,e)}function c1(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function pK(t){switch(t){case"AES-128":case"AES-256":return ux.cbc;case"AES-256-CTR":return ux.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function gK(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function $q(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function UDt(t){const e=$q(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function rAe(t){const e=function(n,i,o){const c=n[i];n[i]=n[o],n[o]=c};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function nAe(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 o=i[0]==="base64",c=i[1];o?(n.splice(-1,1),r=gK(c)):r=UDt(c)}}return r}const oO=typeof self<"u"?self:void 0;var Ja={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Yl={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function IL(t){switch(t){case Yl.FAIRPLAY:return Ja.FAIRPLAY;case Yl.PLAYREADY:return Ja.PLAYREADY;case Yl.WIDEVINE:return Ja.WIDEVINE;case Yl.CLEARKEY:return Ja.CLEARKEY}}function V$(t){switch(t){case Ja.FAIRPLAY:return Yl.FAIRPLAY;case Ja.PLAYREADY:return Yl.PLAYREADY;case Ja.WIDEVINE:return Yl.WIDEVINE;case Ja.CLEARKEY:return Yl.CLEARKEY}}function wA(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[Ja.FAIRPLAY,Ja.WIDEVINE,Ja.PLAYREADY,Ja.CLEARKEY].filter(i=>!!e[i]):[];return!n[Ja.WIDEVINE]&&r&&n.push(Ja.WIDEVINE),n}const iAe=function(t){return oO!=null&&(t=oO.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function VDt(t,e,r,n){let i;switch(t){case Ja.FAIRPLAY:i=["cenc","sinf"];break;case Ja.WIDEVINE:case Ja.PLAYREADY:i=["cenc"];break;case Ja.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return qDt(i,e,r,n)}function qDt(t,e,r,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(o=>({contentType:`audio/mp4; codecs=${o}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(o=>({contentType:`video/mp4; codecs=${o}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function GDt(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(r=>r==="persistent-license")))}function sAe(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=gK(s).subarray(0,16);return rAe(f),f}}return null}let cw={};class Gy{static clearKeyUriToKeyIdMap(){cw={}}static setKeyIdForUri(e,r){cw[e]=r}static addKeyIdForUri(e){const r=Object.keys(cw).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),cw[e]=n,n}constructor(e,r,n,i=[1],o=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=o,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!c1(e),c!=null&&c.startsWith("0x")&&(this.keyId=new Uint8Array(R2e(c)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&aO(e.keyFormatVersions,this.keyFormatVersions)&&nce(e.iv,this.iv)&&nce(e.keyId,this.keyId)}isSupported(){if(this.method){if(c1(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Yl.FAIRPLAY:case Yl.WIDEVINE:case Yl.PLAYREADY:case Yl.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(c1(this.method)){let o=this.iv;return o||(typeof e!="number"&&(Us.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),o=WDt(e)),new Gy(this.method,this.uri,"identity",this.keyFormatVersions,o)}if(this.keyId){const o=cw[this.uri];if(o&&!aO(this.keyId,o)&&Gy.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=nAe(this.uri);if(n)switch(this.keyFormat){case Yl.WIDEVINE:if(this.pssh=n,!this.keyId){const o=ZLt(n.buffer);if(o.length){var i;const c=o[0];this.keyId=(i=c.kids)!=null&&i.length?c.kids[0]:null}}this.keyId||(this.keyId=ice(r));break;case Yl.PLAYREADY:{const o=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=YLt(o,null,n),this.keyId=sAe(n);break}default:{let o=n.subarray(0,16);if(o.length!==16){const c=new Uint8Array(16);c.set(o,16-o.length),o=c}this.keyId=o;break}}if(!this.keyId||this.keyId.byteLength!==16){let o;o=HDt(r),o||(o=ice(r),o||(o=cw[this.uri])),o&&(this.keyId=o,Gy.setKeyIdForUri(this.uri,o))}return this}}function HDt(t){const e=t==null?void 0:t[Yl.WIDEVINE];return e?e.keyId:null}function ice(t){const e=t==null?void 0:t[Yl.PLAYREADY];if(e){const r=nAe(e.uri);if(r)return sAe(r)}return null}function WDt(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const sce=/#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,ace=/#EXT-X-MEDIA:(.*)/g,KDt=/^#EXT(?:INF|-X-TARGETDURATION):/m,q$=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),YDt=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 tm{static findGroup(e,r){for(let n=0;n0&&o.length({id:p.attrs.AUDIO,audioCodec:p.audioCodec})),SUBTITLES:c.map(p=>({id:p.attrs.SUBTITLES,textCodec:p.textCodec})),"CLOSED-CAPTIONS":[]};let f=0;for(ace.lastIndex=0;(i=ace.exec(e))!==null;){const p=new Za(i[1],n),y=p.TYPE;if(y){const _=s[y],T=o[y]||[];o[y]=T;const E=p.LANGUAGE,k=p["ASSOC-LANGUAGE"],P=p.CHANNELS,R=p.CHARACTERISTICS,D=p["INSTREAM-ID"],M={attrs:p,bitrate:0,id:f++,groupId:p["GROUP-ID"]||"",name:p.NAME||E||"",type:y,default:p.bool("DEFAULT"),autoselect:p.bool("AUTOSELECT"),forced:p.bool("FORCED"),lang:E,url:p.URI?tm.resolve(p.URI,r):""};if(k&&(M.assocLang=k),P&&(M.channels=P),R&&(M.characteristics=R),D&&(M.instreamId=D),_!=null&&_.length){const B=tm.findGroup(_,M.groupId)||_[0];uce(M,B,"audioCodec"),uce(M,B,"textCodec")}T.push(M)}}return o}static parseLevelPlaylist(e,r,n,i,o,c){var s;const f={url:r},p=new $Dt(r),y=p.fragments,_=[];let T=null,E=0,k=0,P=0,R=0,D=0,M=null,B=new z$(i,f),V,G,W,Z=-1,Q=!1,re=null,se;if(q$.lastIndex=0,p.m3u8=e,p.hasVariableRefs=ece(e),((s=q$.exec(e))==null?void 0:s[0])!=="#EXTM3U")return p.playlistParsingError=new Error("Missing format identifier #EXTM3U"),p;for(;(V=q$.exec(e))!==null;){Q&&(Q=!1,B=new z$(i,f),B.playlistOffset=P,B.setStart(P),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 Ce=V[1];if(Ce){B.duration=parseFloat(Ce);const Me=(" "+V[2]).slice(1);B.title=Me||null,B.tagList.push(Me?["INF",Ce,Me]:["INF",Ce])}else if(V[3]){if(pn(B.duration)){B.playlistOffset=P,B.setStart(P),W&&hce(B,W,p),B.sn=E,B.level=n,B.cc=R,y.push(B);const Me=(" "+V[3]).slice(1);B.relurl=zq(p,Me),Uq(B,M,_),M=B,P+=B.duration,E++,k=0,Q=!0}}else{if(V=V[0].match(YDt),!V){Us.warn("No matches on slow regex match for level playlist!");continue}for(G=1;G0&&fce(p,Me,V),E=p.startSN=parseInt(Ae);break;case"SKIP":{p.skippedSegments&&lp(p,Me,V);const me=new Za(Ae,p),Pe=me.decimalInteger("SKIPPED-SEGMENTS");if(pn(Pe)){p.skippedSegments+=Pe;for(let Se=Pe;Se--;)y.push(null);E+=Pe}const Ie=me.enumeratedString("RECENTLY-REMOVED-DATERANGES");Ie&&(p.recentlyRemovedDateranges=(p.recentlyRemovedDateranges||[]).concat(Ie.split(" ")));break}case"TARGETDURATION":p.targetduration!==0&&lp(p,Me,V),p.targetduration=Math.max(parseInt(Ae),1);break;case"VERSION":p.version!==null&&lp(p,Me,V),p.version=parseInt(Ae);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":p.live||lp(p,Me,V),p.live=!1;break;case"#":(Ae||be)&&B.tagList.push(be?[Ae,be]:[Ae]);break;case"DISCONTINUITY":R++,B.tagList.push(["DIS"]);break;case"GAP":B.gap=!0,B.tagList.push([Me]);break;case"BITRATE":B.tagList.push([Me,Ae]),D=parseInt(Ae)*1e3,pn(D)?B.bitrate=D:D=0;break;case"DATERANGE":{const me=new Za(Ae,p),Pe=new tAe(me,p.dateRanges[me.ID],p.dateRangeTagCount);p.dateRangeTagCount++,Pe.isValid||p.skippedSegments?p.dateRanges[Pe.id]=Pe:Us.warn(`Ignoring invalid DATERANGE tag: "${Ae}"`),B.tagList.push(["EXT-X-DATERANGE",Ae]);break}case"DEFINE":{{const me=new Za(Ae,p);"IMPORT"in me?DDt(p,me,c):tce(p,me,r)}break}case"DISCONTINUITY-SEQUENCE":p.startCC!==0?lp(p,Me,V):y.length>0&&fce(p,Me,V),p.startCC=R=parseInt(Ae);break;case"KEY":{const me=oce(Ae,r,p);if(me.isSupported()){if(me.method==="NONE"){W=void 0;break}W||(W={});const Pe=W[me.keyFormat];Pe!=null&&Pe.matches(me)||(Pe&&(W=Xs({},W)),W[me.keyFormat]=me)}else Us.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Ae}"`);break}case"START":p.startTimeOffset=lce(Ae);break;case"MAP":{const me=new Za(Ae,p);if(B.duration){const Pe=new z$(i,f);dce(Pe,me,n,W),T=Pe,B.initSegment=T,T.rawProgramDateTime&&!B.rawProgramDateTime&&(B.rawProgramDateTime=T.rawProgramDateTime)}else{const Pe=B.byteRangeEndOffset;if(Pe){const Ie=B.byteRangeStartOffset;re=`${Pe-Ie}@${Ie}`}else re=null;dce(B,me,n,W),T=B,Q=!0}T.cc=R;break}case"SERVER-CONTROL":{se&&lp(p,Me,V),se=new Za(Ae),p.canBlockReload=se.bool("CAN-BLOCK-RELOAD"),p.canSkipUntil=se.optionalFloat("CAN-SKIP-UNTIL",0),p.canSkipDateRanges=p.canSkipUntil>0&&se.bool("CAN-SKIP-DATERANGES"),p.partHoldBack=se.optionalFloat("PART-HOLD-BACK",0),p.holdBack=se.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{p.partTarget&&lp(p,Me,V);const me=new Za(Ae);p.partTarget=me.decimalFloatingPoint("PART-TARGET");break}case"PART":{let me=p.partList;me||(me=p.partList=[]);const Pe=k>0?me[me.length-1]:void 0,Ie=k++,Se=new Za(Ae,p),ve=new DLt(Se,B,f,Ie,Pe);me.push(ve),B.duration+=ve.duration;break}case"PRELOAD-HINT":{const me=new Za(Ae,p);p.preloadHint=me;break}case"RENDITION-REPORT":{const me=new Za(Ae,p);p.renditionReports=p.renditionReports||[],p.renditionReports.push(me);break}default:Us.warn(`line parsed but not handled: ${V}`);break}}}M&&!M.relurl?(y.pop(),P-=M.duration,p.partList&&(p.fragmentHint=M)):p.partList&&(Uq(B,M,_),B.cc=R,p.fragmentHint=B,W&&hce(B,W,p)),p.targetduration||(p.playlistParsingError=new Error("Missing Target Duration"));const ue=y.length,_e=y[0],we=y[ue-1];if(P+=p.skippedSegments*p.targetduration,P>0&&ue&&we){p.averagetargetduration=P/ue;const Ce=we.sn;p.endSN=Ce!=="initSegment"?Ce:0,p.live||(we.endList=!0),Z>0&&(XDt(y,Z),_e&&_.unshift(_e))}return p.fragmentHint&&(P+=p.fragmentHint.duration),p.totalduration=P,_.length&&p.dateRangeTagCount&&_e&&aAe(_,p),p.endCC=R,p}}function aAe(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,o=Object.keys(e.dateRanges);for(let s=o.length;s--;){const f=e.dateRanges[o[s]],p=f.startDate.getTime();f.tagAnchor=n.ref;for(let y=r;y--;){var c;if(((c=t[y])==null?void 0:c.sn)=s||n===0){var c;const f=(((c=r[n+1])==null?void 0:c.start)||i)-o.start;if(e<=s+f*1e3){const p=r[n].sn-t.startSN;if(p<0)return-1;const y=t.fragments;if(y.length>r.length){const T=(r[n+1]||y[y.length-1]).sn-t.startSN;for(let E=T;E>p;E--){const k=y[E].programDateTime;if(e>=k&&en);["video","audio","text"].forEach(n=>{const i=r.filter(o=>uK(o,n));i.length&&(e[`${n}Codec`]=i.map(o=>o.split("/")[0]).join(","),r=r.filter(o=>i.indexOf(o)===-1))}),e.unknownCodecs=r}function uce(t,e,r){const n=e[r];n&&(t[r]=n)}function XDt(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 Uq(t,e,r){t.rawProgramDateTime?r.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function dce(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 hce(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 lp(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function fce(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function G$(t,e){const r=e.startPTS;if(pn(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 oAe(t,e,r,n,i,o,c){n-r<=0&&(c.warn("Fragment should have a positive duration",e),n=r+e.duration,o=i+e.duration);let f=r,p=n;const y=e.startPTS,_=e.endPTS;if(pn(y)){const D=Math.abs(y-r);t&&D>t.totalduration?c.warn(`media timestamps and playlist times differ by ${D}s for level ${e.level} ${t.url}`):pn(e.deltaPTS)?e.deltaPTS=Math.max(D,e.deltaPTS):e.deltaPTS=D,f=Math.max(r,y),r=Math.min(r,y),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,p=Math.min(n,_),n=Math.max(n,_),o=e.endDTS!==void 0?Math.max(o,e.endDTS):o}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=p,e.endDTS=o;const E=e.sn;if(!t||Et.endSN)return 0;let k;const P=E-t.startSN,R=t.fragments;for(R[P]=e,k=P;k>0;k--)G$(R[k],R[k-1]);for(k=P;k=0;y--){const _=i[y].initSegment;if(_){n=_;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let o;tMt(t,e,(y,_,T,E)=>{if((!e.startCC||e.skippedSegments)&&_.cc!==y.cc){const k=y.cc-_.cc;for(let P=T;P{var _;y&&(!y.initSegment||y.initSegment.relurl===((_=n)==null?void 0:_.relurl))&&(y.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=c.some(y=>!y),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let y=e.skippedSegments;y--;)c.shift();e.startSN=c[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=JDt(t.dateRanges,e,r));const y=t.fragments.filter(_=>_.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let _=1;_{_.elementaryStreams=y.elementaryStreams,_.stats=y.stats}),o?oAe(e,o,o.startPTS,o.endPTS,o.startDTS,o.endDTS,r):lAe(t,e),c.length&&(e.totalduration=e.edge-c[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const p=e.advancedDateTime;if(e.advanced&&p){const y=e.edge;e.driftStart||(e.driftStartTime=p,e.driftStart=y),e.driftEndTime=p,e.driftEnd=y}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=t.requestScheduled)}function JDt(t,e,r){const{dateRanges:n,recentlyRemovedDateranges:i}=e,o=Xs({},t);i&&i.forEach(f=>{delete o[f]});const s=Object.keys(o).length;return s?(Object.keys(n).forEach(f=>{const p=o[f],y=new tAe(n[f].attr,p);y.isValid?(o[f]=y,p||(y.tagOrder+=s)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${sa(n[f].attr)}"`)}),o):n}function eMt(t,e,r){if(t&&e){let n=0;for(let i=0,o=t.length;i<=o;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 tMt(t,e,r){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,o=(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 p=i;p<=o;p++){const y=f[c+p];let _=s[p];if(n&&!_&&y&&(_=e.fragments[p]=y),y&&_){r(y,_,p,s);const T=y.relurl,E=_.relurl;if(T&&rMt(T,E)){e.playlistParsingError=mce(`media sequence mismatch ${_.sn}:`,t,e,y,_);return}else if(y.cc!==_.cc){e.playlistParsingError=mce(`discontinuity sequence mismatch (${y.cc}!=${_.cc})`,t,e,y,_);return}}}}function mce(t,e,r,n,i){return new Error(`${t} ${i.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function lAe(t,e,r=!0){const n=e.startSN+e.skippedSegments-t.startSN,i=t.fragments,o=n>=0;let c=0;if(o&&ne){const o=n[n.length-1].duration*1e3;o{var n;(n=e.details)==null||n.fragments.forEach(i=>{i.level=r,i.initSegment&&(i.initSegment.level=r)})})}function rMt(t,e){return t!==e&&e?gce(t)!==gce(e):!1}function gce(t){return t.replace(/\?[^?]*$/,"")}function rj(t,e){for(let n=0,i=t.length;nt.startCC)}function yce(t,e){const r=t.start+e;t.startPTS=r,t.setStart(r),t.endPTS=r+t.duration}function fAe(t,e){const r=e.fragments;for(let n=0,i=r.length;n{const{config:c,fragCurrent:s,media:f,mediaBuffer:p,state:y}=this,_=f?f.currentTime:0,T=Si.bufferInfo(p||f,_,c.maxBufferHole),E=!T.len;if(this.log(`Media seeking to ${pn(_)?_.toFixed(3):_}, state: ${y}, ${E?"out of":"in"} buffer`),this.state===wr.ENDED)this.resetLoadingState();else if(s){const k=c.maxFragLookUpTolerance,P=s.start-k,R=s.start+s.duration+k;if(E||RT.end){const D=_>R;(_k&&(this.lastCurrentTime=_),!this.loadingParts){const P=Math.max(T.end,_),R=this.shouldLoadParts(this.getLevelDetails(),P);R&&(this.log(`LL-Part loading ON after seeking to ${_.toFixed(2)} with buffer @${P.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===wr.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=o,this.hls=e,this.fragmentLoader=new RDt(e.config),this.keyLoader=n,this.fragmentTracker=r,this.config=e.config,this.decrypter=new fK(e.config)}registerListeners(){const{hls:e}=this;e.on(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(je.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===wr.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=wr.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 o=e.buffered;this.config.maxBufferHole&&o&&o.length>1&&(e=Si.bufferedInfo(o,e.start,0));const c=e.nextStart;if(c&&c>i&&c{const c=o.frag;if(this.fragContextChanged(c)){this.warn(`${c.type} sn: ${c.sn}${o.part?" part: "+o.part.index:""} of ${this.fragInfo(c,!1,o.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(c);return}c.stats.chunkCount++,this._handleFragmentLoadProgress(o)};this._doFragLoad(e,r,n,i).then(o=>{if(!o)return;const c=this.state,s=o.frag;if(this.fragContextChanged(s)){(c===wr.FRAG_LOADING||!this.fragCurrent&&c===wr.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=wr.IDLE);return}"payload"in o&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(je.FRAG_LOADED,o)),this._handleFragmentLoadComplete(o)}).catch(o=>{this.state===wr.STOPPED||this.state===wr.ERROR||(this.warn(`Frag error: ${(o==null?void 0:o.message)||o}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===ll.APPENDING){const o=e.type,c=this.getFwdBufferInfo(this.mediaBuffer,o),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)===ll.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(je.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:o,payload:c}=n,s=o.decryptdata;if(c&&c.byteLength>0&&s!=null&&s.key&&s.iv&&c1(s.method)){const f=self.performance.now();return this.decrypter.decrypt(new Uint8Array(c),s.key.buffer,s.iv.buffer,pK(s.method)).catch(p=>{throw i.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_DECRYPT_ERROR,fatal:!1,error:p,reason:p.message,frag:o}),p}).then(p=>{const y=self.performance.now();return i.trigger(je.FRAG_DECRYPTED,{frag:o,payload:p,stats:{tstart:f,tdecrypt:y}}),n.payload=p,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===wr.STOPPED||this.state===wr.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!==wr.STOPPED&&(this.state=wr.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 o=e.tracks;if(o&&!r.encrypted&&((n=o.audio)!=null&&n.encrypted||(i=o.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(je.ERROR,{type:Dn.KEY_SYSTEM_ERROR,details:Jt.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?sMt.toString(Si.getBuffered(n)):"(detached)"})`),jo(e)){var i;if(e.type!==Tn.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(s=>!!c[s])){this.state=wr.IDLE;return}}const o=(i=this.levels)==null?void 0:i[e.level];o!=null&&o.fragmentError&&(this.log(`Resetting level fragment error count of ${o.fragmentError} on frag buffered`),o.fragmentError=0)}this.state=wr.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:i,partsLoaded:o}=e,c=!o||o.length===0||o.some(f=>!f),s=new mK(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 o;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&&!((o=e.decryptdata)!=null&&o.key)){if(this.log(`Loading key for ${e.sn} of [${c.startSN}-${c.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=wr.KEY_LOADING,this.fragCurrent=e,s=this.keyLoader.load(e).then(T=>{if(!this.fragContextChanged(T.frag))return this.hls.trigger(je.KEY_LOADED,T),this.state===wr.KEY_LOADING&&(this.state=wr.IDLE),T}),this.hls.trigger(je.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(jo(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&&jo(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 k=T[E];e=this.fragCurrent=k.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${k.index} (${E}/${T.length-1}) of ${this.fragInfo(e,!1,k)}) cc: ${e.cc} [${c.startSN}-${c.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=k.start+k.duration,this.state=wr.FRAG_LOADING;let P;return s?P=s.then(R=>!R||this.fragContextChanged(R.frag)?null:this.doFragPartsLoad(e,k,r,i)).catch(R=>this.handleFragLoadError(R)):P=this.doFragPartsLoad(e,k,r,i).catch(R=>this.handleFragLoadError(R)),this.hls.trigger(je.FRAG_LOADING,{frag:e,part:k,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):P}else if(!e.url||this.loadedEndOfParts(T,n))return Promise.resolve(null)}}if(jo(e)&&this.loadingParts){var p;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(p=c.partList)==null?void 0:p.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))}`),pn(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=wr.FRAG_LOADING;const y=this.config.progressive&&e.type!==Tn.SUBTITLE;let _;return y&&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,y?i:void 0),s]).then(([T])=>(!y&&i&&i(T),T)).catch(T=>this.handleFragLoadError(T)),this.hls.trigger(je.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((o,c)=>{var s;const f=[],p=(s=n.details)==null?void 0:s.partList,y=_=>{this.fragmentLoader.loadPart(e,_,i).then(T=>{f[_.index]=T;const E=T.part;this.hls.trigger(je.FRAG_LOADED,T);const k=pce(n.details,e.sn,_.index+1)||dAe(p,e.sn,_.index+1);if(k)y(k);else return o({frag:e,part:E,partsLoaded:f})}).catch(c)};y(r)})}handleFragLoadError(e){if("data"in e){const r=e.data;r.frag&&r.details===Jt.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===Dn.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(je.ERROR,r)}else this.hls.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==wr.PARSING){!this.fragCurrent&&this.state!==wr.STOPPED&&this.state!==wr.ERROR&&(this.state=wr.IDLE);return}const{frag:n,part:i,level:o}=r,c=self.performance.now();n.stats.parsing.end=c,i&&(i.stats.parsing.end=c);const s=this.getLevelDetails(),p=s&&n.sn>s.endSN||this.shouldLoadParts(s,n.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=p),this.updateLevelTiming(n,i,o,e.partial)}shouldLoadParts(e,r){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var n;const o=e.partList[0];if(o.fragment.type===Tn.SUBTITLE)return!1;const c=o.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())>o.start-o.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:r,fragCurrent:n}=this,{level:i,sn:o,part:c}=e;if(!(r!=null&&r[i]))return this.warn(`Levels object was unset while buffering fragment ${o} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const s=r[i],f=s.details,p=c>-1?pce(f,o,c):null,y=p?p.fragment:uAe(f,o,n);return y?(n&&n!==y&&(y.stats=n.stats),{frag:y,part:p,level:s}):null}bufferFragmentData(e,r,n,i,o){if(this.state!==wr.PARSING)return;const{data1:c,data2:s}=e;let f=c;if(s&&(f=oh(c,s)),!f.length)return;const p=this.initPTS[r.cc],y=p?-p.baseTime/p.timescale:void 0,_={type:e.type,frag:r,part:n,chunkMeta:i,offset:y,parent:r.type,data:f};if(this.hls.trigger(je.BUFFER_APPENDING,_),e.dropped&&e.independent&&!n){if(o)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!Si.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=Si.bufferInfo(r,n,0),o=e.duration,c=Math.min(this.config.maxFragLookUpTolerance*2,o*.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(!pn(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 o=Si.bufferInfo(e,r,i);if(o.len===0&&o.nextStart!==void 0){const c=this.fragmentTracker.getBufferedFrag(r,n);if(c&&(o.nextStart<=c.end||c.gap)){const s=Math.max(Math.min(o.nextStart,c.end)-r,i);return Si.bufferInfo(e,r,s)}}return o}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 o=e.buffered;if(o){let c=e.len;const s=e.bufferedIndex;for(let f=o.length-1;f>s;f--)o[f].start=r}}return!1}reduceMaxBufferLength(e,r){const n=this.config,i=Math.max(Math.min(e-r,n.maxBufferLength),r),o=Math.max(e-r*3,n.maxMaxBufferLength/2,i);return o>=i?(n.maxMaxBufferLength=o,this.warn(`Reduce max buffer length to ${o}s`),!0):!1}getAppendedFrag(e,r=Tn.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:o}=this,c=r.fragmentStart,s=o.lowLatencyMode&&!!r.partList;let f=null;if(r.live){const _=o.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"):k!==null?(R=k,D="live edge"):(R=e,D="buffer pos"),R=o){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(xce(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(xce(this.config)&&e.type!==Tn.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 o=n==null?void 0:n.playerQueue;if(o)for(let c=o.length;c--;){const s=o[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,o=!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=bDt(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!i){const o=n.sn+1;if(o>=e.startSN&&o<=e.endSN){const c=r[o-e.startSN];n.cc===c.cc&&(i=c,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Z2e(e,n.cc,n.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const o=this.hls.liveSyncPosition;o!==null&&(i=this.getFragmentAtPosition(o,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,r,n){const{config:i}=this;let{fragPrevious:o}=this,{fragments:c,endSN:s}=n;const{fragmentHint:f}=n,{maxFragLookUpTolerance:p}=i,y=n.partList,_=!!(this.loadingParts&&y!=null&&y.length&&f);_&&!this.bitrateTest&&y[y.length-1].fragment.sn===f.sn&&(c=c.concat(f),s=f.sn);let T;if(er-p||(E=this.media)!=null&&E.paused||!this.startFragRequested?0:p;T=J_(o,c,e,P)}else T=c[c.length-1];if(T){const k=T.sn-n.startSN,P=this.fragmentTracker.getState(T);if((P===ll.OK||P===ll.PARTIAL&&T.gap)&&(o=T),o&&T.sn===o.sn&&(!_||y[0].fragment.sn>T.sn||!n.live)&&T.level===o.level){const D=c[k+1];T.sn${e.startSN} fragments: ${i}`),f}return o}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&&jo(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!==wr.FRAG_LOADING_WAITING_RETRY)&&(this.state=wr.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 o;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(o=this.fragCurrent)==null?void 0:o.url}`);return}const c=r.details===Jt.FRAG_GAP;c&&this.fragmentTracker.fragBuffered(i,!0);const s=r.errorAction;if(!s){this.state=wr.ERROR;return}const{action:f,flags:p,retryCount:y=0,retryConfig:_}=s,T=!!_,E=T&&f===Gl.RetryRequest,k=T&&!s.resolved&&p===Yu.MoveAllAlternatesMatchingHost,P=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!E&&k&&jo(i)&&!i.endList&&P&&!Q2e(r))this.resetFragmentErrors(e),this.treatAsGap(i),s.resolved=!0;else if((E||k)&&y<_.maxNumRetry){var R;const D=Bq((R=r.response)==null?void 0:R.code),M=hK(_,y);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+M,this.state=wr.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 ${y+1}/${_.maxNumRetry} in ${M}ms`)}else if(_)if(this.resetFragmentErrors(e),y<_.maxNumRetry)!c&&f!==Gl.RemoveAlternatePermanently&&(s.resolved=!0);else{this.warn(`${r.details} reached or exceeded max retry (${y})`);return}else f===Gl.SendAlternateToPenaltyBox?this.state=wr.WAITING_LEVEL:this.state=wr.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),r=this.retryDate,n=r===1/0;(!r||e>=r||n&&!Bq(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=wr.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===wr.PARSING||this.state===wr.PARSED){const r=e.frag,n=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,n),o=i&&i.len>.5;o&&this.reduceMaxBufferLength(i.len,(r==null?void 0:r.duration)||10);const c=!o;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===Tn.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==wr.STOPPED&&(this.state=wr.IDLE)}afterBufferFlushed(e,r,n){if(!e)return;const i=Si.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,i,n),this.state===wr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==wr.STOPPED&&(this.state=wr.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 o=n.details;if(!o){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((f,p)=>{const y=e.elementaryStreams[p];if(y){const _=y.endPTS-y.startPTS;if(_<=0)return this.warn(`Could not parse fragment ${e.sn} ${p} duration reliably (${_})`),f||!1;const T=i?0:oAe(o,e,y.startPTS,y.endPTS,y.startDTS,y.endDTS,this);return this.hls.trigger(je.LEVEL_PTS_UPDATED,{details:o,level:n,drift:T,type:p,frag:e,start:y.startPTS,end:y.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 p=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(p.message),this.hls.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,error:p,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=wr.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)})`),this.hls.trigger(je.FRAG_PARSED,{frag:e,part:r})}playlistLabel(){return this.playlistType===Tn.MAIN?"level":"track"}fragInfo(e,r=!0,n){var i,o;return`${this.playlistLabel()} ${e.level} (${n?"part":"frag"}:[${((i=r&&!n?e.startPTS:(n||e).start)!=null?i:NaN).toFixed(3)}-${((o=r&&!n?e.endPTS:(n||e).end)!=null?o: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 xce(t){return!!t.interstitialsController&&t.enableInterstitialPlayback!==!1}class pAe{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=aMt(e,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function aMt(t,e){const r=new Uint8Array(e);let n=0;for(let i=0;i0)return t.subarray(r,r+n)}function fMt(t,e,r,n){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],o=e[r+2],c=o>>2&15;if(c>12){const E=new Error(`invalid ADTS sampling index:${c}`);t.emit(je.ERROR,je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!0,error:E,reason:E.message});return}const s=(o>>6&3)+1,f=e[r+3]>>6&3|(o&1)<<2,p="mp4a.40."+s,y=i[c];let _=c;(s===5||s===29)&&(_-=3);const T=[s<<3|(_&14)>>1,(_&1)<<7|f<<3];return Us.log(`manifest codec:${n}, parsed codec:${p}, channels:${f}, rate:${y} (ADTS object type:${s} sampling index:${c})`),{config:T,samplerate:y,channelCount:f,codec:p,parsedCodec:p,manifestCodec:n}}function yAe(t,e){return t[e]===255&&(t[e+1]&246)===240}function xAe(t,e){return t[e+1]&1?7:9}function vK(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function mMt(t,e){return e+5=t.length)return!1;const n=vK(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||cO(t,i)}return!1}function _Ae(t,e,r,n,i){if(!t.samplerate){const o=fMt(e,r,n,i);if(!o)return;Xs(t,o)}}function vAe(t){return 1024*9e4/t}function yMt(t,e){const r=xAe(t,e);if(e+r<=t.length){const n=vK(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function bAe(t,e,r,n,i){const o=vAe(t.samplerate),c=n+i*o,s=yMt(e,r);let f;if(s){const{frameLength:_,headerLength:T}=s,E=T+_,k=Math.max(0,r+E-e.length);k?(f=new Uint8Array(E-T),f.set(e.subarray(r+T,e.length),0)):f=e.subarray(r+T,r+E);const P={unit:f,pts:c};return k||t.samples.push(P),{sample:P,length:E,missing:k}}const p=e.length-r;return f=new Uint8Array(p),f.set(e.subarray(r,e.length),0),{sample:{unit:f,pts:c},length:p,missing:-1}}function xMt(t,e){return _K(t,e)&&YF(t,e+6)+10<=t.length-e}function _Mt(t){return t instanceof ArrayBuffer?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function W$(t,e=0,r=1/0){return vMt(t,e,r,Uint8Array)}function vMt(t,e,r,n){const i=bMt(t);let o=1;"BYTES_PER_ELEMENT"in n&&(o=n.BYTES_PER_ELEMENT);const c=wMt(t)?t.byteOffset:0,s=(c+t.byteLength)/o,f=(c+e)/o,p=Math.floor(Math.max(0,Math.min(f,s))),y=Math.floor(Math.min(p+Math.max(r,0),s));return new n(i,p,y-p)}function bMt(t){return t instanceof ArrayBuffer?t:t.buffer}function wMt(t){return t&&t.buffer instanceof ArrayBuffer&&t.byteLength!==void 0&&t.byteOffset!==void 0}function SMt(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=cd(W$(t.data,1,n)),o=t.data[2+n],c=t.data.subarray(3+n).indexOf(0);if(c===-1)return;const s=cd(W$(t.data,3+n,c));let f;return i==="-->"?f=cd(W$(t.data,4+n+c)):f=_Mt(t.data.subarray(4+n+c)),e.mimeType=i,e.pictureType=o,e.description=s,e.data=f,e}function TMt(t){if(t.size<2)return;const e=cd(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}function EMt(t){if(t.size<2)return;if(t.type==="TXXX"){let r=1;const n=cd(t.data.subarray(r),!0);r+=n.length+1;const i=cd(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=cd(t.data.subarray(1));return{key:t.type,info:"",data:e}}function AMt(t){if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=cd(t.data.subarray(r),!0);r+=n.length+1;const i=cd(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=cd(t.data);return{key:t.type,info:"",data:e}}function jMt(t){return t.type==="PRIV"?TMt(t):t.type[0]==="W"?AMt(t):t.type==="APIC"?SMt(t):EMt(t)}function kMt(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=YF(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}}const jR=10,CMt=10;function wAe(t){let e=0;const r=[];for(;_K(t,e);){const n=YF(t,e+6);t[e+5]>>6&1&&(e+=jR),e+=jR;const i=e+n;for(;e+CMt0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:td.audioId3,duration:Number.POSITIVE_INFINITY});i{if(pn(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n};let kR=null;const PMt=[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],RMt=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],LMt=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],DMt=[0,1,1,4];function TAe(t,e,r,n,i){if(r+24>e.length)return;const o=EAe(e,r);if(o&&r+o.frameLength<=e.length){const c=o.samplesPerFrame*9e4/o.sampleRate,s=n+i*c,f={unit:e.subarray(r,r+o.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=o.channelCount,t.samplerate=o.sampleRate,t.samples.push(f),{sample:f,length:o.frameLength,missing:0}}}function EAe(t,e){const r=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,o=t[e+2]>>2&3;if(r!==1&&i!==0&&i!==15&&o!==3){const c=t[e+2]>>1&1,s=t[e+3]>>6,f=r===3?3-n:n===3?3:4,p=PMt[f*14+i-1]*1e3,_=RMt[(r===3?0:r===2?1:2)*3+o],T=s===3?1:2,E=LMt[r][n],k=DMt[n],P=E*8*k,R=Math.floor(E*p/_+c)*k;if(kR===null){const B=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);kR=B?parseInt(B[1]):0}return!!kR&&kR<=87&&n===2&&p>=224e3&&s===0&&(t[e+3]=t[e+3]|128),{sampleRate:_,channelCount:T,frameLength:R,samplesPerFrame:P}}}function SK(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function AAe(t,e){return e+1{let r=0,n=5;e+=n;const i=new Uint32Array(1),o=new Uint32Array(1),c=new Uint8Array(1);for(;n>0;){c[0]=t[e];const s=Math.min(n,8),f=8-s;o[0]=4278190080>>>24+f<>f,r=r?r<e.length||e[r]!==11||e[r+1]!==119)return-1;const o=e[r+4]>>6;if(o>=3)return-1;const s=[48e3,44100,32e3][o],f=e[r+4]&63,y=[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+o]*2;if(r+y>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,P=[2,1,2,3,3,4,4,5][_]+E,R=e[r+5]>>3,D=e[r+5]&7,M=new Uint8Array([o<<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+y);return t.config=M,t.channelCount=P,t.samplerate=s,t.samples.push({unit:G,pts:V}),y}class BMt extends wK{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=Fk(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&bK(r)!==void 0&&kAe(e,n)<=16)return!1;for(let i=e.length;n{const c=WLt(o);if(zMt.test(c.schemeIdUri)){const s=vce(c,r);let f=c.eventDuration===4294967295?Number.POSITIVE_INFINITY:c.eventDuration/c.timeScale;f<=.001&&(f=Number.POSITIVE_INFINITY);const p=c.payload;n.samples.push({data:p,len:p.byteLength,dts:s,pts:s,type:td.emsg,duration:f})}else if(this.config.enableEmsgKLVMetadata&&c.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const s=vce(c,r);n.samples.push({data:c.payload,len:c.payload.byteLength,dts:s,pts:s,type:td.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 vce(t,e){return pn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class UMt{constructor(e,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new fK(r,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ux.cbc)}decryptAacSample(e,r,n){const i=e[r].unit;if(i.length<=16)return;const o=i.subarray(16,i.length-i.length%16),c=o.buffer.slice(o.byteOffset,o.byteOffset+o.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 o=32;o{o.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 o=e[r].units;for(;!(n>=o.length);n++){const c=o[n];if(!(c.data.length<=48||c.type!==1&&c.type!==5)&&(this.decryptAvcSample(e,r,n,i,c),!this.decrypter.isSync()))return}}}}class IAe{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 o=n.units;i=o[o.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 o=n[i-1];e.pts=o.pts,e.dts=o.dts}else{r.dropped++;return}}r.samples.push(e)}}parseNALu(e,r,n){const i=r.byteLength;let o=e.naluState||0;const c=o,s=[];let f=0,p,y,_,T=-1,E=0;for(o===-1&&(T=0,E=this.getNALuType(r,0),o=0,f=1);f=0){const k={data:r.subarray(T,y),type:E};s.push(k)}else{const k=this.getLastNalUnit(e.samples);k&&(c&&f<=4-c&&k.state&&(k.data=k.data.subarray(0,k.data.byteLength-c)),y>0&&(k.data=oh(k.data,r.subarray(0,y)),k.state=0))}f=0&&o>=0){const k={data:r.subarray(T,i),type:E,state:o};s.push(k)}if(s.length===0){const k=this.getLastNalUnit(e.samples);k&&(k.data=oh(k.data,r))}return e.naluState=o,s}}class nj{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),o=Math.min(4,r);if(o===0)throw new Error("no bytes available");i.set(e.subarray(n,n+o)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=o*8,this.bytesAvailable-=o}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&&Us.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 VMt extends IAe{parsePES(e,r,n,i){const o=this.parseNALu(e,n.data,i);let c=this.VideoSample,s,f=!1;n.data=null,c&&o.length&&!e.audFound&&(this.pushAccessUnit(c,e),c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),o.forEach(p=>{var y,_;switch(p.type){case 1:{let P=!1;s=!0;const R=p.data;if(f&&R.length>4){const D=this.readSliceType(R);(D===2||D===4||D===7||D===9)&&(P=!0)}if(P){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=P;break}case 5:s=!0,(y=c)!=null&&y.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,cK(p.data,1,n.pts,r.samples);break}case 7:{var E,k;s=!0,f=!0;const P=p.data,R=this.readSPS(P);if(!e.sps||e.width!==R.width||e.height!==R.height||((E=e.pixelRatio)==null?void 0:E[0])!==R.pixelRatio[0]||((k=e.pixelRatio)==null?void 0:k[1])!==R.pixelRatio[1]){e.width=R.width,e.height=R.height,e.pixelRatio=R.pixelRatio,e.sps=[P];const D=P.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=[p.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(p)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}getNALuType(e,r){return e[r]&31}readSliceType(e){const r=new nj(e);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(e,r){let n=8,i=8,o;for(let c=0;c{var y,_;switch(p.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,(y=c)!=null&&y.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,cK(p.data,2,n.pts,r.samples);break;case 32:s=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Xs(e.params,this.readVPS(p.data)),this.initVPS=p.data),e.vps=[p.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],p.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const E=this.readSPS(p.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 k in E.params)e.params[k]=E.params[k]}this.pushParameterSet(e.sps,p.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(p.data);for(const k in E)e.params[k]=E[k]}this.pushParameterSet(e.pps,p.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(p)}),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 nj(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 nj(this.ebsp2rbsp(e));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const i=r.readBits(2),o=r.readBoolean(),c=r.readBits(5),s=r.readUByte(),f=r.readUByte(),p=r.readUByte(),y=r.readUByte(),_=r.readUByte(),T=r.readUByte(),E=r.readUByte(),k=r.readUByte(),P=r.readUByte(),R=r.readUByte(),D=r.readUByte(),M=[],B=[];for(let cr=0;cr0)for(let cr=n;cr<8;cr++)r.readBits(2);for(let cr=0;cr1&&r.readEG();for(let At=0;At0&&Mt<16?(ve=dr[Mt-1],We=ur[Mt-1]):Mt===255&&(ve=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 ur=r.readBoolean(),hr=r.readBoolean();let Xt=!1;(ur||hr)&&(Xt=r.readBoolean(),Xt&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),Xt&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let Pr=0;Pr<=n;Pr++){rt=r.readBoolean();const Rn=rt||r.readBoolean();let ci=!1;Rn?r.readEG():ci=r.readBoolean();const ti=ci?1:r.readUEG()+1;if(ur)for(let zi=0;zi>cr&1)<<31-cr)>>>0;let Sr=or.toString(16);return c===1&&Sr==="2"&&(Sr="6"),{codecString:`hvc1.${er}${c}.${Sr}.${o?"H":"L"}${D}.B0`,params:{general_tier_flag:o,general_profile_idc:c,general_profile_space:i,general_profile_compatibility_flags:[s,f,p,y],general_constraint_indicator_flags:[_,T,E,k,P,R],general_level_idc:D,bit_depth:_e+8,bit_depth_luma_minus8:_e,bit_depth_chroma_minus8:we,min_spatial_segmentation_idc:Se,chroma_format_idc:V,frame_rate:{fixed:rt,fps:Et/at}},width:pt,height:Nt,pixelRatio:[ve,We]}}readPPS(e){const r=new nj(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(),o=r.readBoolean();let c=1;return o&&i?c=0:o?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 El=188;class uy{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=uy.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(El*5,r-El)+1,i=0;for(;i1&&(c===0&&s>2||f+El>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:M2e[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=uy.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=uy.createTrack("audio",i),this._id3Track=uy.createTrack("id3"),this._txtTrack=uy.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 o;const c=this._videoTrack,s=this._audioTrack,f=this._id3Track,p=this._txtTrack;let y=c.pid,_=c.pesData,T=s.pid,E=f.pid,k=s.pesData,P=f.pesData,R=null,D=this.pmtParsed,M=this._pmtId,B=e.length;if(this.remainderData&&(e=oh(this.remainderData,e),B=e.length,this.remainderData=null),B>4;let ue;if(se>1){if(ue=Z+5+e[Z+4],ue===Z+El)continue}else ue=Z+4;switch(re){case y:Q&&(_&&(o=uw(_,this.logger))&&(this.readyVideoParser(c.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(c,p,o,!1)),_={data:[],size:0}),_&&(_.data.push(e.subarray(ue,Z+El)),_.size+=Z+El-ue);break;case T:if(Q){if(k&&(o=uw(k,this.logger)))switch(s.segmentCodec){case"aac":this.parseAACPES(s,o);break;case"mp3":this.parseMPEGPES(s,o);break;case"ac3":this.parseAC3PES(s,o);break}k={data:[],size:0}}k&&(k.data.push(e.subarray(ue,Z+El)),k.size+=Z+El-ue);break;case E:Q&&(P&&(o=uw(P,this.logger))&&this.parseID3PES(f,o),P={data:[],size:0}),P&&(P.data.push(e.subarray(ue,Z+El)),P.size+=Z+El-ue);break;case 0:Q&&(ue+=e[ue]+1),M=this._pmtId=GMt(e,ue);break;case M:{Q&&(ue+=e[ue]+1);const _e=HMt(e,ue,this.typeSupported,n,this.observer,this.logger);y=_e.videoPid,y>0&&(c.pid=y,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 ${Z} after unknown PID '${R}'. Backtracking to sync byte @${V} to parse all TS packets.`),R=null,Z=V-188),D=this.pmtParsed=!0;break}case 17:case 8191:break;default:R=re;break}}else G++;G>0&&Gq(this.observer,new Error(`Found ${G} TS packet/s that do not start with 0x47`),void 0,this.logger),c.pesData=_,s.pesData=k,f.pesData=P;const W={audioTrack:s,videoTrack:c,id3Track:f,textTrack:p};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:o}=e,c=n.pesData,s=r.pesData,f=i.pesData;let p;if(c&&(p=uw(c,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,o,p,!0),n.pesData=null)):n.pesData=c,s&&(p=uw(s,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,p);break;case"mp3":this.parseMPEGPES(r,p);break;case"ac3":this.parseAC3PES(r,p);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&&(p=uw(f,this.logger))?(this.parseID3PES(i,p),i.pesData=null):i.pesData=f}demuxSampleAes(e,r,n){const i=this.demux(e,n,!0,!this.config.progressive),o=this.sampleAes=new UMt(this.observer,this.config,r);return this.decrypt(i,o)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new VMt:e==="hevc"&&(this.videoParser=new qMt))}decrypt(e,r){return new Promise(n=>{const{audioTrack:i,videoTrack:o}=e;i.samples&&i.segmentCodec==="aac"?r.decryptAacSamples(i.samples,0,()=>{o.samples?r.decryptAvcSamples(o.samples,0,0,()=>{n(e)}):n(e)}):o.samples&&r.decryptAvcSamples(o.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 o=r.data;if(i){this.aacOverFlow=null;const _=i.missing,T=i.sample.unit.byteLength;if(_===-1)o=oh(i.sample.unit,o);else{const E=T-_;i.sample.unit.set(o.subarray(0,_),E),e.samples.push(i.sample),n=i.missing}}let c,s;for(c=n,s=o.length;c0;)s+=f}}parseID3PES(e,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Xs({},r,{type:this._videoTrack?td.emsg:td.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function qq(t,e){return((t[e+1]&31)<<8)+t[e+2]}function GMt(t,e){return(t[e+10]&31)<<8|t[e+11]}function HMt(t,e,r,n,i,o){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,p=(t[e+10]&15)<<8|t[e+11];for(e+=12+p;e0){let T=e+5,E=_;for(;E>2;){switch(t[T]){case 106:r.ac3!==!0?o.log("AC-3 audio found, not supported in this browser for now"):(c.audioPid=y,c.segmentAudioCodec="ac3");break}const P=t[T+1]+2;T+=P,E-=P}}break;case 194:case 135:return Gq(i,new Error("Unsupported EC-3 in M2TS found"),void 0,o),c;case 36:c.videoPid===-1&&(c.videoPid=y,c.segmentVideoCodec="hevc",o.log("HEVC in M2TS found"));break}e+=_+5}return c}function Gq(t,e,r,n){n.warn(`parsing error: ${e.message}`),t.emit(je.ERROR,je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function K$(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function uw(t,e){let r=0,n,i,o,c,s;const f=t.data;if(!t||t.size===0)return null;for(;f[0].length<19&&f.length>1;)f[0]=oh(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 y=n[7];y&192&&(c=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,y&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),o=n[8];let _=o+9;if(t.size<=_)return null;t.size-=_;const T=new Uint8Array(t.size);for(let E=0,k=f.length;EP){_-=P;continue}else n=n.subarray(_),P-=_,_=0;T.set(n,r),r+=P}return i&&(i-=o+3),{data:T,pts:c,dts:s,len:i}}return null}class WMt{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 Yg=Math.pow(2,32)-1;class Zt{static init(){Zt.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 Zt.types)Zt.types.hasOwnProperty(e)&&(Zt.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]);Zt.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]),o=new Uint8Array([0,0,0,0,0,0,0,0]);Zt.STTS=Zt.STSC=Zt.STCO=o,Zt.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Zt.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Zt.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Zt.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]);Zt.FTYP=Zt.box(Zt.types.ftyp,c,f,c,s),Zt.DINF=Zt.box(Zt.types.dinf,Zt.box(Zt.types.dref,i))}static box(e,...r){let n=8,i=r.length;const o=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 Zt.box(Zt.types.mdia,Zt.mdhd(e.timescale||0,e.duration||0),Zt.hdlr(e.type),Zt.minf(e))}static mfhd(e){return Zt.box(Zt.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"?Zt.box(Zt.types.minf,Zt.box(Zt.types.smhd,Zt.SMHD),Zt.DINF,Zt.stbl(e)):Zt.box(Zt.types.minf,Zt.box(Zt.types.vmhd,Zt.VMHD),Zt.DINF,Zt.stbl(e))}static moof(e,r,n){return Zt.box(Zt.types.moof,Zt.mfhd(e),Zt.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=Zt.trak(e[r]);return Zt.box.apply(null,[Zt.types.moov,Zt.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(Zt.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=Zt.trex(e[r]);return Zt.box.apply(null,[Zt.types.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(Yg+1)),i=Math.floor(r%(Yg+1)),o=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 Zt.box(Zt.types.mvhd,o)}static sdtp(e){const r=e.samples||[],n=new Uint8Array(4+r.length);let i,o;for(i=0;i>>8&255),r.push(c&255),r=r.concat(Array.prototype.slice.call(o));for(i=0;i>>8&255),n.push(c&255),n=n.concat(Array.prototype.slice.call(o));const s=Zt.box(Zt.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,p=e.height,y=e.pixelRatio[0],_=e.pixelRatio[1];return Zt.box(Zt.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,p>>8&255,p&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,Zt.box(Zt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Zt.box(Zt.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&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 Zt.box(Zt.types.mp4a,Zt.audioStsd(e),Zt.box(Zt.types.esds,Zt.esds(e)))}static mp3(e){return Zt.box(Zt.types[".mp3"],Zt.audioStsd(e))}static ac3(e){return Zt.box(Zt.types["ac-3"],Zt.audioStsd(e),Zt.box(Zt.types.dac3,e.config))}static stsd(e){const{segmentCodec:r}=e;if(e.type==="audio"){if(r==="aac")return Zt.box(Zt.types.stsd,Zt.STSD,Zt.mp4a(e));if(r==="ac3"&&e.config)return Zt.box(Zt.types.stsd,Zt.STSD,Zt.ac3(e));if(r==="mp3"&&e.codec==="mp3")return Zt.box(Zt.types.stsd,Zt.STSD,Zt.mp3(e))}else if(e.pps&&e.sps){if(r==="avc")return Zt.box(Zt.types.stsd,Zt.STSD,Zt.avc1(e));if(r==="hevc"&&e.vps)return Zt.box(Zt.types.stsd,Zt.STSD,Zt.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,o=e.height||0,c=Math.floor(n/(Yg+1)),s=Math.floor(n%(Yg+1));return Zt.box(Zt.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,o>>8&255,o&255,0,0]))}static traf(e,r){const n=Zt.sdtp(e),i=e.id,o=Math.floor(r/(Yg+1)),c=Math.floor(r%(Yg+1));return Zt.box(Zt.types.traf,Zt.box(Zt.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),Zt.box(Zt.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,c>>24,c>>16&255,c>>8&255,c&255])),Zt.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Zt.box(Zt.types.trak,Zt.tkhd(e),Zt.mdia(e))}static trex(e){const r=e.id;return Zt.box(Zt.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,o=12+16*i,c=new Uint8Array(o);let s,f,p,y,_,T;for(r+=8+o,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,p>>>16&255,p>>>8&255,p&255,y>>>24&255,y>>>16&255,y>>>8&255,y&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 Zt.box(Zt.types.trun,c)}static initSegment(e){Zt.types||Zt.init();const r=Zt.moov(e);return oh(Zt.FTYP,r)}static hvc1(e){const r=e.params,n=[e.vps,e.sps,e.pps],i=4,o=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=o.length;for(let k=0;k>8,n[k][P].length&255]),c),c+=2,s.set(n[k][P],c),c+=n[k][P].length}const p=Zt.box(Zt.types.hvcC,s),y=e.width,_=e.height,T=e.pixelRatio[0],E=e.pixelRatio[1];return Zt.box(Zt.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,y>>8&255,y&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]),p,Zt.box(Zt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Zt.box(Zt.types.pasp,new Uint8Array([T>>24,T>>16&255,T>>8&255,T&255,E>>24,E>>16&255,E>>8&255,E&255])))}}Zt.types=void 0;Zt.HDLR_TYPES=void 0;Zt.STTS=void 0;Zt.STSC=void 0;Zt.STCO=void 0;Zt.STSZ=void 0;Zt.VMHD=void 0;Zt.SMHD=void 0;Zt.STSD=void 0;Zt.FTYP=void 0;Zt.DINF=void 0;const NAe=9e4;function TK(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function KMt(t,e,r=1,n=!1){return TK(t,e,1/r,n)}function oA(t,e=!1){return TK(t,1e3,1/NAe,e)}function YMt(t,e=1){return TK(t,NAe,1/e)}function bce(t){const{baseTime:e,timescale:r,trackId:n}=t;return`${e/r} (${e}/${r}) trackId: ${n}`}const ZMt=10*1e3,XMt=1024,QMt=1152,JMt=1536;let dw=null,Y$=null;function wce(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 NL extends hh{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,dw===null){const c=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);dw=c?parseInt(c[1]):0}if(Y$===null){const o=navigator.userAgent.match(/Safari\/(\d+)/i);Y$=o?parseInt(o[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&&bce(r)} > ${e&&bce(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((o,c)=>{let s=c.pts,f=s-o;return f<-4294967296&&(r=!0,s=Zu(s,n),f=s-o),f>0?o:s},n);return r&&this.debug("PTS rollover detected"),i}remux(e,r,n,i,o,c,s,f){let p,y,_,T,E,k,P=o,R=o;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 Z,Q,re,se;const Ce=this.videoTrackConfig;(Ce&&(r.width!==Ce.width||r.height!==Ce.height||((Z=r.pixelRatio)==null?void 0:Z[0])!==((Q=Ce.pixelRatio)==null?void 0:Q[0])||((re=r.pixelRatio)==null?void 0:re[1])!==((se=Ce.pixelRatio)==null?void 0:se[1]))||!Ce&&G||this.nextAudioTs===null&&V)&&this.resetInitSegment()}this.ISGenerated||(_=this.generateIS(e,r,o,c));const ue=this.isVideoContiguous;let _e=-1,we;if(G&&(_e=eOt(r.samples),!ue&&this.config.forceKeyFrameOnDiscontinuity))if(k=!0,_e>0){this.warn(`Dropped ${_e} out of ${B} video samples due to a missing keyframe`);const Ce=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(_e),r.dropped+=_e,R+=(r.samples[0].pts-Ce)/r.inputTimeScale,we=R}else _e===-1&&(this.warn(`No keyframe found out of ${B} video samples`),k=!1);if(this.ISGenerated){if(V&&G){const Ce=this.getVideoStartPts(r.samples),Ae=(Zu(e.samples[0].pts,Ce)-Ce)/r.inputTimeScale;P+=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,o,c)),y=this.remuxAudio(e,P,this.isAudioContiguous,c,M||G||f===Tn.AUDIO?R:void 0),G){const Ce=y?y.endPTS-y.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),_=this.generateIS(e,r,o,c)),p=this.remuxVideo(r,R,ue,Ce)}}else G&&(p=this.remuxVideo(r,R,ue,0));p&&(p.firstKeyFrame=_e,p.independent=_e!==-1,p.firstKeyFramePTS=we)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(E=PAe(n,o,this._initPTS,this._initDTS)),i.samples.length&&(T=RAe(i,o,this._initPTS))),{audio:y,video:p,initSegment:_,independent:k,text:T,id3:E}}computeInitPts(e,r,n,i){const o=Math.round(n*r);let c=Zu(e,o);if(c0?Se-1:Se].dts&&(M=!0)}M&&c.sort(function(Se,ve){const We=Se.dts-ve.dts,rt=Se.pts-ve.pts;return We||rt}),k=c[0].dts,P=c[c.length-1].dts;const V=P-k,G=V?Math.round(V/(f-1)):E||e.inputTimeScale/30;if(n){const Se=k-B,ve=Se>G,We=Se<-1;if((ve||We)&&(ve?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${oA(Se,!0)} ms (${Se}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${oA(-Se,!0)} ms (${Se}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!We||B>=c[0].pts||dw)){k=B;const rt=c[0].pts-Se;if(ve)c[0].dts=k,c[0].pts=rt;else{let at=!0;for(let Et=0;Etrt&&at);Et++){const _t=c[Et].pts;if(c[Et].dts-=Se,c[Et].pts-=Se,Et0?ve.dts-c[Se-1].dts:G;if(at=Se>0?ve.pts-c[Se-1].pts:G,_t.stretchShortVideoTrack&&this.nextAudioTs!==null){const pt=Math.floor(_t.maxBufferHole*o),Nt=(i?R+i*o:this.nextAudioTs+y)-ve.pts;Nt>pt?(E=Nt-Vt,E<0?E=Vt:_e=!0,this.log(`It is approximately ${Nt/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(ve.pts-ve.dts);we=Math.min(we,E),Me=Math.max(Me,E),Ce=Math.min(Ce,at),Ae=Math.max(Ae,at),s.push(wce(ve.key,E,rt,Et))}if(s.length){if(dw){if(dw<70){const Se=s[0].flags;Se.dependsOn=2,Se.isNonSync=0}}else if(Y$&&Ae-Ce0&&(i&&Math.abs(B-(D+M))<9e3||Math.abs(Zu(P[0].pts,B)-(D+M))<20*y),P.forEach(function(Ae){Ae.pts=Zu(Ae.pts,B)}),!n||D<0){const Ae=P.length;if(P=P.filter(be=>be.pts>=0),Ae!==P.length&&this.warn(`Removed ${P.length-Ae} of ${Ae} samples (initPTS ${M} / ${c})`),!P.length)return;o===0?D=0:i&&!k?D=Math.max(0,B-M):D=P[0].pts-M}if(e.segmentCodec==="aac"){const Ae=this.config.maxAudioFramesDrift;for(let be=0,me=D+M;be=Ae*y&&ve0){Z+=R;try{W=new Uint8Array(Z)}catch(ve){this.observer.emit(je.ERROR,je.ERROR,{type:Dn.MUX_ERROR,details:Jt.REMUX_ALLOC_ERROR,fatal:!1,error:ve,bytes:Z,reason:`fail allocating audio mdat ${Z}`});return}T||(new DataView(W.buffer).setUint32(0,Z),W.set(Zt.types.mdat,4))}else return;W.set(Pe,R);const Se=Pe.byteLength;R+=Se,E.push(wce(!0,p,Se,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):Zt.moof(e.sequenceNumber++,V/f,Xs({},e,{samples:E}));e.samples=[];const _e=(V-M)/c,we=this.nextAudioTs/c,Me={data1:ue,data2:W,startPTS:_e,endPTS:we,startDTS:_e,endDTS:we,type:"audio",hasAudio:!0,hasVideo:!1,nb:re};return this.isAudioContiguous=!0,Me}}function Zu(t,e){let r;if(e===null)return t;for(e4294967296;)t+=r;return t}function eOt(t){for(let e=0;ec.pts-s.pts);const o=t.samples;return t.samples=[],{samples:o}}class tOt extends hh{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:o,video:c}=this.initData=B2e(e);if(r)ULt(e,r);else{const f=o||c;f!=null&&f.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${f.codec}")!`)}o&&(n=Sce(o,ta.AUDIO,this)),c&&(i=Sce(c,ta.VIDEO,this));const s={};o&&c?s.audiovideo={container:"video/mp4",codec:n+","+i,supplemental:c.supplemental,encrypted:c.encrypted,initSegment:e,id:"main"}:o?s.audio={container:"audio/mp4",codec:n,encrypted:o.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,o,c){var s,f;let{initPTS:p,lastEndTime:y}=this;const _={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};pn(y)||(y=this.lastEndTime=o||0);const T=r.samples;if(!T.length)return _;const E={initPTS:void 0,timescale:void 0,trackId:void 0};let k=this.initData;if((s=k)!=null&&s.length||(this.generateInitSegment(T),k=this.initData),!((f=k)!=null&&f.length))return this.warn("Failed to generate initSegment."),_;this.emitInitSegment&&(E.tracks=this.initTracks,this.emitInitSegment=!1);const P=qLt(T,k,this),R=k.audio?P[k.audio.id]:null,D=k.video?P[k.video.id]:null,M=CR(D,1/0),B=CR(R,1/0),V=CR(D,0,!0),G=CR(R,0,!0);let W=o,Z=0;const Q=R&&(!D||!p&&B0?this.lastEndTime=ue:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _e=!!k.audio,we=!!k.video;let Ce="";_e&&(Ce+="audio"),we&&(Ce+="video");const Me=(k.audio?k.audio.encrypted:!1)||(k.video?k.video.encrypted:!1),Ae={data1:T,startPTS:se,startDTS:se,endPTS:ue,endDTS:ue,type:Ce,hasAudio:_e,hasVideo:we,nb:1,dropped:0,encrypted:Me};_.audio=_e&&!we?Ae:void 0,_.video=we?Ae:void 0;const be=D==null?void 0:D.sampleCount;if(be){const me=D.keyFrameIndex,Pe=me!==-1;Ae.nb=be,Ae.dropped=me===0||this.isVideoContiguous?0:Pe?me:be,Ae.independent=Pe,Ae.firstKeyFrame=me,Pe&&D.keyFrameStart&&(Ae.firstKeyFramePTS=(D.keyFrameStart-p.baseTime)/p.timescale),this.isVideoContiguous||(_.independent=Pe),this.isVideoContiguous||(this.isVideoContiguous=Pe),Ae.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${me}/${be} dropped: ${Ae.dropped} start: ${Ae.firstKeyFramePTS||"NA"}`)}return _.initSegment=E,_.id3=PAe(n,o,p,p),i.samples.length&&(_.text=RAe(i,o,p)),_}}function CR(t,e,r=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(r?t.duration:0))/t.timescale:e}function rOt(t,e,r,n){if(t===null)return!0;const i=Math.max(n,1),o=e-t.baseTime/t.timescale;return Math.abs(o-r)>i}function Sce(t,e,r){const n=t.codec;return n&&n.length>4?n:e===ta.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?tO(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 gp;try{gp=self.performance.now.bind(self.performance)}catch{gp=Date.now}const PL=[{demux:$Mt,remux:tOt},{demux:uy,remux:NL},{demux:OMt,remux:NL},{demux:BMt,remux:NL}];PL.splice(2,0,{demux:FMt,remux:NL});class Tce{constructor(e,r,n,i,o,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=o,this.logger=c}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){const o=n.transmuxing;o.executeStart=gp();let c=new Uint8Array(e);const{currentTransmuxState:s,transmuxConfig:f}=this;i&&(this.currentTransmuxState=i);const{contiguous:p,discontinuity:y,trackSwitch:_,accurateTimeOffset:T,timeOffset:E,initSegmentChange:k}=i||s,{audioCodec:P,videoCodec:R,defaultInitPts:D,duration:M,initSegmentData:B}=f,V=nOt(c,r);if(V&&c1(V.method)){const Q=this.getDecrypter(),re=pK(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 o.executeEnd=gp(),Z$(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(y,_);if(G){const Q=this.configureTransmuxer(c);if(Q)return this.logger.warn(`[transmuxer] ${Q.message}`),this.observer.emit(je.ERROR,je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,error:Q,reason:Q.message}),o.executeEnd=gp(),Z$(n)}(y||_||k||G)&&this.resetInitSegment(B,P,R,M,r),(y||k||G)&&this.resetInitialTimestamp(D),p||this.resetContiguity();const W=this.transmux(c,V,E,T,n);this.asyncResult=Bk(W);const Z=this.currentTransmuxState;return Z.contiguous=!0,Z.discontinuity=!1,Z.trackSwitch=!1,o.executeEnd=gp(),W}flush(e){const r=e.transmuxing;r.executeStart=gp();const{decrypter:n,currentTransmuxState:i,decryptionPromise:o}=this;if(o)return this.asyncResult=!0,o.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:p}=this;if(!f||!p){r.executeEnd=gp();const _=[Z$(e)];return this.asyncResult?Promise.resolve(_):_}const y=f.flush(s);return Bk(y)?(this.asyncResult=!0,y.then(_=>(this.flushRemux(c,_,e),c))):(this.flushRemux(c,y,e),this.asyncResult?Promise.resolve(c):c)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:o,id3Track:c,textTrack:s}=r,{accurateTimeOffset:f,timeOffset:p}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===Tn.MAIN?"level":"track"} ${n.level}`);const y=this.remuxer.remux(i,o,c,s,p,f,!0,this.id);e.push({remuxResult:y,chunkMeta:n}),n.transmuxing.executeEnd=gp()}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,o){const{demuxer:c,remuxer:s}=this;!c||!s||(c.resetInitSegment(e,r,n,i),s.resetInitSegment(e,r,n,o))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,o){let c;return r&&r.method==="SAMPLE-AES"?c=this.transmuxSampleAes(e,r,n,i,o):c=this.transmuxUnencrypted(e,n,i,o),c}transmuxUnencrypted(e,r,n,i){const{audioTrack:o,videoTrack:c,id3Track:s,textTrack:f}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(o,c,s,f,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,o){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:o}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i}=this;let o;for(let _=0,T=PL.length;_0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const Z$=t=>({remuxResult:{},chunkMeta:t});function Bk(t){return"then"in t&&t.then instanceof Function}class iOt{constructor(e,r,n,i,o){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=o||null}}class sOt{constructor(e,r,n,i,o,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=o,this.initSegmentChange=c}}let Ece=0;class LAe{constructor(e,r,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ece++,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 p=f.data,y=this.hls;if(!(!y||!(p!=null&&p.event)||p.instanceNo!==this.instanceNo))switch(p.event){case"init":{var _;const T=(_=this.workerContext)==null?void 0:_.objectURL;T&&self.URL.revokeObjectURL(T);break}case"transmuxComplete":{this.handleTransmuxComplete(p.data);break}case"flush":{this.onFlush(p.data);break}case"workerLog":{y.logger[p.data.logType]&&y.logger[p.data.logType](p.data.message);break}default:{p.data=p.data||{},p.data.frag=this.frag,p.data.part=this.part,p.data.id=this.id,y.trigger(p.event,p.data);break}}},this.onWorkerError=f=>{if(!this.hls)return;const p=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(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:p})};const o=e.config;this.hls=e,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const c=(f,p)=>{p=p||{},p.frag=this.frag||void 0,f===je.ERROR&&(p=p,p.parent=this.id,p.part=this.part,this.error=p.error),this.hls.trigger(f,p)};this.observer=new xK,this.observer.on(je.FRAG_DECRYPTED,c),this.observer.on(je.ERROR,c);const s=zle(o.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const f=this.hls.logger;if(o.workerPath||cMt()){try{o.workerPath?(f.log(`loading Web Worker ${o.workerPath} for "${r}"`),this.workerContext=dMt(o.workerPath)):(f.log(`injecting Web Worker for "${r}"`),this.workerContext=uMt());const{worker:y}=this.workerContext;y.addEventListener("message",this.onWorkerMessage),y.addEventListener("error",this.onWorkerError),y.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:s,id:r,config:sa(o)})}catch(y){f.warn(`Error setting up "${r}" Web Worker, fallback to inline`,y),this.terminateWorker(),this.error=null,this.transmuxer=new Tce(this.observer,s,o,"",r,e.logger)}return}}this.transmuxer=new Tce(this.observer,s,o,"",r,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Ece++;const r=this.hls.config,n=zle(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:sa(r)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),hMt(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,o,c,s,f,p,y){var _,T;p.transmuxing.start=self.performance.now();const{instanceNo:E,transmuxer:k}=this,P=c?c.start:o.start,R=o.decryptdata,D=this.frag,M=!(D&&o.cc===D.cc),B=!(D&&p.level===D.level),V=D?p.sn-D.sn:-1,G=this.part?p.part-this.part.index:-1,W=V===0&&p.id>1&&p.id===(D==null?void 0:D.stats.chunkCount),Z=!B&&(V===1||V===0&&(G===1||W&&G<=0)),Q=self.performance.now();(B||V||o.stats.parsing.start===0)&&(o.stats.parsing.start=Q),c&&(G||!Z)&&(c.stats.parsing.start=Q);const re=!(D&&((_=o.initSegment)==null?void 0:_.url)===((T=D.initSegment)==null?void 0:T.url)),se=new sOt(M,Z,f,B,P,re);if(!Z||M||re){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${o.type} sn: ${p.sn}${p.part>-1?" part: "+p.part:""} ${this.id===Tn.MAIN?"level":"track"}: ${p.level} id: ${p.id} discontinuity: ${M} trackSwitch: ${B} contiguous: ${Z} accurateTimeOffset: ${f} timeOffset: ${P} initSegmentChange: ${re}`);const ue=new iOt(n,i,r,s,y);this.configureTransmuxer(ue)}if(this.frag=o,this.part=c,this.workerContext)this.workerContext.worker.postMessage({instanceNo:E,cmd:"demux",data:e,decryptdata:R,chunkMeta:p,state:se},e instanceof ArrayBuffer?[e]:[]);else if(k){const ue=k.push(e,R,p,se);Bk(ue)?ue.then(_e=>{this.handleTransmuxComplete(_e)}).catch(_e=>{this.transmuxerError(_e,p,"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);Bk(i)?i.then(o=>{this.handleFlushResult(o,e)}).catch(o=>{this.transmuxerError(o,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.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 Ace=100;class aOt extends yK{constructor(e,r,n){super(e,r,n,"audio-stream-controller",Tn.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(je.LEVEL_LOADED,this.onLevelLoaded,this),e.on(je.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(je.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(je.BUFFER_RESET,this.onBufferReset,this),e.on(je.BUFFER_CREATED,this.onBufferCreated,this),e.on(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(je.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(je.FRAG_LOADING,this.onFragLoading,this),e.on(je.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(je.LEVEL_LOADED,this.onLevelLoaded,this),e.off(je.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(je.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(je.BUFFER_RESET,this.onBufferReset,this),e.off(je.BUFFER_CREATED,this.onBufferCreated,this),e.off(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(je.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(je.FRAG_LOADING,this.onFragLoading,this),e.off(je.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:o,trackId:c}){if(n===Tn.MAIN){const s=r.cc,f=this.fragCurrent;if(this.initPTS[s]={baseTime:i,timescale:o,trackId:c},this.log(`InitPTS for cc: ${s} found from main: ${i/o} (${i}/${o}) trackId: ${c}`),this.mainAnchor=r,this.state===wr.WAITING_INIT_PTS){const p=this.waitingData;(!p&&!this.loadingParts||p&&p.frag.cc!==s)&&this.syncWithAnchor(r,p==null?void 0:p.frag)}else!this.hls.hasEnoughToStart&&f&&f.cc!==s?(f.abortRequests(),this.syncWithAnchor(r,f)):this.state===wr.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 o=(i||e).cc,c=this.getLevelDetails(),s=this.getLoadPosition(),f=Z2e(c,o,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===wr.IDLE&&this.doTickIdle())}startLoad(e,r){if(!this.levels){this.startPosition=e,this.state=wr.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(Ace),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=wr.IDLE):this.state=wr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}doTick(){switch(this.state){case wr.IDLE:this.doTickIdle();break;case wr.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=wr.WAITING_INIT_PTS}break}case wr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case wr.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:r,part:n,cache:i,complete:o}=e,c=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=wr.FRAG_LOADING;const s=i.flush().buffer,f={frag:r,part:n,payload:s,networkDetails:null};this._handleFragmentLoadProgress(f),o&&super._handleFragmentLoadComplete(f)}else c&&c.cc!==e.frag.cc&&this.syncWithAnchor(c,e.frag)}else this.state=wr.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:o}=this,c=r.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!c.startFragPrefetch)||!(n!=null&&n[o]))return;const s=n[o],f=s.details;if(!f||this.waitForLive(s)||this.waitForCdnTuneIn(f)){this.state=wr.WAITING_TRACK,this.startFragRequested=!1;return}const p=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&p&&(this.bufferFlushed=!1,this.afterBufferFlushed(p,ta.AUDIO,Tn.AUDIO));const y=this.getFwdBufferInfo(p,Tn.AUDIO);if(y===null)return;if(!this.switchingTrack&&this._streamEnded(y,f)){r.trigger(je.BUFFER_EOS,{type:"audio"}),this.state=wr.ENDED;return}const _=y.len,T=r.maxBufferLength,E=f.fragments,k=E[0].start,P=this.getLoadPosition(),R=this.flushing?P:y.end;if(this.switchingTrack&&i){const B=P;f.PTSKnown&&Bk||y.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=k+.05)}if(_>=T&&!this.switchingTrack&&RM.end){const V=this.fragmentTracker.getFragAtPos(R,Tn.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 Mk(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!==wr.STOPPED&&(this.setInterval(Ace),this.state=wr.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(je.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,r){var n;const{levels:i}=this,{details:o,id:c,groupId:s,track:f}=r;if(!i){this.warn(`Audio tracks reset while loading track ${c} "${f.name}" of "${s}"`);return}const p=this.mainDetails;if(!p||o.endCC>p.endCC||p.expired){this.cachedTrackLoadedData=r,this.state!==wr.STOPPED&&(this.state=wr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${c} "${f.name}" of "${s}" loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`);const y=i[c];let _=0;if(o.live||(n=y.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;if(y.details){var T;_=this.alignPlaylists(o,y.details,(T=this.levelLastLoaded)==null?void 0:T.details)}o.alignedSliding||(mAe(o,p),o.alignedSliding||lO(o,p),_=o.fragmentStart)}y.details=o,this.levelLastLoaded=y,this.startFragRequested||this.setStartPosition(p,_),this.hls.trigger(je.AUDIO_TRACK_UPDATED,{details:o,id:c,groupId:r.groupId}),this.state===wr.WAITING_TRACK&&!this.waitForCdnTuneIn(o)&&(this.state=wr.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const n=e.frag,{part:i,payload:o}=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 p=f[s];if(!p){this.warn("Audio track is undefined on fragment load progress");return}const y=p.details;if(!y){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const _=c.defaultAudioCodec||p.audioCodec||"mp4a.40.2";let T=this.transmuxer;T||(T=this.transmuxer=new LAe(this.hls,Tn.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const E=this.initPTS[n.cc],k=(r=n.initSegment)==null?void 0:r.data;if(E!==void 0){const R=i?i.index:-1,D=R!==-1,M=new mK(n.level,n.sn,n.stats.chunkCount,o.byteLength,R,D);T.push(o,k,_,"",n,i,y.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 [${y.startSN} ,${y.endSN}],track ${s}`);const{cache:P}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new pAe,complete:!1};P.push(new Uint8Array(o)),this.state!==wr.STOPPED&&(this.state=wr.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===Tn.MAIN&&jo(r.frag)&&(this.mainFragLoading=r,this.state===wr.IDLE&&this.tick())}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==Tn.AUDIO){!this.audioOnly&&n.type===Tn.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(jo(n)){this.fragPrevious=n;const o=this.switchingTrack;o&&(this.bufferedTrack=o,this.switchingTrack=null,this.hls.trigger(je.AUDIO_TRACK_SWITCHED,zs({},o)))}this.fragBufferedComplete(n,i),this.media&&this.tick()}onError(e,r){var n;if(r.fatal){this.state=wr.ERROR;return}switch(r.details){case Jt.FRAG_GAP:case Jt.FRAG_PARSING_ERROR:case Jt.FRAG_DECRYPT_ERROR:case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Tn.AUDIO,r);break;case Jt.AUDIO_TRACK_LOAD_ERROR:case Jt.AUDIO_TRACK_LOAD_TIMEOUT:case Jt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===wr.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===Hi.AUDIO_TRACK&&(this.state=wr.IDLE);break;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Jt.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Jt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==ta.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==ta.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===wr.ENDED&&(this.state=wr.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,Tn.AUDIO),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:o,chunkMeta:c}=e,s=this.getCurrentContext(c);if(!s){this.resetWhenMissingContext(c);return}const{frag:f,part:p,level:y}=s,{details:_}=y,{audio:T,text:E,id3:k,initSegment:P}=o;if(this.fragContextChanged(f)||!_){this.fragmentTracker.removeFragment(f);return}if(this.state=wr.PARSING,this.switchingTrack&&T&&this.completeAudioSwitch(this.switchingTrack),P!=null&&P.tracks){const R=f.initSegment||f;if(this.unhandledEncryptionError(P,f))return;this._bufferInitSegment(y,P.tracks,R,c),i.trigger(je.FRAG_PARSING_INIT_SEGMENT,{frag:R,id:n,tracks:P.tracks})}if(T){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=T;p&&(p.elementaryStreams[ta.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),f.setElementaryStreamInfo(ta.AUDIO,R,D,M,B),this.bufferFragmentData(T,f,p,c)}if(k!=null&&(r=k.samples)!=null&&r.length){const R=Xs({id:n,frag:f,details:_},k);i.trigger(je.FRAG_PARSING_METADATA,R)}if(E){const R=Xs({id:n,frag:f,details:_},E);i.trigger(je.FRAG_PARSING_USERDATA,R)}}_bufferInitSegment(e,r,n,i){if(this.state!==wr.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const o=r.audio;o.id=Tn.AUDIO;const c=e.audioCodec;this.log(`Init audio buffer, container:${o.container}, codecs[level/parsed]=[${c}/${o.codec}]`),c&&c.split(",").length===1&&(o.levelCodec=c),this.hls.trigger(je.BUFFER_CODECS,r);const s=o.initSegment;if(s!=null&&s.byteLength){const f={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:s};this.hls.trigger(je.BUFFER_APPENDING,f)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===ll.NOT_LOADED||i===ll.PARTIAL){var o;if(!jo(e))this._loadInitSegment(e,r);else if((o=r.details)!=null&&o.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=wr.WAITING_INIT_PTS;const c=this.mainDetails;c&&c.fragmentStart!==r.details.fragmentStart&&lO(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:o,audioCodec:c,channels:s}=this.bufferedTrack;P_({name:r,lang:n,assocLang:i,characteristics:o,audioCodec:c,channels:s},e,r_)||(nO(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(je.AUDIO_TRACK_SWITCHED,zs({},e))}}class EK extends hh{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 o=-1;for(let c=0;c=0&&y>r.partTarget&&(f+=1)}const p=n&&$le(n);return new Ule(s,f>=0?f:void 0,p)}}}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:o}=r,c=self.performance.now(),s=o.loading.first?Math.max(0,c-o.loading.first):0;i.advancedDateTime=Date.now()-s;const f=this.hls.config.timelineOffset;if(f!==i.appliedTimelineOffset){const y=Math.max(f||0,0);i.appliedTimelineOffset=y,i.fragments.forEach(_=>{_.setStart(_.playlistOffset+y)})}if(i.live||n!=null&&n.live){const y="levelInfo"in r?r.levelInfo:r.track;if(i.reloaded(n),n&&i.fragments.length>0){QDt(n,i,this);const M=i.playlistParsingError;if(M){this.warn(M);const B=this.hls;if(!B.config.ignorePlaylistParsingErrors){var p;const{networkDetails:V}=r;B.trigger(je.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:M,reason:M.message,level:r.level||void 0,parent:(p=i.fragments[0])==null?void 0:p.type,networkDetails:V,stats:o});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=o.loading.start);const _=this.hls.mainForwardBufferInfo,T=_?_.end-_.len:0,E=(i.edge-T)*1e3,k=cAe(i,E);if(i.requestScheduled+k0){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(P=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D),M||!Z){i.requestScheduled=c,this.loadingPlaylist(y,P);return}}else(i.canBlockReload||i.canSkipUntil)&&(P=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D));P&&R!==void 0&&i.canBlockReload&&(i.requestScheduled=o.loading.first+Math.max(k-s*2,k/2)),this.scheduleLoading(y,P,i)}else this.clearTimer()}scheduleLoading(e,r,n){const i=n||e.details;if(!i){this.loadingPlaylist(e,r);return}const o=self.performance.now(),c=i.requestScheduled;if(o>=c){this.loadingPlaylist(e,r);return}const s=c-o;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 o=$le(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,o=CL.No),new Ule(n,i,o)}checkRetry(e){const r=e.details,n=iO(e),i=e.errorAction,{action:o,retryCount:c=0,retryConfig:s}=i||{},f=!!i&&!!s&&(o===Gl.RetryRequest||!i.resolved&&o===Gl.SendAlternateToPenaltyBox);if(f){var p;if(c>=s.maxNumRetry)return!1;if(n&&(p=e.context)!=null&&p.deliveryDirectives)this.warn(`Retrying playlist loading ${c+1}/${s.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const y=hK(s,c);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),y),this.warn(`Retrying playlist loading ${c+1}/${s.maxNumRetry} after "${r}" in ${y}ms`)}e.levelRetry=!0,i.resolved=!0}return f}}function DAe(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}function Hq(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class oOt extends EK{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(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.LEVEL_LOADING,this.onLevelLoading,this),e.on(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(je.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.LEVEL_LOADING,this.onLevelLoading,this),e.off(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(je.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(je.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:o}=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 [${o.startSN}-${o.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 o=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(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=s;const f=this.hls.config.audioPreference;if(!o&&f){const T=em(f,s,r_);if(T>-1)o=s[T];else{const E=em(f,this.tracks);o=this.tracks[E]}}let p=this.findTrackId(o);p===-1&&o&&(p=this.findTrackId(null));const y={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(je.AUDIO_TRACKS_UPDATED,y);const _=this.trackId;if(p!==-1&&_===-1)this.setAudioTrack(p);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(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:T})}}}onError(e,r){r.fatal||!r.context||r.context.type===Hi.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&&P_(e,i,r_))return i;const o=em(e,this.tracksInGroup,r_);if(o>-1){const c=this.tracksInGroup[o];return this.setAudioTrack(o),c}else if(i){let c=r.loadLevel;c===-1&&(c=r.firstAutoLevel);const s=_Dt(e,r.levels,n,c,r_);if(s===-1)return null;r.nextLoadLevel=s}if(e.channels||e.audioCodec){const c=em(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],o=i.details&&!i.details.live;if(e===this.trackId&&i===n&&o||(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(je.AUDIO_TRACK_SWITCHING,zs({},i)),o))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(o){var n;if(i.onError(o),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 jce=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,MAe="HlsJsTrackRemovedError";class cOt extends Error{constructor(e){super(e),this.name=MAe}}class uOt extends hh{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:o}=this;n&&this.log("Media source opened"),!(!i||!o)&&(o.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(je.MEDIA_ATTACHED,{media:i,mediaSource:o}),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=PLt(cx(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(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.BUFFER_RESET,this.onBufferReset,this),e.on(je.BUFFER_APPENDING,this.onBufferAppending,this),e.on(je.BUFFER_CODECS,this.onBufferCodecs,this),e.on(je.BUFFER_EOS,this.onBufferEos,this),e.on(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(je.FRAG_PARSED,this.onFragParsed,this),e.on(je.FRAG_CHANGED,this.onFragChanged,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.BUFFER_RESET,this.onBufferReset,this),e.off(je.BUFFER_APPENDING,this.onBufferAppending,this),e.off(je.BUFFER_CODECS,this.onBufferCodecs,this),e.off(je.BUFFER_EOS,this.onBufferEos,this),e.off(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(je.FRAG_PARSED,this.onFragParsed,this),e.off(je.FRAG_CHANGED,this.onFragChanged,this),e.off(je.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:r}=this;if(!e)return null;const n={};if(this.operationQueue){const o=this.isUpdating();o||this.operationQueue.removeBlockers();const c=this.isQueued();(o||c)&&this.warn(`Transfering MediaSource with${c?" operations in queue":""}${o?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===r?Xs(n,i.tracks):this.sourceBuffers.forEach(o=>{const[c]=o;c&&(n[c]=Xs({},this.tracks[c]),this.removeBuffer(c)),o[0]=o[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=cx(this.appendSource);if(i){const o=!!r.mediaSource;(o||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const c=this.mediaSource=r.mediaSource||new i;if(this.assignMediaSource(c),o)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,kce(n),dOt(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,o=i?Object.keys(i):null,c=o?o.length:0,s=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&o&&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: ${sa(n,(f,p)=>f==="initSegment"?void 0:p)}; transfer tracks: ${sa(i,(f,p)=>f==="initSegment"?void 0:p)}}`),!P2e(i,n)){r.mediaSource=null,r.tracks=void 0;const f=e.currentTime,p=this.details,y=Math.max(f,(p==null?void 0:p.fragments[0].start)||0);if(y-f>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${f} -> ${y}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(n)}") start time: ${y} currentTime: ${f}`),this.onMediaDetaching(je.MEDIA_DETACHING,{}),this.onMediaAttaching(je.MEDIA_ATTACHING,r),e.currentTime=y;return}this.transferData=void 0,o.forEach(f=>{const p=f,y=i[p];if(y){const _=y.buffer;if(_){const T=this.fragmentTracker,E=y.id;if(T.hasFragments(E)||T.hasParts(E)){const R=Si.getBuffered(_);T.detectEvictedFragments(p,R,E,null,!0)}const k=X$(p),P=[p,_];this.sourceBuffers[k]=P,_.updating&&this.operationQueue&&this.operationQueue.prependBlocker(p),this.trackSourceBuffer(p,y)}}}),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:o,_objectUrl:c}=this;if(o){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=o.readyState==="open";try{const f=o.sourceBuffers;for(let p=f.length;p--;)s&&f[p].abort(),o.removeSourceBuffer(f[p]);s&&o.endOfStream()}catch(f){this.warn(`onMediaDetaching: ${f.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}o.removeEventListener("sourceopen",this._onMediaSourceOpen),o.removeEventListener("sourceended",this._onMediaSourceEnded),o.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(o.removeEventListener("startstreaming",this._onStartStreaming),o.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&&kce(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(je.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(o){this.warn(`onBufferReset ${e}`,o)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[X$(e)]=[null,null];const r=this.tracks[e];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new lOt(this.tracks)}onBufferCodecs(e,r){var n;const i=this.tracks,o=Object.keys(r);this.log(`BUFFER_CODECS: "${o}" (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&&o.some(f=>!i[f]);if(c||s){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${o}" SourceBuffers`);return}o.forEach(f=>{var p,y;const _=r[f],{id:T,codec:E,levelCodec:k,container:P,metadata:R,supplemental:D}=_;let M=i[f];const B=(p=this.transferData)==null||(p=p.tracks)==null?void 0:p[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:P,levelCodec:k,metadata:R,id:T});const Z=kL(G,W),Q=Z==null?void 0:Z.replace(jce,"$1");let re=kL(E,k);const se=(y=re)==null?void 0:y.replace(jce,"$1");re&&Z&&Q!==se&&(f.slice(0,5)==="audio"&&(re=tO(re,this.appendSource)),this.log(`switching codec ${G} to ${re}`),re!==(M.pendingCodec||M.codec)&&(M.pendingCodec=re),M.container=P,this.appendChangeType(f,P,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}`,o={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(o,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,Tn.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&&Si.isBuffered(f.buffer,i)||((s=this.fragmentTracker.getAppendedFrag(i,Tn.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:o,parent:c,frag:s,part:f,chunkMeta:p,offset:y}=r,_=p.buffering[o],{sn:T,cc:E}=s,k=self.performance.now();_.start=k;const P=s.stats.buffering,R=f?f.stats.buffering:null;P.start===0&&(P.start=k),R&&R.start===0&&(R.start=k);const D=n.audio;let M=!1;o==="audio"&&(D==null?void 0:D.container)==="audio/mpeg"&&(M=!this.lastMpegAudioChunk||p.id===1||this.lastMpegAudioChunk.sn!==p.sn,this.lastMpegAudioChunk=p);const B=n.video,V=B==null?void 0:B.buffer;if(V&&T!=="initSegment"){const Z=f||s,Q=this.blockedAudioAppend;if(o==="audio"&&c!=="main"&&!this.blockedAudioAppend&&!(B.ending||B.ended)){const se=Z.start+Z.duration*.05,ue=V.buffered,_e=this.currentOp("video");!ue.length&&!_e?this.blockAudio(Z):!_e&&!Si.isBuffered(V,se)&&this.lastVideoAppendEndse||re{var Z;_.executeStart=self.performance.now();const Q=(Z=this.tracks[o])==null?void 0:Z.buffer;Q&&(M?this.updateTimestampOffset(Q,G,.1,o,T,E):y!==void 0&&pn(y)&&this.updateTimestampOffset(Q,y,1e-6,o,T,E)),this.appendExecutor(i,o)},onStart:()=>{},onComplete:()=>{const Z=self.performance.now();_.executeEnd=_.end=Z,P.first===0&&(P.first=Z),R&&R.first===0&&(R.first=Z);const Q={};this.sourceBuffers.forEach(([re,se])=>{re&&(Q[re]=Si.getBuffered(se))}),this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(je.BUFFER_APPENDED,{type:o,frag:s,part:f,chunkMeta:p,parent:s.type,timeRanges:Q})},onError:Z=>{var Q;const re={type:Dn.MEDIA_ERROR,parent:s.type,details:Jt.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:s,part:f,chunkMeta:p,error:Z,err:Z,fatal:!1},se=(Q=this.media)==null?void 0:Q.error;if(Z.code===DOMException.QUOTA_EXCEEDED_ERR||Z.name=="QuotaExceededError"||"quota"in Z)re.details=Jt.BUFFER_FULL_ERROR;else if(Z.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!se)re.errorAction=l1(!0);else if(Z.name===MAe&&this.sourceBufferCount===0)re.errorAction=l1(!0);else{const ue=++this.appendErrors[o];this.warn(`Failed ${ue}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer (${se||"no media error"})`),(ue>=this.hls.config.appendErrorMaxRetry||se)&&(re.fatal=!0)}this.hls.trigger(je.ERROR,re)}};this.log(`queuing "${o}" append sn: ${T}${f?" p: "+f.index:""} of ${s.type===Tn.MAIN?"level":"track"} ${s.level} cc: ${E}`),this.append(W,o,this.isPending(this.tracks[o]))}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(je.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:o}=r;n?this.append(this.getFlushOp(n,i,o),n):this.sourceBuffers.forEach(([c])=>{c&&this.append(this.getFlushOp(c,i,o),c)})}onFragParsed(e,r){const{frag:n,part:i}=r,o=[],c=i?i.elementaryStreams:n.elementaryStreams;c[ta.AUDIOVIDEO]?o.push("audiovideo"):(c[ta.AUDIO]&&o.push("audio"),c[ta.VIDEO]&&o.push("video"));const s=()=>{const f=self.performance.now();n.stats.buffering.end=f,i&&(i.stats.buffering.end=f);const p=i?i.stats:n.stats;this.hls.trigger(je.FRAG_BUFFERED,{frag:n,part:i,stats:p,id:n.type})};o.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(s,o).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(je.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(je.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===Jt.BUFFER_APPEND_ERROR&&r.frag){var n;const i=(n=r.errorAction)==null?void 0:n.nextAutoLevel;pn(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,o=n.currentTime,c=r.levelTargetDuration,s=r.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(pn(s)&&s>=0){const p=Math.max(s,c),y=Math.floor(o/c)*c-p;this.flushBackBuffer(o,c,y)}const f=i.frontBufferFlushThreshold;if(pn(f)&&f>0){const p=Math.max(i.maxBufferLength,f),y=Math.max(p,c),_=Math.floor(o/c)*c+y;this.flushFrontBuffer(o,c,_)}}flushBackBuffer(e,r,n){this.sourceBuffers.forEach(([i,o])=>{if(o){const s=Si.getBuffered(o);if(s.length>0&&n>s.start(0)){var c;this.hls.trigger(je.BACK_BUFFER_REACHED,{bufferEnd:n});const f=this.tracks[i];if((c=this.details)!=null&&c.live)this.hls.trigger(je.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(je.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:i})}}})}flushFrontBuffer(e,r,n){this.sourceBuffers.forEach(([i,o])=>{if(o){const c=Si.getBuffered(o),s=c.length;if(s<2)return;const f=c.start(s-1),p=c.end(s-1);if(n>f||e>=f&&e<=p)return;this.hls.trigger(je.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 p=Math.max(0,r.fragmentStart),y=Math.max(p,i);return{duration:1/0,start:p,end:y}}return{duration:1/0}}const o=(e=this.overrides)==null?void 0:e.duration;if(o)return pn(o)?{duration:o}:null;const c=this.media.duration,s=pn(n.duration)?n.duration:0;return i>s&&i>c||!pn(c)?{duration:i}:null}updateMediaSource({duration:e,start:r,end:n}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(pn(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}) ${sa(n)}`),this.tracksReady){var i;const o=(i=this.transferData)==null?void 0:i.tracks;o&&Object.keys(o).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(je.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(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.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 o in e){const c=o,s=e[c];if(this.isPending(s)){const f=this.getTrackCodec(s,c),p=`${s.container};codecs=${f}`;s.codec=f,this.log(`creating sourceBuffer(${p})${this.currentOp(c)?" Queued":""} ${sa(s)}`);try{const y=n.addSourceBuffer(p),_=X$(c),T=[c,y];r[_]=T,s.buffer=y}catch(y){var i;this.error(`error while trying to add sourceBuffer: ${y.message}`),this.shiftAndExecuteNext(c),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[c],this.hls.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:y,sourceBufferName:c,mimeType:p,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")&&Lk(n,"video")&&(i=eDt(i,n));const o=kL(i,e.levelCodec);return o?r.slice(0,5)==="audio"?tO(o,this.appendSource):o:""}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",(o,c)=>{const s=c.removedRanges;s!=null&&s.length&&this.hls.trigger(je.BUFFER_FLUSHED,{type:o})})}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(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const o=this.currentOp(e);o&&o.onError(i)}updateTimestampOffset(e,r,n,i,o,c){const s=r-e.timestampOffset;Math.abs(s)>=n&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${r} (sn: ${o} cc: ${c})`),e.timestampOffset=r)}removeExecutor(e,r,n){const{media:i,mediaSource:o}=this,c=this.tracks[e],s=c==null?void 0:c.buffer;if(!i||!o||!s){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const f=pn(i.duration)?i.duration:1/0,p=pn(o.duration)?o.duration:1/0,y=Math.max(0,r),_=Math.min(n,f,p);_>y&&(!c.ending||c.ended)?(c.ended=!1,this.log(`Removing [${y},${_}] from the ${e} SourceBuffer`),s.remove(y,_)):this.shiftAndExecuteNext(e)}appendExecutor(e,r){const n=this.tracks[r],i=n==null?void 0:n.buffer;if(!i)throw new cOt(`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 o=i.buffer;if(!o)return;const c=n.bind(this,e);i.listeners.push({event:r,listener:c}),o.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 kce(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function dOt(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}function X$(t){return t==="audio"?1:0}class AK{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(je.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(je.BUFFER_CODECS,this.onBufferCodecs,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(je.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(je.BUFFER_CODECS,this.onBufferCodecs,this),e.off(je.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&&pn(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,o)=>this.isLevelAllowed(i)&&o<=e);return this.clientRect=null,AK.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 o=e.length-1;const c=Math.max(r,n);for(let s=0;s=c||f.height>=c)&&i(f,e[s+1])){o=s;break}}return o}}const hOt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},xu=hOt,fOt={HLS:"h"},mOt=fOt;class gm{constructor(e,r){Array.isArray(e)&&(e=e.map(n=>n instanceof gm?n:new gm(n))),this.value=e,this.params=r}}const pOt="Dict";function gOt(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 yOt(t,e,r,n){return new Error(`failed to ${t} "${gOt(e)}" as ${r}`,{cause:n})}function ym(t,e,r){return yOt("serialize",t,e,r)}class OAe{constructor(e){this.description=e}}const Cce="Bare Item",xOt="Boolean";function _Ot(t){if(typeof t!="boolean")throw ym(t,xOt);return t?"?1":"?0"}function vOt(t){return btoa(String.fromCharCode(...t))}const bOt="Byte Sequence";function wOt(t){if(ArrayBuffer.isView(t)===!1)throw ym(t,bOt);return`:${vOt(t)}:`}const SOt="Integer";function TOt(t){return t<-999999999999999||99999999999999912)throw ym(t,AOt);const r=e.toString();return r.includes(".")?r:`${r}.0`}const kOt="String",COt=/[\x00-\x1f\x7f]+/;function IOt(t){if(COt.test(t))throw ym(t,kOt);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function NOt(t){return t.description||t.toString().slice(7,-1)}const POt="Token";function Ice(t){const e=NOt(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ym(e,POt);return e}function Wq(t){switch(typeof t){case"number":if(!pn(t))throw ym(t,Cce);return Number.isInteger(t)?FAe(t):jOt(t);case"string":return IOt(t);case"symbol":return Ice(t);case"boolean":return _Ot(t);case"object":if(t instanceof Date)return EOt(t);if(t instanceof Uint8Array)return wOt(t);if(t instanceof OAe)return Ice(t);default:throw ym(t,Cce)}}const ROt="Key";function Kq(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw ym(t,ROt);return t}function jK(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${Kq(e)}`:`;${Kq(e)}=${Wq(r)}`).join("")}function zAe(t){return t instanceof gm?`${Wq(t.value)}${jK(t.params)}`:Wq(t)}function LOt(t){return`(${t.value.map(zAe).join(" ")})${jK(t.params)}`}function DOt(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw ym(t,pOt);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,o])=>{o instanceof gm||(o=new gm(o));let c=Kq(i);return o.value===!0?c+=jK(o.params):(c+="=",Array.isArray(o.value)?c+=LOt(o):c+=zAe(o)),c}).join(`,${n}`)}function $Ae(t,e){return DOt(t,e)}const Of="CMCD-Object",uo="CMCD-Request",H0="CMCD-Session",Zg="CMCD-Status",MOt={br:Of,ab:Of,d:Of,ot:Of,tb:Of,tpb:Of,lb:Of,tab:Of,lab:Of,url:Of,pb:uo,bl:uo,tbl:uo,dl:uo,ltc:uo,mtp:uo,nor:uo,nrr:uo,rc:uo,sn:uo,sta:uo,su:uo,ttfb:uo,ttfbb:uo,ttlb:uo,cmsdd:uo,cmsds:uo,smrt:uo,df:uo,cs:uo,ts:uo,cid:H0,pr:H0,sf:H0,sid:H0,st:H0,v:H0,msd:H0,bs:Zg,bsd:Zg,cdn:Zg,rtp:Zg,bg:Zg,pt:Zg,ec:Zg,e:Zg},OOt={REQUEST:uo};function FOt(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 BOt(t,e){const r={};if(!t)return r;const n=Object.keys(t),i=e?FOt(e):{};return n.reduce((o,c)=>{var s;const f=MOt[c]||i[c]||OOt.REQUEST,p=(s=o[f])!==null&&s!==void 0?s:o[f]={};return p[c]=t[c],o},r)}function zOt(t){return["ot","sf","st","e","sta"].includes(t)}function $Ot(t){return typeof t=="number"?pn(t):t!=null&&t!==""&&t!==!1}const UAe="event";function UOt(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),o=n.pathname.split("/").slice(1,-1);for(;i[0]===o[0];)i.shift(),o.shift();for(;o.length;)o.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}const RL=t=>Math.round(t),Yq=(t,e)=>Array.isArray(t)?t.map(r=>Yq(r,e)):t instanceof gm&&typeof t.value=="string"?new gm(Yq(t.value,e),t.params):(e.baseUrl&&(t=UOt(t,e.baseUrl)),e.version===1?encodeURIComponent(t):t),IR=t=>RL(t/100)*100,VOt=(t,e)=>{let r=t;return e.version>=2&&(t instanceof gm&&typeof t.value=="string"?r=new gm([t]):typeof t=="string"&&(r=[t])),Yq(r,e)},qOt={br:RL,d:RL,bl:IR,dl:IR,mtp:IR,nor:VOt,rtp:IR,tb:RL},VAe="request",qAe="response",kK=["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"],GOt=["e"],HOt=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ZF(t){return HOt.test(t)}function WOt(t){return kK.includes(t)||GOt.includes(t)||ZF(t)}const GAe=["d","dl","nor","ot","rtp","su"];function KOt(t){return kK.includes(t)||GAe.includes(t)||ZF(t)}const YOt=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ZOt(t){return kK.includes(t)||GAe.includes(t)||YOt.includes(t)||ZF(t)}const XOt=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function QOt(t){return XOt.includes(t)||ZF(t)}const JOt={[qAe]:ZOt,[UAe]:WOt,[VAe]:KOt};function HAe(t,e={}){const r={};if(t==null||typeof t!="object")return r;const n=e.version||t.v||1,i=e.reportingMode||VAe,o=n===1?QOt:JOt[i];let c=Object.keys(t).filter(o);const s=e.filter;typeof s=="function"&&(c=c.filter(s));const f=i===qAe||i===UAe;f&&!c.includes("ts")&&c.push("ts"),n>1&&!c.includes("v")&&c.push("v");const p=Xs({},qOt,e.formatters),y={version:n,reportingMode:i,baseUrl:e.baseUrl};return c.sort().forEach(_=>{let T=t[_];const E=p[_];if(typeof E=="function"&&(T=E(T,y)),_==="v"){if(n===1)return;T=n}_=="pr"&&T===1||(f&&_==="ts"&&!pn(T)&&(T=Date.now()),$Ot(T)&&(zOt(_)&&typeof T=="string"&&(T=new OAe(T)),r[_]=T))}),r}function e3t(t,e={}){const r={};if(!t)return r;const n=HAe(t,e),i=BOt(n,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((o,[c,s])=>{const f=$Ae(s,{whitespace:!1});return f&&(o[c]=f),o},r)}function t3t(t,e,r){return Xs(t,e3t(e,r))}const r3t="CMCD";function n3t(t,e={}){return t?$Ae(HAe(t,e),{whitespace:!1}):""}function i3t(t,e={}){if(!t)return"";const r=n3t(t,e);return encodeURIComponent(r)}function s3t(t,e={}){if(!t)return"";const r=i3t(t,e);return`${r3t}=${r}`}const Nce=/CMCD=[^&#]+/;function a3t(t,e,r){const n=s3t(e,r);if(!n)return t;if(Nce.test(t))return t.replace(Nce,n);const i=t.includes("?")?"&":"?";return`${t}${i}${n}`}class o3t{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:xu.MANIFEST,su:!this.initialized})}catch(o){this.hls.logger.warn("Could not generate manifest CMCD data.",o)}},this.applyFragmentData=i=>{try{const{frag:o,part:c}=i,s=this.hls.levels[o.level],f=this.getObjectType(o),p={d:(c||o).duration*1e3,ot:f};(f===xu.VIDEO||f===xu.AUDIO||f==xu.MUXED)&&(p.br=s.bitrate/1e3,p.tb=this.getTopBandwidth(f)/1e3,p.bl=this.getBufferLength(f));const y=c?this.getNextPart(c):this.getNextFrag(o);y!=null&&y.url&&y.url!==o.url&&(p.nor=y.url),this.apply(i,p)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},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(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHED,this.onMediaDetached,this),e.on(je.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHED,this.onMediaDetached,this),e.off(je.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:mOt.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){Xs(r,this.createData());const n=r.ot===xu.INIT||r.ot===xu.VIDEO||r.ot===xu.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 o={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),t3t(e.headers,r,o)):e.url=a3t(e.url,r,o)}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,o=(r=this.hls.levels[i.level])==null||(r=r.details)==null?void 0:r.partList;if(o){const{sn:c}=i;for(let s=o.length-1;s>=0;s--){const f=o[s];if(f.index===n&&f.fragment.sn===c)return o[s+1]}}}getObjectType(e){const{type:r}=e;if(r==="subtitle")return xu.TIMED_TEXT;if(e.sn==="initSegment")return xu.INIT;if(r==="audio")return xu.AUDIO;if(r==="main")return this.hls.audioTracks.length?xu.VIDEO:xu.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===xu.AUDIO)n=i.audioTracks;else{const o=i.maxAutoLevel,c=o>-1?o+1:i.levels.length;n=i.levels.slice(0,c)}return n.forEach(o=>{o.bitrate>r&&(r=o.bitrate)}),r>0?r:NaN}getBufferLength(e){const r=this.media,n=e===xu.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:Si.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(o){this.loader=void 0,this.loader=new n(o)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(o,c,s){r(o),this.loader.load(o,c,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(o){this.loader=void 0,this.loader=new n(o)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(o,c,s){r(o),this.loader.load(o,c,s)}}}}const l3t=3e5;class c3t extends hh{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(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.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)===Gl.SendAlternateToPenaltyBox&&n.flags===Yu.MoveAllAlternatesMatchingHost){const i=this.levels;let o=this._pathwayPriority,c=this.pathwayId;if(r.context){const{groupId:s,pathwayId:f,type:p}=r.context;s&&i?c=this.getPathwayForGroupId(s,p,c):f&&(c=f)}c in this.penalizedPathways||(this.penalizedPathways[c]=performance.now()),!o&&i&&(o=this.pathways()),o&&o.length>1&&(this.updatePathwayPriority(o),n.resolved=this.pathwayId!==c),r.details===Jt.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: ${sa(o)} penalized: ${sa(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(o=>{i-n[o]>l3t&&delete n[o]});for(let o=0;o0){this.log(`Setting Pathway to "${c}"`),this.pathwayId=c,hAe(r),this.hls.trigger(je.LEVELS_UPDATED,{levels:r});const p=this.hls.levels[s];f&&p&&this.levels&&(p.attrs["STABLE-VARIANT-ID"]!==f.attrs["STABLE-VARIANT-ID"]&&p.bitrate!==f.bitrate&&this.log(`Unstable Pathways change from bitrate ${f.bitrate} to ${p.bitrate}`),this.hls.nextLoadLevel=s);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let o=0;o{const{ID:c,"BASE-ID":s,"URI-REPLACEMENT":f}=o;if(r.some(y=>y.pathwayId===c))return;const p=this.getLevelsForPathway(s).map(y=>{const _=new Za(y.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 k=WAe(y.uri,_["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",f),P=new Mk({attrs:_,audioCodec:y.audioCodec,bitrate:y.bitrate,height:y.height,name:y.name,url:k,videoCodec:y.videoCodec,width:y.width});if(y.audioGroups)for(let R=1;R{this.log(`Loaded steering manifest: "${i}"`);const k=y.data;if((k==null?void 0:k.VERSION)!==1){this.log(`Steering VERSION ${k.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=k.TTL;const{"RELOAD-URI":P,"PATHWAY-CLONES":R,"PATHWAY-PRIORITY":D}=k;if(P)try{this.uri=new self.URL(P,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${P}`);return}this.scheduleRefresh(this.uri||T.url),R&&this.clonePathways(R);const M={steeringManifest:k,url:i.toString()};this.hls.trigger(je.STEERING_MANIFEST_LOADED,M),D&&this.updatePathwayPriority(D)},onError:(y,_,T,E)=>{if(this.log(`Error loading steering manifest: ${y.code} ${y.text} (${_.url})`),this.stopLoad(),y.code===410){this.enabled=!1,this.log(`Steering manifest ${_.url} no longer available`);return}let k=this.timeToLoad*1e3;if(y.code===429){const P=this.loader;if(typeof(P==null?void 0:P.getResponseHeader)=="function"){const R=P.getResponseHeader("Retry-After");R&&(k=parseFloat(R)*1e3)}this.log(`Steering manifest ${_.url} rate limited`);return}this.scheduleRefresh(this.uri||_.url,k)},onTimeout:(y,_,T)=>{this.log(`Timeout loading steering manifest (${_.url})`),this.scheduleRefresh(this.uri||_.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(o,f,p)}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 Pce(t,e,r,n){t&&Object.keys(e).forEach(i=>{const o=t.filter(c=>c.groupId===i).map(c=>{const s=Xs({},c);return s.details=void 0,s.attrs=new Za(s.attrs),s.url=s.attrs.URI=WAe(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(...o)})}function WAe(t,e,r,n){const{HOST:i,PARAMS:o,[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),o&&Object.keys(o).sort().forEach(p=>{p&&f.searchParams.set(p,o[p])}),f.href}class u1 extends hh{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=u1.CDMCleanupPromise?[u1.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:i}=r,o=`"${r.type}" event: init data type: "${n}"`;if(this.debug(o),i!==null){if(!this.keyFormatPromise){let c=Object.keys(this.keySystemAccessPromises);c.length||(c=wA(this.config));const s=c.map(V$).filter(f=>!!f);this.keyFormatPromise=this.getKeyFormatPromise(s)}this.keyFormatPromise.then(c=>{const s=IL(c);if(n!=="sinf"||s!==Ja.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${s}`);return}let f;try{const E=al(new Uint8Array(i)),k=gK(JSON.parse(E).sinf),P=$2e(k);if(!P)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");f=new Uint8Array(P.subarray(8,24))}catch(E){this.warn(`${o} Failed to parse sinf: ${E}`);return}const p=Kl(f),{keyIdToKeySessionPromise:y,mediaKeySessions:_}=this;let T=y[p];for(let E=0;E<_.length;E++){const k=_[E],P=k.decryptdata;if(!P.keyId)continue;const R=Kl(P.keyId);if(aO(f,P.keyId)||P.uri.replace(/-/g,"").indexOf(p)!==-1){if(T=y[R],!T)continue;if(P.pssh)break;delete y[R],P.pssh=new Uint8Array(i),P.keyId=f,T=y[p]=T.then(()=>this.generateRequestWithPreferredKeySession(k,n,i,"encrypted-event-key-match")),T.catch(D=>this.handleError(D));break}}T||this.handleError(new Error(`Key ID ${p} 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(je.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(je.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(je.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(je.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(je.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(je.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(je.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(je.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(je.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===Ja.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),o=r.map(c=>c.videoCodec).filter(n);return i.length+o.length===0&&o.push("avc1.42e01e"),new Promise((c,s)=>{const f=p=>{const y=p.shift();this.getMediaKeysPromise(y,i,o).then(_=>c({keySystem:y,mediaKeys:_})).catch(_=>{p.length?f(p):_ instanceof Wu?s(_):s(new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.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 iAe===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 o=VDt(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: ${sa(o)}`),s=this.requestMediaKeySystemAccess(e,o);const f=c=this.keySystemAccessPromises[e]={keySystemAccess:s};return s.catch(p=>{this.log(`Failed to obtain access to key-system "${e}": ${p}`)}),s.then(p=>{this.log(`Access for key-system "${p.keySystem}" obtained`);const y=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const _=f.mediaKeys=p.createMediaKeys().then(T=>(this.log(`Media-keys created for "${e}"`),f.hasMediaKeys=!0,y.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: ${Kl(e.keyId||[])} keyUri: ${e.uri}`);const i=n.createSession(),o={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(o),o}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=NR(r),o="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,o,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 ${Kl(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})=>V$(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 o=V$(i);o?r(o):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=wA(this.config),n=e.map(IL).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 ${o}`),this.attemptSetMediaKeys(f,p).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:f,mediaKeys:p,decryptdata:r}))))).then(f=>{const p="cenc",y=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(f,p,y,"playlist-key")});return s.catch(f=>this.handleError(f,e.frag)),this.keyIdToKeySessionPromise[n]=s,s}return c.catch(s=>{if(s instanceof Wu){const f=zs({},s.data);this.getKeyStatus(r)==="internal-error"&&(f.decryptdata=r);const p=new Wu(f,s.message);this.handleError(p,e.frag)}}),c}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,r){if(this.hls)if(e instanceof Wu){r&&(e.data.frag=r);const n=e.data.decryptdata;this.error(`${e.message}${n?` (${Kl(n.keyId||[])})`:""}`),this.hls.trigger(je.ERROR,e.data)}else this.error(e.message),this.hls.trigger(je.ERROR,{type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const r=NR(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=IL(e.keyFormat),o=i?[i]:wA(this.config);return this.attemptKeySystemAccess(o)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=wA(this.config)),e.length===0)throw new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${sa({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((o,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(o).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(o=>n.indexOf(o)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var o;const c=(o=this.config.drmSystems)==null||(o=o[e.keySystem])==null?void 0:o.generateRequest;if(c)try{const k=c.call(this.hls,r,n,e);if(!k)throw new Error("Invalid response from configured generateRequest filter");r=k.initDataType,n=k.initData?k.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(k){if(this.warn(k.message),this.hls&&this.hls.config.debug)throw k}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const s=NR(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 p=new xK,y=e._onmessage=k=>{const P=e.mediaKeysSession;if(!P){p.emit("error",new Error("invalid state"));return}const{messageType:R,message:D}=k;this.log(`"${R}" message event for session "${P.sessionId}" message size: ${D.byteLength}`),R==="license-request"||R==="license-renewal"?this.renewLicense(e,D).catch(M=>{p.eventNames().length?p.emit("error",M):this.handleError(M)}):R==="license-release"?e.keySystem===Ja.FAIRPLAY&&this.updateKeySession(e,$q("acknowledged")).then(()=>this.removeSession(e)).catch(M=>this.handleError(M)):this.warn(`unhandled media key message type "${R}"`)},_=(k,P)=>{P.keyStatus=k;let R;k.startsWith("usable")?p.emit("resolved"):k==="internal-error"||k==="output-restricted"||k==="output-downscaled"?R=Rce(k,P.decryptdata):k==="expired"?R=new Error(`key expired (keyId: ${s})`):k==="released"?R=new Error("key released"):k==="status-pending"||this.warn(`unhandled key status change "${k}" (keyId: ${s})`),R&&(p.eventNames().length?p.emit("error",R):this.handleError(R))},T=e._onkeystatuseschange=k=>{if(!e.mediaKeysSession){p.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 ${sa(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} (${sa(R)}).`)}};Jc(e.mediaKeysSession,"message",y),Jc(e.mediaKeysSession,"keystatuseschange",T);const E=new Promise((k,P)=>{p.on("error",P),p.on("resolved",k)});return e.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${s} URI: ${f}`)}).catch(k=>{throw new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_SESSION,error:k,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${k}`)}).then(()=>E).catch(k=>(p.removeAllListeners(),this.removeSession(e).then(()=>{throw k}))).then(()=>(p.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 o="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===Ja.PLAYREADY&&o.length===16){const s=Kl(o);r[s]=n,rAe(o)}const c=Kl(o);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),o=this.getServerCertificateUrl(e);return o?(this.log(`Fetching server certificate for "${e}"`),new Promise((c,s)=>{const f={responseType:"arraybuffer",url:o},p=r.certLoadPolicy.default,y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},_={onSuccess:(T,E,k,P)=>{c(T.data)},onError:(T,E,k,P)=>{s(new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:k,response:zs({url:f.url,data:void 0},T)},`"${e}" certificate request failed (${o}). Status: ${T.code} (${T.text})`))},onTimeout:(T,E,k)=>{s(new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:k,response:{url:f.url,data:void 0}},`"${e}" certificate request timed out (${o})`))},onAbort:(T,E,k)=>{s(new Error("aborted"))}};i.load(f,y,_)})):Promise.resolve()}setMediaKeysServerCertificate(e,r,n){return new Promise((i,o)=>{e.setServerCertificate(n).then(c=>{this.log(`setServerCertificate ${c?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),i(e)}).catch(c=>{o(new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.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 Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.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"),o=i.querySelectorAll("HttpHeader");if(o.length>0){let y;for(let _=0,T=o.length;_ in key message");return $q(atob(p))}setupLicenseXHR(e,r,n,i){const o=this.config.licenseXhrSetup;return o?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return o.call(this.hls,e,r,n,i)}).catch(c=>{if(!n.decryptdata)throw c;return e.open("POST",r,!0),o.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,o)=>{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 o(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 p=this.config.licenseResponseCallback;if(p)try{f=p.call(this.hls,s,c,e)}catch(y){this.error(y)}i(f)}else{const f=n.errorRetry,p=f?f.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>p||s.status>=400&&s.status<500)o(new Wu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.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 y=p-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${y} attempts left`),this.requestLicense(e,r).then(i,o)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=s,this.setupLicenseXHR(s,c,e,r).then(({xhr:f,licenseChallenge:p})=>{e.keySystem==Ja.PLAYREADY&&(p=this.unpackPlayReadyKeyMessage(f,p)),f.send(p)}).catch(o)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,Jc(n,"encrypted",this.onMediaEncrypted),Jc(n,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=n.mediaKeys}onMediaDetached(){const e=this.media;e&&(ku(e,"encrypted",this.onMediaEncrypted),ku(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,Gy.clearKeyUriToKeyIdMap();const o=i.length;u1.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(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.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(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${c}`)})}).then(()=>{o&&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,o)=>(i.indexOf(o.keyFormat)===-1&&i.push(o.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: ${Kl((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 o=this.mediaKeySessions.indexOf(e);o>-1&&this.mediaKeySessions.splice(o,1);const{keyStatusTimeouts:c}=e;c&&Object.keys(c).forEach(p=>self.clearTimeout(c[p]));const{drmSystemOptions:s}=this.config;return(GDt(s)?new Promise((p,y)=>{self.setTimeout(()=>y(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(p).catch(y)}):Promise.resolve()).catch(p=>{this.log(`Could not remove session: ${p}`),this.hls&&this.hls.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${p}`)})}).then(()=>r.close()).catch(p=>{this.log(`Could not close session: ${p}`),this.hls&&this.hls.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${p}`)})})}return Promise.resolve()}}u1.CDMCleanupPromise=void 0;function NR(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Kl(t.keyId)}function u3t(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 Wu 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 Rce(t,e){const r=t==="output-restricted",n=r?Jt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Jt.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wu({type:Dn.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},r?"HDCP level output restricted":`key status changed to "${t}"`)}class d3t{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(je.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(je.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(je.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 o=i-this.lastTime,c=n-this.lastDroppedFrames,s=r-this.lastDecodedFrames,f=1e3*c/o,p=this.hls;if(p.trigger(je.FPS_DROP,{currentDropped:c,currentDecoded:s,totalDroppedFrames:n}),f>0&&c>p.config.fpsDroppedMonitoringThreshold*s){let y=p.currentLevel;p.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+y),y>0&&(p.autoLevelCapping===-1||p.autoLevelCapping>=y)&&(y=y-1,p.trigger(je.FPS_DROP_LEVEL_CAPPING,{level:y,droppedLevel:p.currentLevel}),p.autoLevelCapping=y,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 KAe(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 YAe(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){Us.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){Us.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function zw(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 Zq(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const o=f3t(t.cues,e,r);for(let c=0;ct[r].endTime)return-1;let n=0,i=r,o;for(;n<=i;)if(o=Math.floor((i+n)/2),et[o].startTime&&n-1)for(let o=i,c=t.length;o=e&&s.endTime<=r)n.push(s);else if(s.startTime>r)return n}return n}function LL(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=LL(this.media.textTracks);for(let o=0;o-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.LEVEL_LOADING,this.onLevelLoading,this),e.on(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(je.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(je.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.LEVEL_LOADING,this.onLevelLoading,this),e.off(je.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(je.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(je.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;LL(n.textTracks).forEach(c=>{zw(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:o}=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 [${o.startSN}-${o.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 o=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(y=>!n||n.indexOf(y.groupId)!==-1);if(c.length)this.selectDefaultTrack&&!c.some(y=>y.default)&&(this.selectDefaultTrack=!1),c.forEach((y,_)=>{y.id=_});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=c;const s=this.hls.config.subtitlePreference;if(!o&&s){this.selectDefaultTrack=!1;const y=em(s,c);if(y>-1)o=c[y];else{const _=em(s,this.tracks);o=this.tracks[_]}}let f=this.findTrackId(o);f===-1&&o&&(f=this.findTrackId(null));const p={subtitleTracks:c};this.log(`Updating subtitle tracks, ${c.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(je.SUBTITLE_TRACKS_UPDATED,p),f!==-1&&this.trackId===-1&&this.setSubtitleTrack(f)}}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const o=this.tracksInGroup[i];return this.setSubtitleTrack(i),o}else{if(n)return null;{const o=em(e,r);if(o>-1)return r[o]}}}}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,o=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||""):""} ${o}`),this.hls.trigger(je.SUBTITLE_TRACK_LOADING,{url:o,id:n,groupId:i,deliveryDirectives:r||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const r=LL(e.textTracks),n=this.currentTrack;let i;if(n&&(i=r.filter(o=>Hq(n,o))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(o=>{o.mode!=="disabled"&&o!==i&&(o.mode="disabled")}),i){const o=this.subtitleDisplay?"showing":"hidden";i.mode!==o&&(i.mode=o)}}setSubtitleTrack(e){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=r.length||!pn(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(je.SUBTITLE_TRACK_SWITCH,{id:e});return}const o=!!i.details&&!i.details.live;if(e===this.trackId&&i===n&&o)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:p,url:y}=i;this.hls.trigger(je.SUBTITLE_TRACK_SWITCH,{id:c,groupId:s,name:f,type:p,url:y});const _=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(_)}}function p3t(){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 o=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(i=="x"?o:o&3|8).toString(16)})}}}function ij(t){let e=5381,r=t.length;for(;r;)e=e*33^t.charCodeAt(--r);return(e>>>0).toString()}const d1=.025;let uO=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function g3t(t,e,r){return`${t.identifier}-${r+1}-${ij(e)}`}class y3t{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 Q$(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=Q$(r,e);return r-n<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,r=pn(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 Q$(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 x3t(this)}}function Q$(t,e){return t-e.start":t.cue.post?"":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function yw(t){const e=t.timelineStart,r=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+r).toFixed(2)}]`}class _3t{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(je.PLAYOUT_LIMIT_REACHED,{})};const o=this.hls=new e(r);this.interstitial=n,this.assetItem=i;const c=()=>{this.hasDetails=!0};o.once(je.LEVEL_LOADED,c),o.once(je.AUDIO_TRACK_LOADED,c),o.once(je.SUBTITLE_TRACK_LOADED,c),o.on(je.MEDIA_ATTACHING,(s,{media:f})=>{this.removeMediaListeners(),this.mediaAttached=f,this.interstitial.playoutLimit&&(f.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&o.on(je.BUFFER_APPENDED,()=>{const y=this.bufferedEnd;this.reachedPlayout(y)&&(this._bufferedEosTime=y,o.trigger(je.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=ZAe(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,o=Si.bufferInfo(e,i,0);return this.getAssetTime(o.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=Si.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: ${yw(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Lce=.033;class v3t extends hh{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&&(o=i[n])!=null&&o.event;){var o;n--}return n}findItemIndexAtTime(e,r){const n=this.items;if(n)for(let i=0;io.start&&e1)for(let o=0;os&&(r!s.includes(p.identifier)):[];c.length&&c.sort((p,y)=>{const _=p.cue.pre,T=p.cue.post,E=y.cue.pre,k=y.cue.post;if(_&&!E)return-1;if(E&&!_||T&&!k)return 1;if(k&&!T)return-1;if(!_&&!E&&!T&&!k){const P=p.startTime,R=y.startTime;if(P!==R)return P-R}return p.dateRange.tagOrder-y.dateRange.tagOrder}),this.events=c,f.forEach(p=>{this.removeEvent(p)}),this.updateSchedule(e,f)}updateSchedule(e,r=[],n=!1){const i=this.events||[];if(i.length||r.length||this.length<2){const o=this.items,c=this.parseSchedule(i,e);(n||r.length||(o==null?void 0:o.length)!==c.length||c.some((f,p)=>Math.abs(f.playout.start-o[p].playout.start)>.005||Math.abs(f.playout.end-o[p].playout.end)>.005))&&(this.items=c,this.onScheduleUpdate(r,o))}}parseDateRanges(e,r,n){const i=[],o=Object.keys(e);for(let c=0;c!f.error&&!(f.cue.once&&f.hasPlayed)),e.length){this.resolveOffsets(e,r);let f=0,p=0;if(e.forEach((y,_)=>{const T=y.cue.pre,E=y.cue.post,k=e[_-1]||null,P=y.appendInPlace,R=E?o:y.startOffset,D=y.duration,M=y.timelineOccupancy===uO.Range?D:0,B=y.resumptionOffset,V=(k==null?void 0:k.startTime)===R,G=R+y.cumulativeDuration;let W=P?G+D:R+B;if(T||!E&&R<=0){const Q=p;p+=M,y.timelineStart=G;const re=c;c+=D,n.push({event:y,start:G,end:W,playout:{start:re,end:c},integrated:{start:Q,end:p}})}else if(R<=o){if(!V){const se=R-f;if(se>Lce){const ue=f,_e=p;p+=se;const we=c;c+=se;const Ce={previousEvent:e[_-1]||null,nextEvent:y,start:ue,end:ue+se,playout:{start:we,end:c},integrated:{start:_e,end:p}};n.push(Ce)}else se>0&&k&&(k.cumulativeDuration+=se,n[n.length-1].end=R)}E&&(W=G),y.timelineStart=G;const Q=p;p+=M;const re=c;c+=D,n.push({event:y,start:G,end:W,playout:{start:re,end:c},integrated:{start:Q,end:p}})}else return;const Z=y.resumeTime;E||Z>o?f=o:f=Z}),f{const p=s.cue.pre,y=s.cue.post,_=p?0:y?i:s.startTime;this.updateAssetDurations(s),c===_?s.cumulativeDuration=o:(o=0,c=_),!y&&s.snapOptions.in&&(s.resumeAnchor=J_(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+1d1?(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 p=J_(null,s.fragments,n);if(!p)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${c} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;const y=c==="audio"?.175:0;return Math.abs(p.start-n){const R=T.data,D=R==null?void 0:R.ASSETS;if(!Array.isArray(D)){const M=this.assignAssetListError(e,Jt.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),k.url,E,P);this.hls.trigger(je.ERROR,M);return}e.assetListResponse=R,this.hls.trigger(je.ASSET_LIST_LOADED,{event:e,assetListResponse:R,networkDetails:P})},onError:(T,E,k,P)=>{const R=this.assignAssetListError(e,Jt.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${T.code} ${T.text} (${E.url})`),E.url,P,k);this.hls.trigger(je.ERROR,R)},onTimeout:(T,E,k)=>{const P=this.assignAssetListError(e,Jt.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${E.url})`),E.url,T,k);this.hls.trigger(je.ERROR,P)}};return s.load(f,y,_),this.hls.trigger(je.ASSET_LIST_LOADING,{event:e}),s}assignAssetListError(e,r,n,i,o,c){return e.error=n,{type:Dn.NETWORK_ERROR,details:r,fatal:!1,interstitial:e,url:i,error:n,networkDetails:c,stats:o}}}function Dce(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function hw(t,e){return`[${t}] Advancing timeline position to ${e}`}class w3t extends hh{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 k=this.schedule.findItemIndexAtTime(n);if(k===-1&&(k=E+(c?-1:1),this.log(`seeked ${c?"back ":""}to position not covered by schedule ${n} (resolving from ${E} to ${k})`)),!this.isInterstitial(s)&&(f=this.media)!=null&&f.paused&&(this.shouldPlay=!1),!c&&k>E){const P=this.schedule.findJumpRestrictedIndex(E+1,k);if(P>E){this.setSchedulePosition(P);return}}this.setSchedulePosition(k);return}const p=this.playingAsset;if(!p){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 y=p.timelineStart,_=p.duration||0;if(c&&n=y+_){var T;(T=s.event)!=null&&T.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,p)}},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 o=this.playingAsset;if(!o)return;const c=o.timelineStart+(o.duration||0);n>=c&&this.setScheduleToAssetAtTime(n,o)},this.onScheduleUpdate=(n,i)=>{const o=this.schedule;if(!o)return;const c=this.playingItem,s=o.events||[],f=o.items||[],p=o.durations,y=n.map(P=>P.identifier),_=!!(s.length||y.length);(_||i)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s} Schedule: ${f.map(P=>Lh(P))} pos: ${this.timelinePos}`),y.length&&this.log(`Removed events ${y}`);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 k=this.bufferingItem;if(k&&(E=this.updateItem(k,this.bufferedPos),this.itemsMatch(k,E)?this.bufferingItem=E:k.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(k.event,null))),n.forEach(P=>{P.assetList.forEach(R=>{this.clearAssetPlayer(R.identifier,null)})}),this.playerQueue.forEach(P=>{if(P.interstitial.appendInPlace){const R=P.assetItem.timelineStart,D=P.timelineOffset-R;if(D)try{P.timelineOffset=R}catch(M){Math.abs(D)>d1&&this.warn(`${M} ("${P.assetId}" ${P.timelineOffset}->${R})`)}}}),_||i){if(this.hls.trigger(je.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:f.slice(0),durations:p,removedIds:y}),this.isInterstitial(c)&&y.includes(c.event.identifier)){this.warn(`Interstitial "${c.event.identifier}" removed while playing`),this.primaryFallback(c.event);return}c&&this.trimInPlace(T,c),k&&E!==T&&this.trimInPlace(E,k),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=r,this.assetListLoader=new b3t(e),this.schedule=new v3t(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(je.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(je.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(je.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(je.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(je.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(je.BUFFER_APPENDED,this.onBufferAppended,this),e.on(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(je.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(je.MEDIA_ENDED,this.onMediaEnded,this),e.on(je.ERROR,this.onError,this),e.on(je.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(je.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(je.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(je.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(je.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(je.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(je.BUFFER_CODECS,this.onBufferCodecs,this),e.off(je.BUFFER_APPENDED,this.onBufferAppended,this),e.off(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(je.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(je.MEDIA_ENDED,this.onMediaEnded,this),e.off(je.ERROR,this.onError,this),e.off(je.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){ku(e,"play",this.onPlay),ku(e,"pause",this.onPause),ku(e,"seeking",this.onSeeking),ku(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,r){const n=this.media=r.media;Jc(n,"seeking",this.onSeeking),Jc(n,"timeupdate",this.onTimeupdate),Jc(n,"play",this.onPlay),Jc(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 o=this.findItemIndex(n);this.setSchedulePosition(o)}}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 o=this.getBufferingPlayer();o&&(this.log(`Removing schedule state for detachedData and ${o}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,o.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,k,P)=>{if(_){let R=_[T].start;const D=_.event;if(D){if(T==="playout"||D.timelineOccupancy!==uO.Point){const M=n(E);(M==null?void 0:M.interstitial)===D&&(R+=M.assetItem.startOffset+M[P])}}else{const M=k==="bufferedPos"?c():e[k];R+=M-_.start}return R}return 0},o=(_,T)=>{var E;if(_!==0&&T!=="primary"&&(E=e.schedule)!=null&&E.length){var k;const P=e.schedule.findItemIndexAtTime(_),R=(k=e.schedule.items)==null?void 0:k[P];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,k;const P=e.effectivePlayingItem;if(P!=null&&(E=P.event)!=null&&E.restrictions.skip||!e.schedule)return;e.log(`seek to ${_} "${T}"`);const R=e.effectivePlayingItem,D=e.schedule.findItemIndexAtTime(_,T),M=(k=e.schedule.items)==null?void 0:k[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 Z=n(e.playingAsset),Q=(Z==null?void 0:Z.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&&(!Z||G||ue<=Z.duration)){Q.currentTime=ue;return}}}if(M){let Z=_;if(T!=="primary"){const re=M[T].start,se=_-re;Z=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=Z)}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=Z,e.checkBuffer();else{const ue=M.event.assetList,_e=_-(M[T]||M).start;for(let we=ue.length;we--;){const Ce=ue[we];if(Ce.duration&&_e>=Ce.startOffset&&_e{const _=e.effectivePlayingItem;if(e.isInterstitial(_))return _;const T=r();return e.isInterstitial(T)?T:null},y={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 _=p(),T=e.effectivePlayingItem;return T&&T===_?i(T,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-T.playout.start:0},set currentTime(_){const T=p(),E=e.effectivePlayingItem;E&&E===T&&f(_+E.playout.start,"playout")},get duration(){const _=p();return _?_.playout.end-_.playout.start:0},get assetPlayers(){var _;const T=(_=p())==null?void 0:_.event.assetList;return T?T.map(E=>e.getAssetPlayer(E.identifier)):[]},get playingIndex(){var _;const T=(_=p())==null?void 0:_.event;return T&&e.effectivePlayingAsset?T.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return p()}};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 p()?y: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 o(((_=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 k=_.playout.start+_.event.duration;f(k+.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 o=(r=i)==null?void 0:r.currentTime;if(!(o===void 0||!pn(o)))return o}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 o=e.transferMedia();this.log(`transfer MediaSource from ${e} ${sa(o)}`),this.detachedData=o}else r&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,r){var n,i;if(e.media===r)return;let o=null;const c=this.hls,s=e!==c,f=s&&e.interstitial.appendInPlace,p=(n=this.detachedData)==null?void 0:n.mediaSource;let y;if(c.media)f&&(o=c.transferMedia(),this.detachedData=o),y="Primary";else if(p){const k=this.getBufferingPlayer();k?(o=k.transferMedia(),y=`${k}`):y="detached MediaSource"}else y="detached media";if(!o){if(p)o=this.detachedData,this.log(`using detachedData: MediaSource ${sa(o)}`);else if(!this.detachedData||c.media===r){const k=this.playerQueue;k.length>1&&k.forEach(P=>{if(s&&P.interstitial.appendInPlace!==f){const R=P.interstitial;this.clearInterstitial(P.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 _=o&&"mediaSource"in o&&((i=o.mediaSource)==null?void 0:i.readyState)!=="closed",T=_&&o?o:r;this.log(`${_?"transfering MediaSource":"attaching media"} to ${s?e:"Primary"} from ${y} (media.currentTime: ${r.currentTime})`);const E=this.schedule;if(T===o&&E){const k=s&&e.assetId===E.assetIdAtEnd;T.overrides={duration:E.duration,endOfStream:!s||k,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 o=this.hls.startPosition;if(this.timelinePos=o,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(hw("checkStart (preroll)",o));const c=e.findEventIndex(r[0].identifier);this.setSchedulePosition(c)}else if(o>=0||!this.primaryLive){this.log(hw("checkStart",o));const c=this.timelinePos=o>0?o: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(hw("checkStart (playing item)",i.start));const o=e.findItemIndex(i);this.setSchedulePosition(o)}}advanceAssetBuffering(e,r){const n=e.event,i=n.findAssetIndex(r),o=J$(n,i);if(!n.isAssetPastPlayoutLimit(o))this.bufferedToEvent(e,o);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=J$(e,n);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const o=this.schedule.items;if(o){const c=r+1,s=o.length;if(c>=s){this.setSchedulePosition(-1);return}const f=e.resumeTime;this.timelinePos=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${r} (${o&&Lh(o)}) pos: ${this.timelinePos}`);const c=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(c)){const y=c.event,_=this.playingAsset,T=_==null?void 0:_.identifier,E=T?this.getAssetPlayer(T):null;if(E&&T&&(!this.eventItemsMatch(c,o)||r!==void 0&&T!==y.assetList[r].identifier)){var f;const k=y.findAssetIndex(_);if(this.log(`INTERSTITIAL_ASSET_ENDED ${k+1}/${y.assetList.length} ${yw(_)}`),this.endedAsset=_,this.playingAsset=null,this.hls.trigger(je.INTERSTITIAL_ASSET_ENDED,{asset:_,assetListIndex:k,event:y,schedule:i.slice(0),scheduleIndex:e,player:E}),c!==this.playingItem){this.itemsMatch(c,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(y,this.findItemIndex(this.playingItem),k);return}this.retreiveMediaSource(T,o),E.media&&!((f=this.detachedData)!=null&&f.mediaSource)&&E.detachMedia()}if(!this.eventItemsMatch(c,o)&&(this.endedItem=c,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${y} ${Lh(c)}`),y.hasPlayed=!0,this.hls.trigger(je.INTERSTITIAL_ENDED,{event:y,schedule:i.slice(0),scheduleIndex:e}),y.cue.once)){var p;this.updateSchedule();const k=(p=this.schedule)==null?void 0:p.items;if(o&&k){const P=this.findItemIndex(o);this.advanceSchedule(P,k,r,c,s)}return}}this.advanceSchedule(e,i,r,c,s)}advanceSchedule(e,r,n,i,o){const c=this.schedule;if(!c)return;const s=r[e]||null,f=this.primaryMedia,p=this.playerQueue;if(p.length&&p.forEach(y=>{const _=y.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 y=s.event;if(n===void 0){n=c.findAssetIndex(y,this.timelinePos);const k=J$(y,n-1);if(y.isAssetPastPlayoutLimit(k)||y.appendInPlace&&this.timelinePos===s.end){this.advanceAfterAssetEnded(y,e,n);return}n=k}const _=this.waitingItem;this.assetsBuffered(s,f)||this.setBufferingItem(s);let T=this.preloadAssets(y,n);if(this.eventItemsMatch(s,_||i)||(this.waitingItem=s,this.log(`INTERSTITIAL_STARTED ${Lh(s)} ${y.appendInPlace?"append in place":""}`),this.hls.trigger(je.INTERSTITIAL_STARTED,{event:y,schedule:r.slice(0),scheduleIndex:e})),!y.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${y}`);return}if(y.assetListLoader&&(y.assetListLoader.destroy(),y.assetListLoader=void 0),!f){this.log(`Waiting for attachMedia to start Interstitial ${y}`);return}this.waitingItem=this.endedItem=null,this.playingItem=s;const E=y.assetList[n];if(!E){this.advanceAfterAssetEnded(y,e,n||0);return}if(T||(T=this.getAssetPlayer(E.identifier)),T===null||T.destroyed){const k=y.assetList.length;this.warn(`asset ${n+1}/${k} player destroyed ${y}`),T=this.createAssetPlayer(y,E,n),T.loadSource()}if(!this.eventItemsMatch(s,this.bufferingItem)&&y.appendInPlace&&this.isAssetBuffered(E))return;this.startAssetPlayer(T,n,r,e,f),this.shouldPlay&&Dce(T.media)}else s?(this.resumePrimary(s,e,i),this.shouldPlay&&Dce(this.hls.media)):o&&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,o;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Lh(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let s=this.timelinePos;(s=e.end)&&(s=this.getPrimaryResumption(e,r),this.log(hw("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,e)}if(!n)return;const c=(o=this.schedule)==null?void 0:o.items;c&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Lh(e)}`),this.hls.trigger(je.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:Si.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 o=this.hls;o.media?this.checkBuffer():(this.transferMediaTo(o,i),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(hw("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(je.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(je.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=zs(zs({},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=zs(zs({},this.altSelection),{},{audio:n});return}const o=zs(zs({},i),{},{audio:n});this.mediaSelection=o}onSubtitleTrackUpdated(e,r){const n=this.hls.subtitleTracks[r.id],i=this.mediaSelection;if(!i){this.altSelection=zs(zs({},this.altSelection),{},{subtitles:n});return}const o=zs(zs({},i),{},{subtitles:n});this.mediaSelection=o}onAudioTrackSwitching(e,r){const n=qle(r);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(r)||i.setAudioOption(n)))}onSubtitleTrackSwitch(e,r){const n=qle(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((o,c)=>{e.event.isAssetPastPlayoutLimit(c)&&this.clearAssetPlayer(o.identifier,null)});const n=e.end+.25,i=Si.bufferInfo(this.primaryMedia,n,0);(i.end>n||(i.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Lh(e)} (was ${Lh(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=Si.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,o=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(r.length===1&&this.itemsMatch(r[0],o)){this.bufferedPos=e;return}const c=this.playingItem,s=this.findItemIndex(c);let f=i.findItemIndexAtTime(e);if(this.bufferedPos=o.end||(p=T.event)!=null&&p.appendInPlace&&e+.01>=T.start)&&(f=_),this.isInterstitial(o)){const E=o.event;if(_-s>1&&E.appendInPlace===!1||E.assetList.length===0&&E.assetListLoader)return}if(this.bufferedPos=e,f>y&&f>s)this.bufferedToItem(T);else{const E=this.primaryDetails;this.primaryLive&&E&&e>E.edge-E.targetduration&&T.start{const o=this.getAssetPlayer(i.identifier);return!(o!=null&&o.bufferedInPlaceToEnd(r))})}setBufferingItem(e){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,r)&&n){const{items:i,events:o}=n;if(!i||!o)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 ${Lh(e)}`+(r?` (${f.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(c){const p=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((y,_)=>{const T=this.getAssetPlayer(y.identifier);T&&(_===p&&T.loadSource(),T.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(p=>p.pauseBuffering());this.hls.trigger(je.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:o.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,o=n.cue.once;if(i||!o){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,o=i===0&&!e.assetListLoader,c=e.cue.once;if(o){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 p,y=0;if(!this.playingItem&&this.primaryLive&&(y=this.hls.startPosition,y===-1&&(y=this.hls.liveSyncPosition||0)),y&&!(e.cue.pre||e.cue.post)){const T=y-f;T>0&&(p=Math.round(T*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:i} ${e}${p?` live-start: ${y} start-offset: ${p}`:""}`),n)return this.createAsset(e,0,0,f,e.duration,n);const _=this.assetListLoader.loadAssetList(e,p);_&&(e.assetListLoader=_)}else if(!c&&i){for(let p=r;p{this.hls.trigger(je.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:Dn.OTHER_ERROR,details:Jt.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,Z=r.duration;(P||Z===null||W>Z)&&(P=!1,this.log(`Interstitial asset "${_}" duration change ${Z} > ${W}`),r.duration=W,this.updateSchedule())};k.on(je.LEVEL_UPDATED,(V,{details:G})=>R(G)),k.on(je.LEVEL_PTS_UPDATED,(V,{details:G})=>R(G)),k.on(je.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const D=(V,G)=>{const W=this.getAssetPlayer(_);if(W&&G.tracks){W.off(je.BUFFER_CODECS,D),W.tracks=G.tracks;const Z=this.primaryMedia;this.bufferingAsset===W.assetItem&&Z&&!W.media&&this.bufferAssetPlayer(W,Z)}};k.on(je.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),Z=(V=this.schedule.items)==null?void 0:V[W];this.isInterstitial(Z)&&this.advanceAssetBuffering(Z,r)};k.on(je.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 k.once(je.MEDIA_ENDED,B(n)),k.once(je.PLAYOUT_LIMIT_REACHED,B(1/0)),k.on(je.ERROR,(V,G)=>{if(!this.schedule)return;const W=this.getAssetPlayer(_);if(G.details===Jt.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}`)}),k.on(je.DESTROYING,()=>{if(!this.getAssetPlayer(_)||!this.schedule)return;const G=new Error(`Asset player destroyed unexpectedly ${_}`),W={fatal:!0,type:Dn.OTHER_ERROR,details:Jt.INTERSTITIAL_ASSET_ITEM_ERROR,error:G};this.handleAssetItemError(W,e,this.schedule.findEventIndex(e.identifier),n,G.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${yw(r)}`),this.hls.trigger(je.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:e,player:k}),k}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&&Lh(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,o){const{interstitial:c,assetItem:s,assetId:f}=e,p=c.assetList.length,y=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(!y||y.identifier!==f)&&(y&&(this.clearAssetPlayer(y.identifier,n[i]),delete y.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${p} ${yw(s)}`),this.hls.trigger(je.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:r,event:c,schedule:n.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,o)}bufferAssetPlayer(e,r){var n,i;if(!this.schedule)return;const{interstitial:o,assetItem:c}=e,s=this.schedule.findEventIndex(o.identifier),f=(n=this.schedule.items)==null?void 0:n[s];if(!f)return;e.loadSource(),this.setBufferingItem(f),this.bufferingAsset=c;const p=this.getBufferingPlayer();if(p===e)return;const y=o.appendInPlace;if(y&&(p==null?void 0:p.interstitial.appendInPlace)===!1)return;const _=(p==null?void 0:p.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(y&&c!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(_&&!P2e(_,e.tracks)){const T=new Error(`Asset ${yw(c)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(_)}')`),E={fatal:!0,type:Dn.OTHER_ERROR,details:Jt.INTERSTITIAL_ASSET_ITEM_ERROR,error:T},k=o.findAssetIndex(c);this.handleAssetItemError(E,o,s,k,T.message);return}}this.transferMediaTo(e,r)}handleInPlaceStall(e){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const i=n.currentTime,o=r.findAssetIndex(e,i),c=e.assetList[o];if(c){const s=this.getAssetPlayer(c.identifier);if(s){const f=s.currentTime||i-c.timelineStart,p=s.duration-f;if(this.warn(`Stalled at ${f} of ${f+p} in ${s} ${e} (media.currentTime: ${i})`),f&&(p/n.playbackRate<.5||s.bufferedInPlaceToEnd(n))&&s.hls){const y=r.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,y,o)}}}}advanceInPlace(e){const r=this.primaryMedia;r&&r.currentTime!P.error))r.error=k;else for(let P=i;P{const D=parseFloat(P.DURATION);this.createAsset(o,R,y,f+y,D,P.URI),y+=D}),o.duration=y,this.log(`Loaded asset-list with duration: ${y} (was: ${p}) ${o}`);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 k;const P=this.schedule.findEventIndex(c),R=(k=this.schedule.items)==null?void 0:k[P];if(R){if(!this.playingItem&&this.timelinePos>R.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==P){o.error=new Error(`Interstitial ${s.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${o}`),this.log(o.error.message),this.updateSchedule(!0),this.primaryFallback(o);return}this.setBufferingItem(R)}this.setSchedulePosition(P)}else if((E==null?void 0:E.identifier)===c){const P=o.assetList[0];if(P){const R=this.getAssetPlayer(P.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 Jt.ASSET_LIST_PARSING_ERROR:case Jt.ASSET_LIST_LOAD_ERROR:case Jt.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case Jt.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 Mce=500;class S3t extends yK{constructor(e,r,n){super(e,r,n,"subtitle-stream-controller",Tn.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(je.LEVEL_LOADED,this.onLevelLoaded,this),e.on(je.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(je.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(je.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(je.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(je.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(je.LEVEL_LOADED,this.onLevelLoaded,this),e.off(je.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(je.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(je.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(je.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(je.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,r){this.stopLoad(),this.state=wr.IDLE,this.setInterval(Mce),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)||(jo(n)&&(this.fragPrevious=n),this.state=wr.IDLE),!i)return;const o=this.tracksBuffered[this.currentTrackId];if(!o)return;let c;const s=n.start;for(let p=0;p=o[p].start&&s<=o[p].end){c=o[p];break}const f=n.start+n.duration;c?c.end=f:(c={start:s,end:f},o.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 o=i-1;if(o<=0)return;r.endOffsetSubtitles=Math.max(0,o),this.tracksBuffered.forEach(c=>{for(let s=0;snew Mk(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new Mk(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Tn.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!==wr.STOPPED&&this.setInterval(Mce)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:o}=this,{details:c,id:s}=r;if(!o){this.warn(`Subtitle tracks were reset while loading level ${s}`);return}const f=o[s];if(s>=o.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 p=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?(lO(c,_),p=c.fragmentStart):T&&(p=T.start,Vq(c,p));else{var y;p=this.alignPlaylists(c,f.details,(y=this.levelLastLoaded)==null?void 0:y.details),p===0&&T&&(p=T.start,Vq(c,p))}_&&!this.startFragRequested&&this.setStartPosition(_,p)}f.details=c,this.levelLastLoaded=f,s===i&&(this.hls.trigger(je.SUBTITLE_TRACK_UPDATED,{details:c,id:s,groupId:r.groupId}),this.tick(),c.live&&!this.fragCurrent&&this.media&&this.state===wr.IDLE&&(J_(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,o=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i!=null&&i.key&&i.iv&&c1(i.method)){const c=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer,pK(i.method)).catch(s=>{throw o.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_DECRYPT_ERROR,fatal:!1,error:s,reason:s.message,frag:r}),s}).then(s=>{const f=performance.now();o.trigger(je.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:c,tdecrypt:f}})}).catch(s=>{this.warn(`${s.name}: ${s.message}`),this.state=wr.IDLE})}}doTick(){if(!this.media){this.state=wr.IDLE;return}if(this.state===wr.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,o=this.getLoadPosition(),c=Si.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,i.maxBufferHole),{end:s,len:f}=c,p=n.details,y=this.hls.maxBufferLength+p.levelTargetDuration;if(f>y)return;const _=p.fragments,T=_.length,E=p.edge;let k=null;const P=this.fragPrevious;if(sE-M?0:M;k=J_(P,_,Math.max(_[0].start,s),B),!k&&P&&P.start<_[0].start&&(k=_[0])}else k=_[T-1];if(k=this.filterReplacedPrimary(k,n.details),!k)return;const R=k.sn-p.startSN,D=_[R-1];if(D&&D.cc===k.cc&&this.fragmentTracker.getState(D)===ll.NOT_LOADED&&(k=D),this.fragmentTracker.getState(k)===ll.NOT_LOADED){const M=this.mapToInitFragWhenRequired(k);M&&this.loadFragment(M,n,s)}}}loadFragment(e,r,n){jo(e)?super.loadFragment(e,r,n):this._loadInitSegment(e,r)}get mediaBufferTimeRanges(){return new T3t(this.tracksBuffered[this.currentTrackId]||[])}}class T3t{constructor(e){this.buffered=void 0;const r=(n,i,o)=>{if(i=i>>>0,i>o-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${o})`);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 E3t={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},XAe=t=>String.fromCharCode(E3t[t]||t),Oh=15,cp=100,A3t={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},j3t={17:2,18:4,21:6,22:8,23:10,19:13,20:15},k3t={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},C3t={25:2,26:4,29:6,30:8,31:10,27:13,28:15},I3t=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class N3t{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;Us.log(`${this.time} [${e}] ${n}`)}}}const W0=function(e){const r=[];for(let n=0;ncp&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=cp)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=XAe(e);if(this.pos>=cp){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 = "+sa(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+sa(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 o=0;o0&&(e?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class Oce{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 e6(n),this.nonDisplayedMemory=new e6(n),this.lastOutputScreen=new e6(n),this.currRollUpRow=this.displayedMemory.rows[Oh-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[Oh-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: "+sa(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 Fce{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=D3t(),this.logger=void 0;const i=this.logger=new N3t;this.channels=[null,new Oce(e,r,i),new Oce(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"["+W0([r[n],r[n+1]])+"] -> ("+W0([i,o])+")");const f=this.cmdHistory;if(i>=16&&i<=31){if(L3t(i,o,f)){PR(null,null,f),this.logger.log(3,()=>"Repeated command ("+W0([i,o])+") is dropped");continue}PR(i,o,this.cmdHistory),c=this.parseCmd(i,o),c||(c=this.parseMidrow(i,o)),c||(c=this.parsePAC(i,o)),c||(c=this.parseBackgroundAttributes(i,o))}else PR(null,null,f);if(!c&&(s=this.parseChars(i,o),s)){const y=this.currentChannel;y&&y>0?this.channels[y].insertChars(s):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!c&&!s&&this.logger.log(2,()=>"Couldn't parse cleaned data "+W0([i,o])+" orig: "+W0([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 o=e===20||e===21||e===23?1:2,c=this.channels[o];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=o,!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 ("+W0([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,o=(e===16||e===24)&&r>=64&&r<=95;if(!(i||o))return!1;const c=e<=23?1:2;r>=64&&r<=95?n=c===1?A3t[e]:k3t[e]:n=c===1?j3t[e]:C3t[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,o=null;if(e>=25?(n=2,o=e-8):(n=1,o=e),o>=17&&o<=19){let c;o===17?c=r+80:o===18?c=r+112:c=r+144,this.logger.log(2,()=>"Special char '"+XAe(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 = "+W0(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 o;const c={};e===16||e===24?(o=Math.floor((r-32)/2),c.background=I3t[o],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(y,"positionAlign",o({},_,{get:function(){return Z},set:function(se){const ue=i(se);if(!ue)throw new SyntaxError("An invalid or illegal string was specified.");Z=ue,this.hasBeenReset=!0}})),Object.defineProperty(y,"size",o({},_,{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(y,"align",o({},_,{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}})),y.displayState=void 0}return c.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},c}();class M3t{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function JAe(t){function e(n,i,o,c){return(n|0)*3600+(i|0)*60+(o|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 O3t{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 eje(t,e,r,n){const i=n?t.split(n):[t];for(const o in i){if(typeof i[o]!="string")continue;const c=i[o].split(r);if(c.length!==2)continue;const s=c[0],f=c[1];e(s,f)}}const Xq=new CK(0,0,""),RR=Xq.align==="middle"?"middle":"center";function F3t(t,e,r){const n=t;function i(){const s=JAe(t);if(s===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),s}function o(s,f){const p=new O3t;eje(s,function(T,E){let k;switch(T){case"region":for(let P=r.length-1;P>=0;P--)if(r[P].id===E){p.set(T,r[P].region);break}break;case"vertical":p.alt(T,E,["rl","lr"]);break;case"line":k=E.split(","),p.integer(T,k[0]),p.percent(T,k[0])&&p.set("snapToLines",!1),p.alt(T,k[0],["auto"]),k.length===2&&p.alt("lineAlign",k[1],["start",RR,"end"]);break;case"position":k=E.split(","),p.percent(T,k[0]),k.length===2&&p.alt("positionAlign",k[1],["start",RR,"end","line-left","line-right","auto"]);break;case"size":p.percent(T,E);break;case"align":p.alt(T,E,["start",RR,"end","left","right"]);break}},/:/,/\s/),f.region=p.get("region",null),f.vertical=p.get("vertical","");let y=p.get("line","auto");y==="auto"&&Xq.line===-1&&(y=-1),f.line=y,f.lineAlign=p.get("lineAlign","start"),f.snapToLines=p.get("snapToLines",!0),f.size=p.get("size",100),f.align=p.get("align",RR);let _=p.get("position","auto");_==="auto"&&Xq.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(),o(t,e)}function tje(t){return t.replace(//gi,` `)}class B3t{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new M3t,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 o=r.buffer,c=0;for(o=tje(o);c")===-1){r.cue.id=o;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{F3t(o,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const s=o.indexOf("-->")!==-1;if(!o||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+=o}continue;case"BADCUE":o||(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 z3t=/\r\n|\n\r|\n|\r/g,t6=function(e,r,n=0){return e.slice(n,n+r.length)===r},$3t=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),o=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!pn(r)||!pn(n)||!pn(i)||!pn(o))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*o,r};function IK(t,e,r){return ij(t.toString())+ij(e.toString())+ij(r)}const U3t=function(e,r,n){let i=e[r],o=e[i.prevCC];if(!o||!o.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(c=o)!=null&&c.new;){var c;e.ccOffset+=i.start-o.start,i.new=!1,i=o,o=e[i.prevCC]}e.presentationOffset=n};function V3t(t,e,r,n,i,o,c){const s=new B3t,f=cd(new Uint8Array(t)).trim().replace(z3t,` `).split(` `),p=[],y=e?YMt(e.baseTime,e.timescale):0;let _="00:00.000",T=0,E=0,k,P=!0;s.oncue=function(R){const D=r[n];let M=r.ccOffset;const B=(T-y)/9e4;if(D!=null&&D.new&&(E!==void 0?M=r.ccOffset=D.start:U3t(r,n,B)),B){if(!e){k=new Error("Missing initPTS for VTT MPEGTS");return}M=B-r.presentationOffset}const V=R.endTime-R.startTime,G=Zu((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=IK(R.startTime,R.endTime,W)),R.endTime>0&&p.push(R)},s.onparsingerror=function(R){k=R},s.onflush=function(){if(k){c(k);return}o(p)},f.forEach(R=>{if(P)if(t6(R,"X-TIMESTAMP-MAP=")){P=!1,R.slice(16).split(",").forEach(D=>{t6(D,"LOCAL:")?_=D.slice(6):t6(D,"MPEGTS:")&&(T=parseInt(D.slice(7)))});try{E=$3t(_)/1e3}catch(D){k=D}return}else R===""&&(P=!1);s.parse(R+` `)}),s.flush()}const r6="stpp.ttml.im1t",rje=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nje=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,q3t={left:"start",center:"center",right:"end",start:"start",end:"end"};function Bce(t,e,r,n){const i=qi(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const o=i.map(s=>cd(s)),c=KMt(e.baseTime,1,e.timescale);try{o.forEach(s=>r(G3t(s,c)))}catch(s){n(s)}}function G3t(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const o={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},c=Object.keys(o).reduce((_,T)=>(_[T]=i.getAttribute(`ttp:${T}`)||o[T],_),{}),s=i.getAttribute("xml:space")!=="preserve",f=zce(n6(i,"styling","style")),p=zce(n6(i,"layout","region")),y=n6(i,"body","[begin]");return[].map.call(y,_=>{const T=ije(_,s);if(!T||!_.hasAttribute("begin"))return null;const E=s6(_.getAttribute("begin"),c),k=s6(_.getAttribute("dur"),c);let P=s6(_.getAttribute("end"),c);if(E===null)throw $ce(_);if(P===null){if(k===null)throw $ce(_);P=E+k}const R=new CK(E-e,P-e,T);R.id=IK(R.startTime,R.endTime,R.text);const D=p[_.getAttribute("region")],M=f[_.getAttribute("style")],B=H3t(D,M,f),{textAlign:V}=B;if(V){const G=q3t[V];G&&(R.lineAlign=G),R.align=V}return Xs(R,B),R}).filter(_=>_!==null)}function n6(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function zce(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function ije(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var o;return n.nodeName==="br"&&i?r+` `:(o=n.childNodes)!=null&&o.length?ije(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function H3t(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const o=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],c=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return c&&r.hasOwnProperty(c)&&(i=r[c]),o.reduce((s,f)=>{const p=i6(e,n,f)||i6(t,n,f)||i6(i,n,f);return p&&(s[f]=p),s},{})}function i6(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function $ce(t){return new Error(`Could not parse ttml timestamp ${t}`)}function s6(t,e){if(!t)return null;let r=JAe(t);return r===null&&(rje.test(t)?r=W3t(t,e):nje.test(t)&&(r=K3t(t,e))),r}function W3t(t,e){const r=rje.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 K3t(t,e){const r=nje.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 LR{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 Y3t{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=Vce(),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(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(je.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(je.FRAG_LOADING,this.onFragLoading,this),e.on(je.FRAG_LOADED,this.onFragLoaded,this),e.on(je.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(je.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(je.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(je.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(je.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(je.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(je.FRAG_LOADING,this.onFragLoading,this),e.off(je.FRAG_LOADED,this.onFragLoaded,this),e.off(je.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(je.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(je.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(je.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(je.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new LR(this,"textTrack1"),r=new LR(this,"textTrack2"),n=new LR(this,"textTrack3"),i=new LR(this,"textTrack4");this.cea608Parser1=new Fce(1,e,r),this.cea608Parser2=new Fce(3,n,i)}addCues(e,r,n,i,o){let c=!1;for(let s=o.length;s--;){const f=o[s],p=Z3t(f[0],f[1],r,n);if(p>=0&&(f[0]=Math.min(f[0],r),f[1]=Math.max(f[1],n),c=!0,p/(n-r)>.5))return}if(c||o.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(je.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:o,trackId:c}){const{unparsedVttFrags:s}=this;n===Tn.MAIN&&(this.initPTS[r.cc]={baseTime:i,timescale:o,trackId:c}),s.length&&(this.unparsedVttFrags=[],s.forEach(f=>{this.initPTS[f.frag.cc]?this.onFragLoaded(je.FRAG_LOADED,f):this.hls.trigger(je.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{zw(i[o]),delete i[o]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Vce(),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;no.textCodec===r6);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(DAe(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const c=this.media,s=c?LL(c.textTracks):null;if(this.tracks.forEach((f,p)=>{let y;if(s){let _=null;for(let T=0;Tp!==null).map(p=>p.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(je.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 o=`textTrack${i[1]}`,c=this.captionsProperties[o];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===Tn.MAIN){var n,i;const{cea608Parser1:o,cea608Parser2:c,lastSn:s}=this,{cc:f,sn:p}=r.frag,y=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;o&&c&&(p!==s+1||p===s&&y!==this.lastPartIndex+1||f!==this.lastCc)&&(o.reset(),c.reset()),this.lastCc=f,this.lastSn=p,this.lastPartIndex=y}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.type===Tn.SUBTITLE)if(i.byteLength){const o=n.decryptdata,c="stats"in r;if(o==null||!o.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===r6?this._parseIMSC1(n,i):this._parseVTTs(r)}}else this.hls.trigger(je.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;Bce(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(je.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{n.logger.log(`Failed to parse IMSC1: ${i}`),n.trigger(je.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,{initPTS:o,unparsedVttFrags:c}=this,s=o.length-1;if(!o[n.cc]&&s===-1){c.push(e);return}const f=this.hls,p=(r=n.initSegment)!=null&&r.data?oh(n.initSegment.data,new Uint8Array(i)).buffer:i;V3t(p,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,y=>{this._appendCues(y,n.level),f.trigger(je.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},y=>{const _=y.message==="Missing initPTS for VTT MPEGTS";_?c.push(e):this._fallbackToIMSC1(n,i),f.logger.log(`Failed to parse VTT cue: ${y}`),!(_&&s>n.cc)&&f.trigger(je.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:y})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||Bce(r,this.initPTS[e.cc],()=>{n.textCodec=r6,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(o=>YAe(i,o))}else{const i=this.tracks[r];if(!i)return;const o=i.default?"default":"subtitles"+r;n.trigger(je.CUES_PARSED,{type:"subtitles",cues:e,track:o})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===Tn.SUBTITLE&&this.onFragLoaded(je.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===Tn.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;oZq(s[f],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:s}=this;Object.keys(s).forEach(f=>Zq(s[f],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let o=0;o=16?f--:f++;const E=tje(p.trim()),k=IK(e,r,E);t!=null&&(_=t.cues)!=null&&_.getCueById(k)||(c=new y(e,r,E),c.id=k,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=>YAe(t,T))),i}};function J3t(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const eFt=/(\d+)-(\d+)\/(\d+)/;class qce{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||iFt,this.controller=new self.AbortController,this.stats=new lK}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 o=tFt(e,this.controller.signal),c=e.responseType==="arraybuffer",s=c?"byteLength":"length",{maxTimeToFirstByteMs:f,maxLoadTimeMs:p}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,o),self.clearTimeout(this.requestTimeout),r.timeout=f&&pn(f)?f:p,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},r.timeout),(Bk(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=p,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},p-(E-i.loading.start)),!_.ok){const{status:P,statusText:R}=_;throw new sFt(R||"fetch, bad network response",P,_)}i.loading.first=E,i.total=nFt(_.headers)||i.total;const k=(T=this.callbacks)==null?void 0:T.onProgress;return k&&pn(r.highWaterMark)?this.loadProgressively(_,i,e,r.highWaterMark,k):c?_.arrayBuffer():e.responseType==="json"?_.json():_.text()}).then(_=>{var T,E;const k=this.response;if(!k)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const P=_[s];P&&(i.loaded=i.total=P);const R={url:k.url,data:_,code:k.status},D=(T=this.callbacks)==null?void 0:T.onProgress;D&&!pn(r.highWaterMark)&&D(i,e,_,k),(E=this.callbacks)==null||E.onSuccess(R,i,e,k)}).catch(_=>{var T;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const E=_&&_.code||0,k=_?_.message:null;(T=this.callbacks)==null||T.onError({code:E,text:k},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,o){const c=new pAe,s=e.body.getReader(),f=()=>s.read().then(p=>{if(p.done)return c.dataLength&&o(r,n,c.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const y=p.value,_=y.length;return r.loaded+=_,_=i&&o(r,n,c.flush().buffer,e)):o(r,n,y.buffer,e),f()}).catch(()=>Promise.reject());return f()}}function tFt(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Xs({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function rFt(t){const e=eFt.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function nFt(t){const e=t.get("Content-Range");if(e){const n=rFt(e);if(pn(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function iFt(t,e){return new self.Request(t.url,e)}class sFt extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const aFt=/^age:\s*[\d.]+\s*$/im;class aje{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 lK,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 o=this.xhrSetup;o?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return o(n,r.url)}).catch(c=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),o(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:o,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=o&&pn(o)?o: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,o=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),o.timeout!==o.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),o.timeout=o.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),o.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const p=r.status,y=r.responseType==="text"?r.responseText:null;if(p>=200&&p<300){const k=y??r.response;if(k!=null){var c,s;n.loading.end=Math.max(self.performance.now(),n.loading.first);const P=r.responseType==="arraybuffer"?k.byteLength:k.length;n.loaded=n.total=P,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,k,r);const D={url:r.responseURL,data:k,code:p};(s=this.callbacks)==null||s.onSuccess(D,n,e,r);return}}const _=o.loadPolicy.errorRetry,T=n.retry,E={url:e.url,data:void 0,code:p};if(sO(_,T,!1,E))this.retry(_);else{var f;Us.error(`${p} while loading ${e.url}`),(f=this.callbacks)==null||f.onError({code:p,text:r.statusText},e,r,n)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(sO(e,r,!0))this.retry(e);else{var n;Us.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=hK(e,n.retry),n.retry++,Us.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&&aFt.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 oFt={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},lFt=zs(zs({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:aje,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:vDt,bufferController:uOt,capLevelController:AK,errorController:EDt,fpsController:d3t,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:iAe,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:oFt},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},cFt()),{},{subtitleStreamController:S3t,subtitleTrackController:m3t,timelineController:Y3t,audioStreamController:aOt,audioTrackController:oOt,emeController:u1,cmcdController:o3t,contentSteeringController:c3t,interstitialsController:w3t});function cFt(){return{cueHandler:Q3t,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 uFt(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=Qq(t),i=["manifest","level","frag"],o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(c=>{const s=`${c==="level"?"playlist":c}LoadPolicy`,f=e[s]===void 0,p=[];o.forEach(y=>{const _=`${c}Loading${y}`,T=e[_];if(T!==void 0&&f){p.push(_);const E=n[s].default;switch(e[s]={default:E},y){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}}}),p.length&&r.warn(`hls.js config: "${p.join('", "')}" setting(s) are deprecated, use "${s}": ${sa(e[s])}`)}),zs(zs({},n),e)}function Qq(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(Qq):Object.keys(t).reduce((e,r)=>(e[r]=Qq(t[r]),e),{}):t}function dFt(t,e){const r=t.loader;r!==qce&&r!==aje?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):J3t()&&(t.loader=qce,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const DL=2,hFt=.1,fFt=.05,mFt=100;class pFt extends J2e{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(je.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.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(mFt),this.mediaSource=r.mediaSource;const n=this.media=r.media;Jc(n,"playing",this.onMediaPlaying),Jc(n,"waiting",this.onMediaWaiting),Jc(n,"ended",this.onMediaEnded)}onMediaDetaching(e,r){this.clearInterval();const{media:n}=this;n&&(ku(n,"playing",this.onMediaPlaying),ku(n,"waiting",this.onMediaWaiting),ku(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 o=(n=this.hls)==null?void 0:n.config;if(!o)return;const c=this.media;if(!c)return;const{seeking:s}=c,f=this.seeking&&!s,p=!this.seeking&&s,y=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,o.nudgeOnVideoHole&&!y&&e>r&&this.nudgeOnVideoHole(e,r)),this.waiting===0&&this.stallResolved(e);return}if(p||f){f&&this.stallResolved(e);return}if(y){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&c.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(je.MEDIA_ENDED,{stalled:!1}));return}if(!Si.getBuffered(c).length){this.nudgeRetry=0;return}const _=Si.bufferInfo(c,e,0),T=_.nextStart||0,E=this.fragmentTracker;if(s&&E&&this.hls){const W=Gce(this.hls.inFlightFragments,e),Z=_.len>DL,Q=!T||W||T-e>DL&&!E.getPartialFragment(e);if(Z||Q)return;this.moved=!1}const k=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&E){if(!(_.len>0)&&!T)return;const Z=Math.max(T,_.start||0)-e,re=!!(k!=null&&k.live)?k.targetduration*2:DL,se=DR(e,E);if(Z>0&&(Z<=re||se)){c.paused||this._trySkipBufferHole(se);return}}const P=o.detectStallWithCurrentTimeMs,R=self.performance.now(),D=this.waiting;let M=this.stalled;if(M===null)if(D>0&&R-D=P||D)&&this.hls){var V;if(((V=this.mediaSource)==null?void 0:V.readyState)==="ended"&&!(k!=null&&k.live)&&Math.abs(e-((k==null?void 0:k.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(je.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(_),!this.media||!this.hls)return}const G=Si.bufferInfo(c,e,o.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(je.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 o=Si.bufferedInfo(Si.timeRangesToArray(this.buffered.audio),e,0);if(o.len>1&&r>=o.start){const c=Si.timeRangesToArray(i),s=Si.bufferedInfo(c,r,0).bufferedIndex;if(s>-1&&ss)&&y-p<1&&e-p<2){const _=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${p} -> ${y} buffered index: ${f}`);this.warn(_.message),this.media.currentTime+=1e-6;let T=DR(e,this.fragmentTracker);T&&"fragment"in T?T=T.fragment:T||(T=void 0);const E=Si.bufferInfo(this.media,e,0);this.hls.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:_,reason:_.message,frag:T,buffer:E.len,bufferInfo:E})}}}}}_tryFixBufferStall(e,r,n){var i,o;const{fragmentTracker:c,media:s}=this,f=(i=this.hls)==null?void 0:i.config;if(!s||!c||!f)return;const p=(o=this.hls)==null?void 0:o.latestLevelDetails,y=DR(n,c);if((y||p!=null&&p.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 o=n.getFragAtPos(r,Tn.MAIN),c=n.getFragAtPos(i,Tn.MAIN);if(o&&c)return c.sn-o.sn<2}return!1}_reportStall(e){const{hls:r,media:n,stallReported:i,stalled:o}=this;if(!i&&o!==null&&n&&r){this.stallReported=!0;const c=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${sa(e)})`);this.warn(c.message),r.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_STALLED_ERROR,fatal:!1,error:c,buffer:e.len,bufferInfo:e,stalled:{start:o}})}}_trySkipBufferHole(e){var r;const{fragmentTracker:n,media:i}=this,o=(r=this.hls)==null?void 0:r.config;if(!i||!n||!o)return 0;const c=i.currentTime,s=Si.bufferInfo(i,c,0),f=c0&&s.len<1&&i.readyState<3,T=f-c;if(T>0&&(y||_)){if(T>o.maxBufferHole){let k=!1;if(c===0){const P=n.getAppendedFrag(0,Tn.MAIN);P&&f"u"))return self.VTTCue||self.TextTrackCue}function a6(t,e,r,n,i){let o=new t(e,r,"");try{o.value=n,i&&(o.type=i)}catch{o=new t(e,r,sa(i?zs({type:i},n):n))}return o}const MR=(()=>{const t=Jq();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class yFt{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(je.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(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(je.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(je.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(je.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(je.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&&zw(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;rMR&&(_=MR),_-y<=0&&(_=y+gFt);for(let E=0;Ey.type===td.audioId3&&f:i==="video"?p=y=>y.type===td.emsg&&s:p=y=>y.type===td.audioId3&&f||y.type===td.emsg&&s,Zq(o,r,n,p)}}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:o,interstitialsController:c}=this.hls.config;if(!o)return;const s=Jq();if(n&&i&&!c){const{fragmentStart:P,fragmentEnd:R}=e;let D=this.assetCue;D?(D.startTime=P,D.endTime=R):s&&(D=this.assetCue=a6(s,P,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:p}=e,y=Object.keys(p);let _=this.dateRangeCuesAppended;if(f&&r){var T;if((T=f.cues)!=null&&T.length){const P=Object.keys(_).filter(R=>!y.includes(R));for(let R=P.length;R--;){var E;const D=P[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 k=e.fragments[e.fragments.length-1];if(!(y.length===0||!pn(k==null?void 0:k.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let P=0;P{if(_e!==D.id){const we=p[_e];if(we.class===D.class&&we.startDate>D.startDate&&(!ue||D.startDate.01&&(_e.startTime=M,_e.endTime=W);else if(s){let we=D.attr[ue];BDt(ue)&&(we=R2e(we));const Me=a6(s,M,W,{key:ue,data:we},td.dateRange);Me&&(Me.id=R,this.id3Track.addCue(Me),V[ue]=Me,c&&(ue==="X-ASSET-LIST"||ue==="X-ASSET-URL")&&Me.addEventListener("enter",this.onEventCueEnter))}}_[R]={cues:V,dateRange:D,durationKnown:G}}}}}class xFt{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:o,maxLiveSyncPlaybackRate:c}=this.config;if(!o||c===1||!n.live)return;const s=this.targetLatency;if(s===null)return;const f=i-s,p=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:o,liveSyncDurationCount:c,lowLatencyMode:s}=this.config,f=this.hls.userConfig;let p=s&&n||r;(this._targetLatencyUpdated||f.liveSyncDuration||f.liveSyncDurationCount||p===0)&&(p=o!==void 0?o:c*i);const y=i;return p+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,y)}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,o=e-r-this.edgeStalled,c=i-n.totalduration,s=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(c,o),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(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(je.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(je.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(je.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(je.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===Jt.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 _Ft extends EK{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(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(je.LEVEL_LOADED,this.onLevelLoaded,this),e.on(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(je.FRAG_BUFFERED,this.onFragBuffered,this),e.on(je.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(je.LEVEL_LOADED,this.onLevelLoaded,this),e.off(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(je.FRAG_BUFFERED,this.onFragBuffered,this),e.off(je.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=[],o={},c={};let s=!1,f=!1,p=!1;r.levels.forEach(y=>{const _=y.attrs;let{audioCodec:T,videoCodec:E}=y;T&&(y.audioCodec=T=tO(T,n)||void 0),E&&(E=y.videoCodec=tDt(E));const{width:k,height:P,unknownCodecs:R}=y,D=(R==null?void 0:R.length)||0;if(s||(s=!!(k&&P)),f||(f=!!E),p||(p=!!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":Z}=_,re=`${`${G||"."}-`}${y.bitrate}-${W}-${B}-${M}-${Z}-${V}`;if(o[re])if(o[re].uri!==y.url&&!y.attrs["PATHWAY-ID"]){const se=c[re]+=1;y.attrs["PATHWAY-ID"]=new Array(se+1).join(".");const ue=this.createLevel(y);o[re]=ue,i.push(ue)}else o[re].addGroupId("audio",_.AUDIO),o[re].addGroupId("text",_.SUBTITLES);else{const se=this.createLevel(y);o[re]=se,c[re]=1,i.push(se)}}),this.filterAndSortMediaOptions(i,r,s,f,p)}createLevel(e){const r=new Mk(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=G2e(i,[])}return r}isAudioSupported(e){return Lk(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Lk(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,r,n,i,o){var c;let s=[],f=[],p=e;const y=((c=r.stats)==null?void 0:c.parsing)||{};if((n||i)&&o&&(p=p.filter(({videoCodec:M,videoRange:B,width:V,height:G})=>(!!M||!!(V&&G))&&dDt(B))),p.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: ${sa(r.levels.map(G=>G.attrs.CODECS).filter((G,W,Z)=>Z.indexOf(G)===W))}`,this.warn(B),M+=` (${B})`);const V=new Error(M);this.hls.trigger(je.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:V,reason:B})}}),y.end=performance.now();return}r.audioTracks&&(s=r.audioTracks.filter(M=>!M.audioCodec||this.isAudioSupported(M.audioCodec)),Wce(s)),r.subtitles&&(f=r.subtitles,Wce(f));const _=p.slice(0);p.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 rO.indexOf(M.videoRange)-rO.indexOf(B.videoRange);if(M.videoCodec!==B.videoCodec){const V=Fle(M.videoCodec),G=Fle(B.videoCodec);if(V!==G)return G-V}if(M.uri===B.uri&&M.codecSet!==B.codecSet){const V=eO(M.codecSet),G=eO(B.codecSet);if(V!==G)return G-V}return M.averageBitrate!==B.averageBitrate?M.averageBitrate-B.averageBitrate:0});let T=_[0];if(this.steering&&(p=this.steering.filterParsedLevels(p),p.length!==_.length)){for(let M=0;M<_.length;M++)if(_[M].pathwayId===p[0].pathwayId){T=_[M];break}}this._levels=p;for(let M=0;MV&&V===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=G)}break}const k=o&&!i,P=this.hls.config,R=!!(P.audioStreamController&&P.audioTrackController),D={levels:p,audioTracks:s,subtitleTracks:f,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:o,video:i,altAudio:R&&!k&&s.some(M=>!!M.url)};y.end=performance.now(),this.hls.trigger(je.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 y=new Error("invalid level idx"),_=e<0;if(this.hls.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.LEVEL_SWITCH_ERROR,level:e,fatal:_,error:y,reason:y.message}),_)return;e=Math.min(e,r.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,o=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&&o===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}${o?" with Pathway "+o:""}`);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(je.LEVEL_SWITCHING,f);const p=c.details;if(!p||p.live){const y=this.switchParams(c.uri,i==null?void 0:i.details,p);this.loadPlaylist(y)}}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===Hi.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r!==void 0&&r.type===Tn.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o]))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:o}=r,c=r.levelInfo;if(!c){var s;this.warn(`Invalid level index ${i}`),(s=r.deliveryDirectives)!=null&&s.skip&&(o.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&&(o.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,o=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:""}${o?" Pathway "+o:""}${s&&c.live?" age "+s.toFixed(1)+(c.type&&" "+c.type||""):""} ${n}`),this.hls.trigger(je.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((o,c)=>c!==e?!0:(this.steering&&this.steering.removeLevel(o),o===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,o.details&&o.details.fragments.forEach(s=>s.level=-1)),!1));hAe(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(je.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(je.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function Wce(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}function oje(){return self.SourceBuffer||self.WebKitSourceBuffer}function lje(){if(!cx())return!1;const e=oje();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function vFt(){if(!lje())return!1;const t=cx();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(Dk(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(Dk(e,"audio"))))}function bFt(){var t;const e=oje();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const wFt=100;class SFt extends yK{constructor(e,r,n){super(e,r,n,"stream-controller",Tn.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,o=i?i.currentTime:null;if(o===null||!pn(o)||(this.log(`Media seeked to ${o.toFixed(3)}`),!this.getBufferedFrag(o)))return;const c=this.getFwdBufferInfoAtPos(i,o,Tn.MAIN,0);if(c===null||c.len===0){this.warn(`Main forward buffer length at ${o} on "seeked" event ${c?c.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(je.MANIFEST_PARSED,this.onManifestParsed,this),e.on(je.LEVEL_LOADING,this.onLevelLoading,this),e.on(je.LEVEL_LOADED,this.onLevelLoaded,this),e.on(je.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(je.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(je.BUFFER_CREATED,this.onBufferCreated,this),e.on(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(je.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(je.MANIFEST_PARSED,this.onManifestParsed,this),e.off(je.LEVEL_LOADED,this.onLevelLoaded,this),e.off(je.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(je.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(je.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(je.BUFFER_CREATED,this.onBufferCreated,this),e.off(je.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(je.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(je.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(wFt),this.level=-1,!this.startFragRequested){let o=i.startLevel;o===-1&&(i.config.testBandwidth&&this.levels.length>1?(o=0,this.bitrateTest=!0):o=i.firstAutoLevel),i.nextLoadLevel=o,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=wr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=wr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case wr.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=wr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=wr.IDLE;break}break}case wr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===wr.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 o=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[o]))return;const c=n[o],s=this.getMainFwdBufferInfo();if(s===null)return;const f=this.getLevelDetails();if(f&&this._streamEnded(s,f)){const P={};this.altAudio===2&&(P.type="video"),this.hls.trigger(je.BUFFER_EOS,P),this.state=wr.ENDED;return}if(!this.buffering)return;e.loadLevel!==o&&e.manualLevel===-1&&this.log(`Adapting to level ${o} from level ${this.level}`),this.level=e.nextLoadLevel=o;const p=c.details;if(!p||this.state===wr.WAITING_LEVEL||this.waitForLive(c)){this.level=o,this.state=wr.WAITING_LEVEL,this.startFragRequested=!1;return}const y=s.len,_=this.getMaxBufferLength(c.maxBitrate);if(y>=_)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,p);if(this.couldBacktrack&&!this.fragPrevious&&E&&jo(E)&&this.fragmentTracker.getState(E)!==ll.OK){var k;const R=((k=this.backtrackFragment)!=null?k:E).sn-p.startSN,D=p.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?ta.AUDIO:ta.VIDEO,D=(R===ta.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;D&&this.afterBufferFlushed(D,R,Tn.MAIN)}E=this.getNextFragmentLoopLoading(E,p,s,Tn.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===ll.NOT_LOADED||i===ll.PARTIAL?jo(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,Tn.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 o=this.getLevelDetails();if(o!=null&&o.live){const s=this.getMainFwdBufferInfo();if(!s||s.len=c-r.maxFragLookUpTolerance&&o<=s;if(i!==null&&n.duration>i&&(o{this.hls&&this.hls.trigger(je.AUDIO_TRACK_SWITCHED,r)}),n.trigger(je.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(je.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=nO(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,o,c=!1;for(const s in n){const f=n[s];if(f.id==="main"){if(o=s,i=f,s==="video"){const p=n[s];p&&(this.videoBuffer=p.buffer)}}else c=!0}c&&i?(this.log(`Alternate track found, use ${o}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r,o=n.type===Tn.MAIN;if(o){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===wr.PARSED&&(this.state=wr.IDLE);return}const s=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),jo(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}const c=this.media;c&&(!this._hasEnoughToStart&&Si.getBuffered(c).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),o&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,r){var n;if(r.fatal){this.state=wr.ERROR;return}switch(r.details){case Jt.FRAG_GAP:case Jt.FRAG_PARSING_ERROR:case Jt.FRAG_DECRYPT_ERROR:case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Tn.MAIN,r);break;case Jt.LEVEL_LOAD_ERROR:case Jt.LEVEL_LOAD_TIMEOUT:case Jt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===wr.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===Hi.LEVEL&&(this.state=wr.IDLE);break;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case Jt.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 Jt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=wr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==ta.AUDIO||!this.altAudio){const n=(r===ta.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,Tn.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,o=n==null?void 0:n.frag;if(!o||this.fragContextChanged(o))return;r.fragmentError=0,this.state=wr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const c=o.stats;c.parsing.start=c.parsing.end=c.buffering.start=c.buffering.end=self.performance.now(),i.trigger(je.FRAG_LOADED,n),o.bitrateTest=!1}).catch(n=>{this.state===wr.STOPPED||this.state===wr.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const r=this.playlistType,{hls:n}=this,{remuxResult:i,chunkMeta:o}=e,c=this.getCurrentContext(o);if(!c){this.resetWhenMissingContext(o);return}const{frag:s,part:f,level:p}=c,{video:y,text:_,id3:T,initSegment:E}=i,{details:k}=p,P=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s)){this.fragmentTracker.removeFragment(s);return}if(this.state=wr.PARSING,E){const R=E.tracks;if(R){const V=s.initSegment||s;if(this.unhandledEncryptionError(E,s))return;this._bufferInitSegment(p,R,V,o),n.trigger(je.FRAG_PARSING_INIT_SEGMENT,{frag:V,id:r,tracks:R})}const D=E.initPTS,M=E.timescale,B=this.initPTS[s.cc];if(pn(D)&&(!B||B.baseTime!==D||B.timescale!==M)){const V=E.trackId;this.initPTS[s.cc]={baseTime:D,timescale:M,trackId:V},n.trigger(je.INIT_PTS_FOUND,{frag:s,id:r,initPTS:D,timescale:M,trackId:V})}}if(y&&k){P&&y.type==="audiovideo"&&this.logMuxedErr(s);const R=k.fragments[s.sn-1-k.startSN],D=s.sn===k.startSN,M=!R||s.cc>R.cc;if(i.independent!==!1){const{startPTS:B,endPTS:V,startDTS:G,endDTS:W}=y;if(f)f.elementaryStreams[y.type]={startPTS:B,endPTS:V,startDTS:G,endDTS:W};else if(y.firstKeyFrame&&y.independent&&o.id===1&&!M&&(this.couldBacktrack=!0),y.dropped&&y.independent){const Z=this.getMainFwdBufferInfo(),Q=(Z?Z.end:this.getLoadPosition())+this.config.maxBufferHole,re=y.firstKeyFramePTS?y.firstKeyFramePTS:B;if(!D&&QDL&&(s.gap=!0);s.setElementaryStreamInfo(y.type,B,V,G,W),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(y,s,f,o,D||M)}else if(D||M)s.gap=!0;else{this.backtrack(s);return}}if(P){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=P;f&&(f.elementaryStreams[ta.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),s.setElementaryStreamInfo(ta.AUDIO,R,D,M,B),this.bufferFragmentData(P,s,f,o)}if(k&&T!=null&&T.samples.length){const R={id:r,frag:s,details:k,samples:T.samples};n.trigger(je.FRAG_PARSING_METADATA,R)}if(k&&_){const R={id:r,frag:s,details:k,samples:_.samples};n.trigger(je.FRAG_PARSING_USERDATA,R)}}logMuxedErr(e){this.warn(`${jo(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,r,n,i){if(this.state!==wr.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:o,video:c,audiovideo:s}=r;if(o){const p=e.audioCodec;let y=kL(o.codec,p);y==="mp4a"&&(y="mp4a.40.5");const _=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){y&&(y.indexOf("mp4a.40.5")!==-1?y="mp4a.40.2":y="mp4a.40.5");const T=o.metadata;T&&"channelCount"in T&&(T.channelCount||1)!==1&&_.indexOf("firefox")===-1&&(y="mp4a.40.5")}y&&y.indexOf("mp4a.40.5")!==-1&&_.indexOf("android")!==-1&&o.container!=="audio/mpeg"&&(y="mp4a.40.2",this.log(`Android: force audio codec to ${y}`)),p&&p!==y&&this.log(`Swapping manifest audio codec "${p}" for "${y}"`),o.levelCodec=y,o.id=Tn.MAIN,this.log(`Init audio buffer, container:${o.container}, codecs[selected/level/parsed]=[${y||""}/${p||""}/${o.codec}]`),delete r.audiovideo}if(c){c.levelCodec=e.videoCodec,c.id=Tn.MAIN;const p=c.codec;if((p==null?void 0:p.length)===4)switch(p){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||""}/${p}]${c.codec!==p?" 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(je.BUFFER_CODECS,r),!this.hls)return;f.forEach(p=>{const _=r[p].initSegment;_!=null&&_.byteLength&&this.hls.trigger(je.BUFFER_APPENDING,{type:p,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,Tn.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=wr.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(Si.isBuffered(e,n)?r=this.getAppendedFrag(n):Si.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,o=r.level;(!i||r.sn!==i.sn||i.level!==o)&&(this.fragPlaying=r,this.hls.trigger(je.FRAG_CHANGED,{frag:r}),(!i||i.level!==o)&&this.hls.trigger(je.LEVEL_SWITCHED,{level:o}))}}}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 pn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var e;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(pn(r)){const n=this.getLevelDetails(),i=this.currentFrag||(n?J_(null,n.fragments,r):null);if(i){const o=i.programDateTime;if(o!==null){const c=o+(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 TFt extends hh{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=Jt.KEY_LOAD_ERROR,n,i,o){return new pp({type:Dn.NETWORK_ERROR,details:r,fatal:!1,frag:e,response:o,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,o=r.length;i{if(!this.emeController)return;c.setKeyFormat(s);const f=IL(s);if(f)return this.emeController.getKeySystemAccess([f])})}if(this.config.requireKeySystemAccessOnStart){const i=wA(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 o=e.decryptdata;if(!o){const p=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,Jt.KEY_LOAD_ERROR,p))}const c=o.uri;if(!c)return Promise.reject(this.createKeyLoadError(e,Jt.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${c}"`)));const s=o6(o);let f=this.keyIdToKeyInfo[s];if((n=f)!=null&&n.decryptdata.key)return o.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(y=>{const{keyInfo:_}=y;return o.key=_.decryptdata.key,{frag:e,keyInfo:_}})}switch(this.log(`${this.keyIdToKeyInfo[s]?"Rel":"L"}oading${o.keyId?" keyId: "+Kl(o.keyId):""} URI: ${o.uri} from ${e.type} ${e.level}`),f=this.keyIdToKeyInfo[s]={decryptdata:o,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},o.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return o.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,Jt.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${o.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=VLt(r.initSegment.data);if(c.length){let s=c[0];s.some(f=>f!==0)?(this.log(`Using keyId found in init segment ${Kl(s)}`),Gy.setKeyIdForUri(e.decryptdata.uri,s)):(s=Gy.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Kl(s)}`)),e.decryptdata.keyId=s}}if(!e.decryptdata.keyId&&!jo(r))return Promise.resolve(n);const o=this.emeController.loadKey(n);return(e.keyLoadPromise=o.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,o=new i(n);return r.keyLoader=e.loader=o,e.keyLoadPromise=new Promise((c,s)=>{const f={keyInfo:e,frag:r,responseType:"arraybuffer",url:e.decryptdata.uri},p=n.keyLoadPolicy.default,y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},_={onSuccess:(T,E,k,P)=>{const{frag:R,keyInfo:D}=k,M=o6(D.decryptdata);if(!R.decryptdata||D!==this.keyIdToKeyInfo[M])return s(this.createKeyLoadError(R,Jt.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),P));D.decryptdata.key=R.decryptdata.key=new Uint8Array(T.data),R.keyLoader=null,D.loader=null,c({frag:R,keyInfo:D})},onError:(T,E,k,P)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Jt.KEY_LOAD_ERROR,new Error(`HTTP Error ${T.code} loading key ${T.text}`),k,zs({url:f.url,data:void 0},T)))},onTimeout:(T,E,k)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Jt.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),k))},onAbort:(T,E,k)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Jt.INTERNAL_ABORTED,new Error("key loading aborted"),k))}};o.load(f,y,_)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,o=n.loader;r.keyLoader===o&&(r.keyLoader=null,n.loader=null);const c=o6(n.decryptdata)||i;delete this.keyIdToKeyInfo[c],o&&o.destroy()}}function o6(t){if(t.keyFormat!==Yl.FAIRPLAY){const e=t.keyId;if(e)return Kl(e)}return t.uri}function Kce(t){const{type:e}=t;switch(e){case Hi.AUDIO_TRACK:return Tn.AUDIO;case Hi.SUBTITLE_TRACK:return Tn.SUBTITLE;default:return Tn.MAIN}}function l6(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class EFt{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(je.MANIFEST_LOADING,this.onManifestLoading,this),e.on(je.LEVEL_LOADING,this.onLevelLoading,this),e.on(je.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(je.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(je.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(je.MANIFEST_LOADING,this.onManifestLoading,this),e.off(je.LEVEL_LOADING,this.onLevelLoading,this),e.off(je.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(je.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(je.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const r=this.hls.config,n=r.pLoader,i=r.loader,o=n||i,c=new o(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:Hi.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:o,url:c,deliveryDirectives:s,levelInfo:f}=r;this.load({id:n,level:i,pathwayId:o,responseType:"text",type:Hi.LEVEL,url:c,deliveryDirectives:s,levelOrTrack:f})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:o,deliveryDirectives:c,track:s}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Hi.AUDIO_TRACK,url:o,deliveryDirectives:c,levelOrTrack:s})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:o,deliveryDirectives:c,track:s}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Hi.SUBTITLE_TRACK,url:o,deliveryDirectives:c,levelOrTrack:s})}onLevelsUpdated(e,r){const n=this.loaders[Hi.LEVEL];if(n){const i=n.context;i&&!r.levels.some(o=>o===i.levelOrTrack)&&(n.abort(),delete this.loaders[Hi.LEVEL])}}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const p=this.hls.logger,y=i.context;if(y&&y.levelOrTrack===e.levelOrTrack&&(y.url===e.url||y.deliveryDirectives&&!e.deliveryDirectives)){y.url===e.url?p.log(`[playlist-loader]: ignore ${e.url} ongoing request`):p.log(`[playlist-loader]: ignore ${e.url} in favor of ${y.url}`);return}p.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let o;if(e.type===Hi.MANIFEST?o=n.manifestLoadPolicy.default:o=Xs({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),pn((r=e.deliveryDirectives)==null?void 0:r.part)){let p;if(e.type===Hi.LEVEL&&e.level!==null?p=this.hls.levels[e.level].details:e.type===Hi.AUDIO_TRACK&&e.id!==null?p=this.hls.audioTracks[e.id].details:e.type===Hi.SUBTITLE_TRACK&&e.id!==null&&(p=this.hls.subtitleTracks[e.id].details),p){const y=p.partTarget,_=p.targetduration;if(y&&_){const T=Math.max(y*3,_*.8)*1e3;o=Xs({},o,{maxTimeToFirstByteMs:Math.min(T,o.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(T,o.maxTimeToFirstByteMs)})}}}const c=o.errorRetry||o.timeoutRetry||{},s={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},f={onSuccess:(p,y,_,T)=>{const E=this.getInternalLoader(_);this.resetInternalLoader(_.type);const k=p.data;y.parsing.start=performance.now(),tm.isMediaPlaylist(k)||_.type!==Hi.MANIFEST?this.handleTrackOrLevelPlaylist(p,y,_,T||null,E):this.handleMasterPlaylist(p,y,_,T)},onError:(p,y,_,T)=>{this.handleNetworkError(y,_,!1,p,T)},onTimeout:(p,y,_)=>{this.handleNetworkError(y,_,!0,void 0,p)}};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 o=this.hls,c=e.data,s=l6(e,n),f=tm.parseMasterPlaylist(c,s);if(f.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(e,n,f.playlistParsingError,i,r);return}const{contentSteering:p,levels:y,sessionData:_,sessionKeys:T,startTimeOffset:E,variableList:k}=f;this.variableList=k,y.forEach(M=>{const{unknownCodecs:B}=M;if(B){const{preferManagedMediaSource:V}=this.hls.config;let{audioCodec:G,videoCodec:W}=M;for(let Z=B.length;Z--;){const Q=B[Z];Lk(Q,"audio",V)?(M.audioCodec=G=G?`${G},${Q}`:Q,wS.audio[G.substring(0,4)]=2,B.splice(Z,1)):Lk(Q,"video",V)&&(M.videoCodec=W=W?`${W},${Q}`:Q,wS.video[W.substring(0,4)]=2,B.splice(Z,1))}}});const{AUDIO:P=[],SUBTITLES:R,"CLOSED-CAPTIONS":D}=tm.parseMasterPlaylistMedia(c,s,f);P.length&&!P.some(B=>!B.url)&&y[0].audioCodec&&!y[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),P.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Za({}),bitrate:0,url:""})),o.trigger(je.MANIFEST_LOADED,{levels:y,audioTracks:P,subtitles:R,captions:D,contentSteering:p,url:s,stats:r,networkDetails:i,sessionData:_,sessionKeys:T,startTimeOffset:E,variableList:k})}handleTrackOrLevelPlaylist(e,r,n,i,o){const c=this.hls,{id:s,level:f,type:p}=n,y=l6(e,n),_=pn(f)?f:pn(s)?s:0,T=Kce(n),E=tm.parseLevelPlaylist(e.data,y,_,T,0,this.variableList);if(p===Hi.MANIFEST){const k={attrs:new Za({}),bitrate:0,details:E,name:"",url:y};E.requestScheduled=r.loading.start+cAe(E,0),c.trigger(je.MANIFEST_LOADED,{levels:[k],audioTracks:[],url:y,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,o)}handleManifestParsingError(e,r,n,i,o){this.hls.trigger(je.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.MANIFEST_PARSING_ERROR,fatal:r.type===Hi.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:r,networkDetails:i,stats:o})}handleNetworkError(e,r,n=!1,i,o){let c=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Hi.LEVEL?c+=`: ${e.level} id: ${e.id}`:(e.type===Hi.AUDIO_TRACK||e.type===Hi.SUBTITLE_TRACK)&&(c+=` id: ${e.id} group-id: "${e.groupId}"`);const s=new Error(c);this.hls.logger.warn(`[playlist-loader]: ${c}`);let f=Jt.UNKNOWN,p=!1;const y=this.getInternalLoader(e);switch(e.type){case Hi.MANIFEST:f=n?Jt.MANIFEST_LOAD_TIMEOUT:Jt.MANIFEST_LOAD_ERROR,p=!0;break;case Hi.LEVEL:f=n?Jt.LEVEL_LOAD_TIMEOUT:Jt.LEVEL_LOAD_ERROR,p=!1;break;case Hi.AUDIO_TRACK:f=n?Jt.AUDIO_TRACK_LOAD_TIMEOUT:Jt.AUDIO_TRACK_LOAD_ERROR,p=!1;break;case Hi.SUBTITLE_TRACK:f=n?Jt.SUBTITLE_TRACK_LOAD_TIMEOUT:Jt.SUBTITLE_LOAD_ERROR,p=!1;break}y&&this.resetInternalLoader(e.type);const _={type:Dn.NETWORK_ERROR,details:f,fatal:p,url:e.url,loader:y,context:e,error:s,networkDetails:r,stats:o};if(i){const T=(r==null?void 0:r.url)||e.url;_.response=zs({url:T,data:void 0},i)}this.hls.trigger(je.ERROR,_)}handlePlaylistLoaded(e,r,n,i,o,c){const s=this.hls,{type:f,level:p,levelOrTrack:y,id:_,groupId:T,deliveryDirectives:E}=i,k=l6(r,i),P=Kce(i);let R=typeof i.level=="number"&&P===Tn.MAIN?p:void 0;const D=e.playlistParsingError;if(D){if(this.hls.logger.warn(`${D} ${e.url}`),!s.config.ignorePlaylistParsingErrors){s.trigger(je.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_PARSING_ERROR,fatal:!1,url:k,error:D,reason:D.message,response:r,context:i,level:R,parent:P,networkDetails:o,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){const M=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(je.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_EMPTY_ERROR,fatal:!1,url:k,error:M,reason:M.message,response:r,context:i,level:R,parent:P,networkDetails:o,stats:n});return}switch(e.live&&c&&(c.getCacheAge&&(e.ageHeader=c.getCacheAge()||0),(!c.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),f){case Hi.MANIFEST:case Hi.LEVEL:if(R){if(!y)R=0;else if(y!==s.levels[R]){const M=s.levels.indexOf(y);M>-1&&(R=M)}}s.trigger(je.LEVEL_LOADED,{details:e,levelInfo:y||s.levels[0],level:R||0,id:_||0,stats:n,networkDetails:o,deliveryDirectives:E,withoutMultiVariant:f===Hi.MANIFEST});break;case Hi.AUDIO_TRACK:s.trigger(je.AUDIO_TRACK_LOADED,{details:e,track:y,id:_||0,groupId:T||"",stats:n,networkDetails:o,deliveryDirectives:E});break;case Hi.SUBTITLE_TRACK:s.trigger(je.SUBTITLE_TRACK_LOADED,{details:e,track:y,id:_||0,groupId:T||"",stats:n,networkDetails:o,deliveryDirectives:E});break}}}class Xf{static get version(){return Ok}static isMSESupported(){return lje()}static isSupported(){return vFt()}static getMediaSource(){return cx()}static get Events(){return je}static get MetadataSchema(){return td}static get ErrorTypes(){return Dn}static get ErrorDetails(){return Jt}static get DefaultConfig(){return Xf.defaultConfig?Xf.defaultConfig:lFt}static set DefaultConfig(e){Xf.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 xK,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=NLt(e.debug||!1,"Hls instance",e.assetPlayerId),n=this.config=uFt(Xf.DefaultConfig,e,r);this.userConfig=e,n.progressive&&dFt(n,r);const{abrController:i,bufferController:o,capLevelController:c,errorController:s,fpsController:f}=n,p=new s(this),y=this.abrController=new i(this),_=new ADt(this),T=n.interstitialsController,E=T?this.interstitialsController=new T(this,Xf):null,k=this.bufferController=new o(this,_),P=this.capLevelController=new c(this),R=new f(this),D=new EFt(this),M=n.contentSteeringController,B=M?new M(this):null,V=this.levelController=new _Ft(this,B),G=new yFt(this),W=new TFt(this.config,this.logger),Z=this.streamController=new SFt(this,_,W),Q=this.gapController=new pFt(this,_);P.setStreamController(Z),R.setStreamController(Z);const re=[D,V,Z];E&&re.splice(1,0,E),B&&re.splice(1,0,B),this.networkControllers=re;const se=[y,k,Q,P,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(xFt,se),this.coreComponents=se,re.push(p);const we=p.onErrorOut;typeof we=="function"&&this.on(je.ERROR,we,p),this.on(je.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===je.ERROR;this.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.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(je.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 o=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(je.ERROR,{type:Dn.OTHER_ERROR,details:Jt.ATTACH_MEDIA_ERROR,fatal:!0,error:o});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(je.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(je.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(je.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const r=this.media,n=this._url,i=this._url=oK.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(je.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={[Tn.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Tn.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Tn.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=p3t()),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){uDt(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 o=i;o--;){const c=e[o].attrs["HDCP-LEVEL"];if(c&&c<=n)return o}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=K2e(r);return H2e(e,n,navigator.mediaCapabilities)}}Xf.defaultConfig=void 0;const AFt=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function SA(t){return!!t&&AFt.test(t)&&!/\.mp4($|\?)/i.test(t)}function jFt(t){const e=t.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return e?{libraryId:e[1],videoId:e[2]}:null}function kFt(t,e){if(!t)return null;const r=jFt(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 CFt(t){const e=t.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return e?e[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const Yce=I.forwardRef(function({sourceUrl:e,thumbnailUrl:r,autoPlay:n,muted:i,loop:o,playsInline:c=!0,...s},f){const p=I.useRef(null),[y,_]=I.useState(null),T=I.useMemo(()=>kFt(e,{autoplay:!!n,muted:!!i,loop:!!o}),[e,n,i,o]);I.useEffect(()=>{let k=!1;if(!e){_(null);return}if(!SA(e)){_(e);return}if(!T){_(null);return}return _(null),fetch(T).then(async P=>{if(!P.ok)throw new Error(`Failed to load Bunny embed (${P.status})`);const R=await P.text();return CFt(R)}).then(P=>{k||_(P)}).catch(()=>{k||_(null)}),()=>{k=!0}},[T,e]),I.useEffect(()=>{const k=p.current;if(!k||!y)return;let P=null;const R=()=>{if(!n)return;const M=k.play();M&&M.catch(()=>{})};if(k.muted=!!i,k.loop=!!o,y.endsWith(".m3u8")){if(k.canPlayType("application/vnd.apple.mpegurl")){k.src=y;const M=()=>R();return k.addEventListener("loadedmetadata",M),()=>{k.removeEventListener("loadedmetadata",M),k.removeAttribute("src"),k.load()}}return Xf.isSupported()?(P=new Xf({enableWorker:!0,lowLatencyMode:!0}),P.loadSource(y),P.attachMedia(k),P.on(Xf.Events.MANIFEST_PARSED,R),()=>{P==null||P.destroy(),k.removeAttribute("src"),k.load()}):void 0}k.src=y;const D=()=>R();return k.addEventListener("loadedmetadata",D),()=>{k.removeEventListener("loadedmetadata",D),k.removeAttribute("src"),k.load()}},[n,o,i,y]),I.useEffect(()=>{const k=p.current;if(k){if(k.muted=!!i,k.loop=!!o,n&&y){const P=k.play();P&&P.catch(()=>{});return}k.pause()}},[n,o,i,y]);const E=k=>{if(p.current=k,typeof f=="function"){f(k);return}f&&(f.current=k)};return a.jsx("video",{ref:E,poster:r||void 0,autoPlay:n,muted:i,loop:o,playsInline:c,preload:"metadata",...s})}),IFt={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 NFt(){try{let t=localStorage.getItem("vg_visitor_token");return t||(t=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",t)),t}catch{return null}}function Zce(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 PFt({config:t,appSlug:e="video_greeter",preview:r=!1,embedded:n=!1}){const[i,o]=I.useState(!1),[c,s]=I.useState(!1),[f,p]=I.useState(!0),[y,_]=I.useState(!1),[T,E]=I.useState("portrait"),[k,P]=I.useState(!1),[R,D]=I.useState(!1),[M,B]=I.useState({name:"",email:"",phone:""}),[V,G]=I.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),W=I.useRef(null),Z=I.useRef(null),Q=I.useRef(!1),re=async(cr,xr)=>{if(!r)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:e,event_type:cr,visitor_token:NFt(),page_url:typeof window<"u"?window.location.href:null,metadata:xr||{}})}catch{}};I.useEffect(()=>{if(y)return;const cr=typeof window<"u"?window.location.pathname:"/",xr=t.targeting||{mode:"all"};if(xr.mode==="include"&&!Zce(xr.include,cr)||xr.mode==="exclude"&&Zce(xr.exclude,cr))return;const tr=t.trigger||{type:"immediate"};if(tr.type==="immediate"||r){o(!0);return}if(tr.type==="delay"){const _n=(tr.value||3)*1e3,lt=setTimeout(()=>o(!0),_n);return()=>clearTimeout(lt)}if(tr.type==="scroll"){const _n=(tr.value||25)/100,lt=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=_n&&(o(!0),window.removeEventListener("scroll",lt))};return window.addEventListener("scroll",lt,{passive:!0}),()=>window.removeEventListener("scroll",lt)}if(tr.type==="exit_intent"){const _n=lt=>{lt.clientY<=0&&o(!0)};return document.addEventListener("mouseleave",_n),()=>document.removeEventListener("mouseleave",_n)}},[y,t.targeting,t.trigger,r]),I.useEffect(()=>{i&&!Q.current&&(Q.current=!0,re("impression"))},[i]),I.useEffect(()=>{if(c&&Z.current&&!SA(t.video_url)){Z.current.currentTime=0,Z.current.muted=!1,p(!1);const cr=Z.current.play();cr&&cr.catch(()=>{})}else c&&SA(t.video_url)&&p(!1)},[c,t.video_url]),I.useEffect(()=>{if(!t.thumbnail_url)return;let cr=!1;const xr=new Image;return xr.onload=()=>{cr||E(xr.naturalWidth>xr.naturalHeight?"landscape":"portrait")},xr.src=t.thumbnail_url,()=>{cr=!0}},[t.thumbnail_url]),I.useEffect(()=>{const cr=()=>{G({width:window.innerWidth,height:window.innerHeight})};return cr(),window.addEventListener("resize",cr),()=>window.removeEventListener("resize",cr)},[]);const se=()=>{s(!0),re("expand")},ue=cr=>{cr.stopPropagation(),_(!0),s(!1)},_e=cr=>{re("cta_click",{cta_id:cr.id,label:cr.label,url:cr.url})},we=async cr=>{if(cr.preventDefault(),r){P(!0);return}if(!(!M.email||!M.name)){D(!0);try{const{error:xr}=await Re.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(xr)throw xr;re("lead_capture",{email:M.email}),P(!0)}catch(xr){console.error("lead submit failed",xr)}finally{D(!1)}}};if(!i||y||!t.video_url&&!t.video_embed_url)return null;const Ce=IFt[T][t.size||"md"],Me=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",be=r?T==="landscape"?"w-[280px]":"w-[220px]":T==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",me=T==="landscape"?"aspect-video":"aspect-[9/16]",Pe=t.agent||{},Ie=t.lead_form_fields||["name","email","phone"],Se=!!(t.show_socials&&(Pe.instagram_url||Pe.facebook_url||Pe.linkedin_url)),ve=108+(t.ctas||[]).length*48+(t.lead_form_enabled&&!k?72+Ie.length*42:0)+(k?40:0)+(Se?34:0),We=Math.max(300,V.height-32),rt=Math.max(220,V.width-32),at=Math.max(150,We-ve),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":`${be} 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`,pt=n?{width:`${_t}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Nt=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",vt=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 a.jsx("div",{"data-vg-widget":!0,"data-expanded":c?"true":"false",className:`${Me} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c?a.jsxs("div",{className:Vt,style:pt,children:[a.jsxs("div",{className:`relative bg-black ${me}`,children:[SA(t.video_url)?a.jsx(Yce,{ref:Z,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:f,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:cr=>{const{videoWidth:xr,videoHeight:tr}=cr.currentTarget;xr&&tr&&E(xr>tr?"landscape":"portrait")},onEnded:()=>re("watch_complete")},`expanded-${t.video_url}-${t.thumbnail_url||"no-thumb"}-${c?"on":"off"}`):a.jsx("video",{ref:Z,src:t.video_url||void 0,poster:t.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>re("watch_complete"),onLoadedMetadata:cr=>{const{videoWidth:xr,videoHeight:tr}=cr.currentTarget;xr&&tr&&E(xr>tr?"landscape":"portrait")}}),a.jsx("button",{onClick:()=>{Z.current&&(Z.current.muted=!Z.current.muted,p(Z.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:f?a.jsx(CDe,{className:"w-4 h-4"}):a.jsx(kDe,{className:"w-4 h-4"})}),a.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:a.jsx(Ds,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:Nt,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[Pe.avatar_url&&a.jsx("img",{src:Pe.avatar_url,alt:Pe.name||"",className:er}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:vt,children:t.greeting_title||"Glad you're here!"}),t.greeting_subtitle&&a.jsx("p",{className:or,children:t.greeting_subtitle})]})]}),(t.ctas||[]).length>0&&a.jsx("div",{className:"space-y-2",children:(t.ctas||[]).map(cr=>{var xr;return a.jsxs("a",{href:cr.url,target:(xr=cr.url)!=null&&xr.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>_e(cr),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 ${cr.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[a.jsx("span",{children:cr.label}),a.jsx(iv,{className:"w-3.5 h-3.5 opacity-60"})]},cr.id)})}),t.lead_form_enabled&&!k&&a.jsxs("form",{onSubmit:we,className:"space-y-2 pt-1",children:[Ie.includes("name")&&a.jsx("input",{type:"text",placeholder:"Name",required:!0,value:M.name,onChange:cr=>B({...M,name:cr.target.value}),className:Sr}),Ie.includes("email")&&a.jsx("input",{type:"email",placeholder:"Email",required:!0,value:M.email,onChange:cr=>B({...M,email:cr.target.value}),className:Sr}),Ie.includes("phone")&&a.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:M.phone,onChange:cr=>B({...M,phone:cr.target.value}),className:Sr}),a.jsxs("button",{type:"submit",disabled:R,className:nn,children:[a.jsx(lD,{className:"w-3.5 h-3.5"}),R?"Sending...":"Send"]})]}),k&&a.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&&(Pe.instagram_url||Pe.facebook_url||Pe.linkedin_url)&&a.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[Pe.instagram_url&&a.jsx("a",{href:Pe.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"instagram"}),children:a.jsx(Dfe,{className:"w-4 h-4"})}),Pe.facebook_url&&a.jsx("a",{href:Pe.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"facebook"}),children:a.jsx(Rfe,{className:"w-4 h-4"})}),Pe.linkedin_url&&a.jsx("a",{href:Pe.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"linkedin"}),children:a.jsx(Ffe,{className:"w-4 h-4"})})]})]})]}):a.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[a.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:Ce.w,height:Ce.h},"aria-label":"Play video greeting",children:[SA(t.video_url)?a.jsx(Yce,{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:cr=>{const{videoWidth:xr,videoHeight:tr}=cr.currentTarget;xr&&tr&&E(xr>tr?"landscape":"portrait")}},`collapsed-${t.video_url}-${t.thumbnail_url||"no-thumb"}`):a.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:cr=>{const{videoWidth:xr,videoHeight:tr}=cr.currentTarget;xr&&tr&&E(xr>tr?"landscape":"portrait")}}),a.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),a.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:a.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:a.jsx("path",{d:"M8 5v14l11-7z"})})}),a.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"})]}),a.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:a.jsx(Ds,{className:"w-3.5 h-3.5"})})]})})}function NK({slug:t}){const[e,r]=I.useState(null);return I.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_video_greeter_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?a.jsx(PFt,{config:e}):null}const cje="eip_last_shown",Xce="eip_visitor_token";function RFt(){try{let t=localStorage.getItem(Xce);return t||(t=crypto.randomUUID(),localStorage.setItem(Xce,t)),t}catch{return}}function LFt(t){try{const e=Number(localStorage.getItem(cje)||0);return e?Date.now()-e>t*24*60*60*1e3:!0}catch{return!0}}function DFt(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 MFt({config:t,preview:e=!1,forceOpen:r=!1}){const[n,i]=I.useState(r),[o,c]=I.useState(!1),[s,f]=I.useState(!1),[p,y]=I.useState({name:"",email:"",phone:""}),_=I.useRef(!1),T=I.useRef(!1),E=async(W,Z={})=>{if(!e)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:"exit_intent",event_type:W,visitor_token:RFt(),page_url:window.location.href,metadata:Z})}catch{}};I.useEffect(()=>{if(e||!DFt(t.targeting)||!LFt(t.frequency_days))return;const W=/Mobi|Android/i.test(navigator.userAgent),Z={low:5,medium:15,high:30}[t.trigger_sensitivity]||15,Q=_e=>{if(!_.current){_.current=!0,i(!0);try{localStorage.setItem(cje,String(Date.now()))}catch{}E("impression",{reason:_e})}},re=_e=>{_e.clientY<=Z&&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]),I.useEffect(()=>{n&&!T.current&&!e&&!_.current&&(T.current=!0)},[n,e]);const k=()=>{i(!1),e||E("close")},P=async W=>{if(W.preventDefault(),e){c(!0);return}if(!(!p.email||!p.name)){f(!0);try{const{error:Z}=await Re.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"exit_intent",name:p.name,email:p.email,phone:p.phone||void 0,page_url:window.location.href}});if(Z)throw Z;E("lead_capture",{email:p.email}),c(!0),t.cta_url&&setTimeout(()=>{window.location.href=t.cta_url},1200)}catch(Z){console.error("exit intent submit failed",Z)}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 a.jsx("div",{className:G,style:{background:e?"transparent":"rgba(0,0,0,0.6)"},children:a.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:[a.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${V}, ${c6(V,-25)})`}}),a.jsx("button",{onClick:k,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:a.jsx(Ds,{className:"w-4 h-4"})}),a.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[B&&a.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}}),a.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:[a.jsx(xs,{className:"w-3 h-3"}),t.offer_label]})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.headline}),a.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.subheadline})]}),o?a.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${V}10`,color:V},children:[a.jsx("div",{className:"text-3xl",children:"🎉"}),a.jsx("p",{className:"text-sm font-medium",style:{color:V},children:t.success_message})]}):t.form_enabled?a.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[R.includes("name")&&a.jsx("input",{type:"text",placeholder:"Your name",value:p.name,onChange:W=>y({...p,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")&&a.jsx("input",{type:"email",placeholder:"you@email.com",value:p.email,onChange:W=>y({...p,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")&&a.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:p.phone,onChange:W=>y({...p,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}}),a.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}, ${c6(V,-20)})`},children:s?"Sending...":t.cta_label}),a.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):a.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}, ${c6(V,-20)})`},children:t.cta_label}),M&&a.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",M]})]})]})})}function c6(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,o=r>>16,c=r>>8&255,s=r&255,f=Math.round((n-o)*i)+o,p=Math.round((n-c)*i)+c,y=Math.round((n-s)*i)+s;return"#"+(16777216+(f<<16)+(p<<8)+y).toString(16).slice(1)}catch{return t}}function PK({slug:t}){const[e,r]=I.useState(null);return I.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_exit_intent_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?a.jsx(MFt,{config:e}):null}const Qce="lm_dismissed",Jce="lm_visitor_token";function OFt(){try{let t=localStorage.getItem(Jce);return t||(t=crypto.randomUUID(),localStorage.setItem(Jce,t)),t}catch{return}}function FFt(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 BFt({config:t,preview:e=!1}){const[r,n]=I.useState(!1),[i,o]=I.useState(!1),[c,s]=I.useState(!1),[f,p]=I.useState(!1),[y,_]=I.useState({name:"",email:"",phone:""}),T=I.useRef(!1),E=async(B,V={})=>{if(!e)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:"lead_magnet",event_type:B,visitor_token:OFt(),page_url:window.location.href,metadata:V})}catch{}};I.useEffect(()=>{if(e){n(!0);return}if(!FFt(t.targeting))return;try{if(sessionStorage.getItem(Qce))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 k=()=>{n(!1);try{sessionStorage.setItem(Qce,"1")}catch{}e||E("close")},P=async B=>{if(B.preventDefault(),e){s(!0);return}if(!(!y.email||!y.name)){p(!0);try{const{error:V}=await Re.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"lead_magnet",name:y.name,email:y.email,phone:y.phone||void 0,page_url:window.location.href}});if(V)throw V;E("lead_capture",{email:y.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{p(!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 a.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:[a.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${R}, ${lA(R,-20)})`},children:a.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[a.jsx(rf,{className:"w-5 h-5 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold truncate",children:t.title}),a.jsx("p",{className:"text-xs text-white/80 truncate",children:t.description})]}),a.jsx("button",{onClick:()=>{o(!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}),a.jsx("button",{onClick:k,className:"text-white/80 hover:text-white","aria-label":"Close",children:a.jsx(Ds,{className:"w-4 h-4"})})]})}),i&&M()]});if(!i)return a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>{o(!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}, ${lA(R,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:a.jsx(N1,{className:"w-5 h-5"})}),a.jsxs("div",{className:"text-left text-white",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:t.badge_label}),a.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:t.title})]}),a.jsx("button",{onClick:B=>{B.stopPropagation(),k()},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:a.jsx(Ds,{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 a.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:()=>o(!1),children:a.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:[a.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${R}, ${lA(R,-25)})`},children:[t.cover_image_url?a.jsx("img",{src:t.cover_image_url,alt:t.title,className:"w-full h-full object-cover opacity-90"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(cm,{className:"w-20 h-20 text-white/40"})}),a.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:[a.jsx(rf,{className:"w-3 h-3"}),t.badge_label]}),a.jsx("button",{onClick:()=>o(!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:a.jsx(Ds,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.title}),a.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.description})]}),c?a.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${R}10`},children:[a.jsx(rc,{className:"w-8 h-8 mx-auto",style:{color:R}}),a.jsx("p",{className:"text-sm font-medium",style:{color:R},children:t.success_message}),t.download_url&&a.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?a.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[B.includes("name")&&a.jsx("input",{type:"text",placeholder:"Your name",value:y.name,onChange:W=>_({...y,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")&&a.jsx("input",{type:"email",placeholder:"you@email.com",value:y.email,onChange:W=>_({...y,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")&&a.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:y.phone,onChange:W=>_({...y,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}}),a.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}, ${lA(R,-20)})`},children:[a.jsx(rc,{className:"w-4 h-4"}),f?"Sending...":t.download_label]}),a.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):a.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}, ${lA(R,-20)})`},children:t.download_label}),G&&a.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",G]})]})]})})}}function lA(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,o=r>>16,c=r>>8&255,s=r&255,f=Math.round((n-o)*i)+o,p=Math.round((n-c)*i)+c,y=Math.round((n-s)*i)+s;return"#"+(16777216+(f<<16)+(p<<8)+y).toString(16).slice(1)}catch{return t}}function RK({slug:t}){const[e,r]=I.useState(null);return I.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_lead_magnet_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?a.jsx(BFt,{config:e}):null}function LK({siteConfig:t,className:e="",iconClassName:r=""}){var o;const n=((o=t==null?void 0:t.themeConfig)==null?void 0:o.socialLinks)||null;if(!n)return null;const i=[{key:"facebook",url:n.facebook,Icon:Rfe,label:"Facebook"},{key:"instagram",url:n.instagram,Icon:Dfe,label:"Instagram"},{key:"linkedin",url:n.linkedin,Icon:Ffe,label:"LinkedIn"},{key:"youtube",url:n.youtube,Icon:NDe,label:"YouTube"}].filter(c=>!!c.url);return i.length?a.jsx("div",{className:`flex items-center gap-3 ${e}`,children:i.map(({key:c,url:s,Icon:f,label:p})=>a.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer","aria-label":p,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:a.jsx(f,{className:"h-4 w-4"})},c))}):null}const zFt="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109";function $Ft({children:t,siteConfig:e}){var Pr,Rn,ci,ti,zi,wa,xi,la;const r=Bi(),n=Gs(),[i,o]=I.useState(!1),[c,s]=I.useState(!1);I.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&s(!0)},[]);const[f,p]=I.useState(!1),[y,_]=I.useState([]),[T,E]=I.useState([]),[k,P]=I.useState([]),[R,D]=I.useState(null),M=I.useRef(null),B=I.useRef(null),{user:V,profile:G,signOut:W}=hT();sK(e,V==null?void 0:V.id),aK(e,V==null?void 0:V.id);const Z=((Pr=e.agent)==null?void 0:Pr.full_name)||"Agent",Q=e.siteTitle||`${Z} Real Estate`,re=r.pathname==="/search",se=r.pathname==="/",ue=e.leadRegistrationMode!=="disabled",_e=e.id===zFt;I.useEffect(()=>{(async()=>{const{data:Fn}=await Re.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});_(Fn||[])})()},[e.id]),I.useEffect(()=>{(async()=>{const{data:Fn}=await Re.from("lead_site_menu_items").select("*").eq("site_id",e.id).order("sort_order",{ascending:!0});P(Fn||[]),E((Fn||[]).filter(As=>As.is_visible!==!1))})()},[e.id]),I.useEffect(()=>{const Cr=Fn=>{M.current&&!M.current.contains(Fn.target)&&p(!1),B.current&&!B.current.contains(Fn.target)&&D(null)};return document.addEventListener("mousedown",Cr),()=>document.removeEventListener("mousedown",Cr)},[]);const we=ax(e),Ce=e==null?void 0:e.bookingUrl,{data:Me}=GF(we?e.agentId:null),Ae=((Me==null?void 0:Me.length)??0)>0,{data:be}=XW(e.agentId),me=((be==null?void 0:be.length)??0)>0,Pe=T.filter(Cr=>{const Fn=String(Cr.target_url||"").toLowerCase().replace(/\/+$/,""),As=String(Cr.label||"").toLowerCase();return!(we&&(Fn==="/search"||Fn.startsWith("/search?")||As.includes("search"))||Fn==="/listings"&&we&&!Ae||Fn==="/sold"&&!me)}),Ie=we&&Ae&&Pe.length>0&&!Pe.some(Cr=>String(Cr.target_url||"").toLowerCase().startsWith("/listings"))?[...Pe,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:Pe,Se=Ie.length>0,ve=[{to:"/",label:"Home"},...we?[]:[{to:"/search",label:"Search"}],...we&&Ae?[{to:"/listings",label:"My Listings"}]:[],...me?[{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(Cr=>!Cr.parent_id),rt=Cr=>Ie.filter(Fn=>Fn.parent_id===Cr),at=k.filter(Cr=>!Cr.parent_id),Et=new Set([...at,...We].filter(Cr=>String(Cr.target_url||"").trim()!=="").map(Cr=>String(Cr.target_url).toLowerCase().replace(/\/+$/,"")||"/")),_t=new Set([...at,...We].map(Cr=>String(Cr.label||"").trim().toLowerCase())),pt=["/","/search","/about","/contact","/sell","/blog"].some(Cr=>Et.has(Cr)),Nt=pt?[]:ve.filter(Cr=>!Et.has(Cr.to.toLowerCase())&&!_t.has(Cr.label.toLowerCase())),er=pt?We.filter(Cr=>Cr.is_visible!==!1&&String(Cr.target_url||"").trim()!=="").map(Cr=>({to:String(Cr.target_url),label:String(Cr.label||"").trim()||"Link"})):Nt,vt=at.find(Cr=>Cr.item_type==="cities"),or=String((vt==null?void 0:vt.label)||"Cities").trim()||"Cities",Sr=y.length>0&&!_e,nn=Sr&&!vt,cr=Cr=>`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${Cr?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"}`,xr=r.pathname.startsWith("/homes-for-sale-in-"),tr=Cr=>a.jsxs("div",{ref:M,className:"relative",children:[a.jsxs("button",{onClick:()=>p(!f),className:`flex items-center gap-1 ${cr(xr)}`,children:[Cr," ",a.jsx(wc,{className:`h-3.5 w-3.5 transition-transform ${f?"rotate-180":""}`})]}),f&&a.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:y.map(Fn=>a.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Fn.city_slug}`),p(!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:Fn.city_name},Fn.city_slug))})]},"__cities"),_n=Cr=>a.jsxs("div",{children:[a.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${se?"text-white/40":"text-gray-400"}`,children:Cr}),y.map(Fn=>a.jsx(mn,{to:`/homes-for-sale-in-${Fn.city_slug}`,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${Fn.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:Fn.city_name},Fn.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||`${Z} - Real Estate`,Mt=e.seoMetaDescription||e.siteTagline||`Browse homes and listings with ${Z}`,dr=e.ogImageUrl||((Rn=e.agent)==null?void 0:Rn.avatar_url)||"",ur=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,hr=rK(e.siteTitle,Z),Xt=(e.googleSearchConsoleVerification||"").trim().replace(/^google-site-verification[=:]\s*/i,"").replace(/^content=/i,"").replace(/^["']|["']$/g,"");return a.jsxs("div",{className:`flex flex-col ${re?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[a.jsx(nK,{siteConfig:e,pagePath:r.pathname}),(!_e||r.pathname==="/p/frequently-asked-questions")&&a.jsx(iK,{siteConfig:e}),a.jsxs(Wo,{children:[a.jsx("title",{children:At}),a.jsx("meta",{name:"description",content:Mt}),Xt&&a.jsx("meta",{name:"google-site-verification",content:Xt}),a.jsx("meta",{property:"og:site_name",content:hr}),a.jsx("meta",{property:"og:title",content:At}),a.jsx("meta",{property:"og:description",content:Mt}),a.jsx("meta",{property:"og:type",content:"website"}),a.jsx("meta",{property:"og:url",content:ur+r.pathname}),dr&&a.jsx("meta",{property:"og:image",content:dr}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),a.jsx("meta",{name:"twitter:title",content:At}),a.jsx("meta",{name:"twitter:description",content:Mt}),dr&&a.jsx("meta",{name:"twitter:image",content:dr}),e.faviconUrl&&a.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),a.jsx("link",{rel:"canonical",href:`${ur}${r.pathname}`}),e.subdomainSlug==="matthogg"&&a.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),a.jsxs("header",{className:`${se?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${lt}`,children:[a.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:a.jsxs("div",{className:"flex items-center justify-between h-20",children:[a.jsxs(mn,{to:"/",className:"flex items-center gap-3",children:[e.showTeamLogo&&e.teamLogoUrl?a.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${UPt(e.headerLogoSize)} w-auto object-contain`}):(ci=e.agent)!=null&&ci.avatar_url?a.jsx("img",{src:e.agent.avatar_url,alt:Z,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,a.jsx("div",{children:a.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:Q})})]}),a.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[e.bookingUrl&&!_e&&a.jsx(Pp,{bookingUrl:e.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),Nt.map(Cr=>a.jsx(mn,{to:Cr.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===Cr.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:Cr.label},Cr.to)),Se&&We.map(Cr=>{if(Cr.item_type==="cities")return Sr?tr(String(Cr.label||"Cities")):null;if(Cr.item_type==="dropdown"){const Fn=rt(Cr.id);return a.jsxs("div",{ref:B,className:"relative",children:[a.jsxs("button",{onClick:()=>D(R===Cr.id?null:Cr.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:[Cr.label," ",a.jsx(wc,{className:`h-3.5 w-3.5 transition-transform ${R===Cr.id?"rotate-180":""}`})]}),R===Cr.id&&Fn.length>0&&a.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:Fn.map(As=>a.jsx(OR,{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))})]},Cr.id)}return a.jsx(OR,{item:Cr,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"}`},Cr.id)}),nn&&tr(or),!_e&&(V?a.jsx("div",{className:"ml-2",children:a.jsx(eK,{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?a.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)]}),a.jsx("button",{onClick:()=>o(!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?a.jsx(Ds,{className:"h-5 w-5"}):a.jsx(IS,{className:"h-5 w-5"})})]})}),i&&a.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:a.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[e.bookingUrl&&!_e&&a.jsx(Pp,{bookingUrl:e.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),Nt.map(Cr=>a.jsx(mn,{to:Cr.to,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===Cr.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:Cr.label},Cr.to)),Se&&We.map(Cr=>{if(Cr.item_type==="cities")return Sr?_n(String(Cr.label||"Cities")):null;if(Cr.item_type==="dropdown"){const Fn=rt(Cr.id);return a.jsxs("div",{className:"space-y-1",children:[a.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${se?"text-white/40":"text-gray-400"}`,children:Cr.label}),Fn.map(As=>a.jsx(OR,{item:As,onClick:()=>o(!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))]},Cr.id)}return a.jsx(OR,{item:Cr,onClick:()=>o(!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"}`},Cr.id)}),nn&&_n(or),!_e&&(V?a.jsx(tK,{dark:se,onNavigate:()=>o(!1)}):ue?a.jsx("button",{onClick:()=>{s(!0),o(!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)]})})]}),a.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!re&&a.jsx("footer",{className:"bg-gray-950 text-gray-400",children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((ti=e.agent)==null?void 0:ti.avatar_url)&&a.jsx("img",{src:e.agent.avatar_url,alt:Z,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-bold text-white text-lg tracking-tight",children:Z}),a.jsx("p",{className:"text-sm text-gray-400",children:_e?"Personal Real Estate Advisor":((zi=e.agent)==null?void 0:zi.title)||"Real Estate Professional"})]})]}),((wa=e.agent)==null?void 0:wa.phone)&&a.jsx("p",{className:"text-sm mt-3",children:a.jsxs("a",{href:`tel:${e.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[a.jsx(ai,{className:"h-3.5 w-3.5"})," ",e.agent.phone]})}),((xi=e.agent)==null?void 0:xi.email)&&a.jsx("p",{className:"text-sm mt-1",children:a.jsxs("a",{href:`mailto:${e.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," ",e.agent.email]})}),a.jsx(LK,{siteConfig:e,className:"mt-4"}),_e&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm mt-4",children:"Helping you find the right real estate agent, wherever you need one."}),a.jsx("p",{className:"text-sm mt-2",children:"Columbia, Missouri"})]})]}),a.jsxs("div",{children:[a.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),a.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(Cr=>a.jsx("li",{children:/^https?:\/\//i.test(Cr.to)?a.jsx("a",{href:Cr.to,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:Cr.label}):a.jsx(mn,{to:Cr.to,className:"hover:text-white transition-colors",children:Cr.label})},Cr.to)),Ce&&!_e&&a.jsx("li",{children:a.jsx("a",{href:Ce,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),y.length>0&&!_e&&a.jsxs(a.Fragment,{children:[a.jsx("h2",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),a.jsx("ul",{className:"space-y-3 text-sm",children:y.map(Cr=>a.jsx("li",{children:a.jsx(mn,{to:`/homes-for-sale-in-${Cr.city_slug}`,className:"hover:text-white transition-colors",children:Cr.city_name})},Cr.city_slug))})]})]}),a.jsxs("div",{children:[a.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),a.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.":we?"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."}),a.jsx(mn,{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"})]})]}),a.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[e.showTeamLogo&&e.teamLogoUrl&&a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${VPt(e.headerLogoSize)} w-auto object-contain`})}),e.brokerageLegalName&&a.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-400 mb-3",children:[a.jsxs("span",{children:[Z," · ",e.brokerageLegalName]}),e.agentLicenseNumber&&a.jsx("span",{children:e.agentLicenseNumber}),e.brokerageLicenseNumber&&a.jsxs("span",{children:["Brokerage #",e.brokerageLicenseNumber]})]}),e.mlsDisclaimerText&&a.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&a.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),a.jsx("p",{className:"text-[11px] text-gray-400 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),a.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-400",children:[e.equalHousingEnabled&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-400",children:a.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),a.jsx("span",{children:"Equal Housing Opportunity"})]}),a.jsxs("span",{children:["© ",new Date().getFullYear()," ",Z,". Powered by LevelUp."]})]})]})]})}),!re&&!_e&&((la=e.agent)==null?void 0:la.avatar_url)&&a.jsx(UFt,{agent:e.agent,bookingUrl:Ce}),c&&a.jsx(JW,{open:c,mode:"optional",siteConfig:e,onComplete:()=>s(!1),onSkip:()=>s(!1)}),a.jsx(NK,{slug:e.subdomainSlug}),a.jsx(PK,{slug:e.subdomainSlug}),!_e&&a.jsx(RK,{slug:e.subdomainSlug})]})}function UFt({agent:t,bookingUrl:e}){var o;const[r,n]=I.useState(!1),i=Gs();return t?a.jsx("div",{className:`fixed right-6 z-40 ${e?"bottom-24 md:bottom-6":"bottom-6"}`,children:r?a.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:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[a.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-bold text-gray-900 text-sm",children:t.full_name}),a.jsx("p",{className:"text-xs text-gray-600",children:t.title||"Real Estate Professional"})]})]}),a.jsx("p",{className:"text-xs text-gray-600 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),a.jsxs("div",{className:"space-y-2",children:[t.phone&&a.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:[a.jsx(ai,{className:"h-4 w-4 text-gray-400"}),t.phone]}),t.email&&a.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:[a.jsx(Ti,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),a.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&&a.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"})]})]}),a.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:a.jsx(Ds,{className:"h-4 w-4"})})]}):a.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:[a.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(o=t.full_name)==null?void 0:o.split(" ")[0]}),a.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function OR({item:t,className:e,onClick:r}){const n=t.target_url||"#";return/^(https?:)?\/\//i.test(n)||/^(mailto:|tel:)/i.test(n)?a.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:e,onClick:r,children:t.label}):a.jsx(mn,{to:n,className:e,onClick:r,children:t.label})}const VFt=new Set(["danicapatton"]);function uje(t){if(!t)return!1;const e=t.themeConfig||{};return e.expReady===!1?!1:e.expReady===!0||VFt.has(t.subdomainSlug)}const qFt="/exp-ready",GFt="eXp Ready",eue={california:"California DRE License",ca:"California DRE License"};function eG(t){const e=(t||"").trim();if(!e)return"Real Estate License";const r=e.toLowerCase();return eue[r]?eue[r]:`${e.replace(/\b\w/g,i=>i.toUpperCase())} Real Estate License`}function tue(t){if(t)return t.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function HFt({children:t,siteConfig:e}){var er,vt,or,Sr,nn,cr,xr;const r=Bi(),n=Gs(),[i,o]=I.useState(!1),[c,s]=I.useState(!1);I.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&s(!0)},[]);const[f,p]=I.useState(!1),[y,_]=I.useState(!1),[T,E]=I.useState([]),[k,P]=I.useState(!1),R=I.useRef(null),D=I.useRef(null),{user:M,profile:B,signOut:V}=hT();sK(e,M==null?void 0:M.id),aK(e,M==null?void 0:M.id);const G=((er=e.agent)==null?void 0:er.full_name)||"Agent",W=tue(e.agentLicenseNumber),Z=tue(e.brokerageLicenseNumber),Q=e.siteTitle||`${G} Real Estate`,re=tr=>{if(!tr)return tr;const _n=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lt=new RegExp(`^\\s*${_n}\\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,we=r.pathname==="/search",Ce=r.pathname==="/",Me=e.leadRegistrationMode!=="disabled",Ae="#c9a96e",be=e.bookingUrl;I.useEffect(()=>{const tr=()=>P(window.scrollY>80);return window.addEventListener("scroll",tr,{passive:!0}),()=>window.removeEventListener("scroll",tr)},[]),I.useEffect(()=>{(async()=>{const{data:_n}=await Re.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(_n||[])})()},[e.id]),I.useEffect(()=>{const tr=_n=>{R.current&&!R.current.contains(_n.target)&&p(!1),D.current&&!D.current.contains(_n.target)&&_(!1)};return document.addEventListener("mousedown",tr),()=>document.removeEventListener("mousedown",tr)},[]);const me=(((vt=e.themeConfig)==null?void 0:vt.focusPages)??[]).filter(tr=>tr==null?void 0:tr.slug).map(tr=>({to:`/${tr.slug}`,label:tr.navLabel||tr.title})).concat(uje(e)?[{to:qFt,label:GFt}]:[]),Pe=b2e(e)||ax(e),{data:Ie}=GF(Pe?e.agentId:null),Se=((Ie==null?void 0:Ie.length)??0)>0,{data:ve}=XW(e.agentId),We=((ve==null?void 0:ve.length)??0)>0,rt=[{to:"/",label:"Home"},...Pe?Se?[{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,...me],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)||"",pt=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,Nt=Ce?k?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return a.jsxs("div",{className:`flex flex-col ${we?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[a.jsx(nK,{siteConfig:e,pagePath:r.pathname}),a.jsx(iK,{siteConfig:e}),a.jsxs(Wo,{children:[a.jsx("title",{children:Et}),a.jsx("meta",{name:"description",content:_t}),a.jsx("meta",{property:"og:title",content:Et}),a.jsx("meta",{property:"og:description",content:_t}),a.jsx("meta",{property:"og:type",content:"website"}),a.jsx("meta",{property:"og:url",content:pt+r.pathname}),Vt&&a.jsx("meta",{property:"og:image",content:Vt}),a.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),a.jsx("meta",{name:"twitter:title",content:Et}),a.jsx("meta",{name:"twitter:description",content:_t}),Vt&&a.jsx("meta",{name:"twitter:image",content:Vt}),e.faviconUrl&&a.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),a.jsx("link",{rel:"canonical",href:`${pt}${r.pathname}`}),a.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"})]}),a.jsxs("header",{className:`${Ce?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Nt}`,children:[a.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:a.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[a.jsxs(mn,{to:"/",className:"flex items-center gap-3 shrink-0",children:[e.showTeamLogo&&e.teamLogoUrl&&a.jsx("img",{src:e.teamLogoUrl,alt:`${G} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),a.jsxs("span",{className:"flex flex-col leading-tight",children:[a.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&&a.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:e.brokerageLegalName}),_e&&a.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:_e})]})]}),a.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[rt.map(tr=>a.jsx(mn,{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)),me.length>0&&a.jsxs("div",{ref:D,className:"relative",children:[a.jsxs("button",{onClick:()=>_(!y),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 ${me.some(tr=>r.pathname===tr.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",a.jsx(wc,{className:`h-3 w-3 transition-transform ${y?"rotate-180":""}`})]}),y&&a.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:me.map(tr=>a.jsx(mn,{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&&a.jsxs("div",{ref:R,className:"relative",children:[a.jsxs("button",{onClick:()=>p(!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 ",a.jsx(wc,{className:`h-3 w-3 transition-transform ${f?"rotate-180":""}`})]}),f&&a.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=>a.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${tr.city_slug}`),p(!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?a.jsx("div",{className:"ml-3",children:a.jsx(eK,{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"})}):Me?a.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,be&&a.jsx(Pp,{bookingUrl:be,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),a.jsxs("button",{onClick:()=>o(!i),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[a.jsx("div",{className:"flex flex-col items-center gap-0.5",children:i?a.jsx(Ds,{className:"h-5 w-5"}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-6 h-px bg-current"}),a.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),a.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),a.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),i&&a.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:a.jsxs("div",{className:"px-6 py-4 space-y-1",children:[be&&a.jsx(Pp,{bookingUrl:be,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),rt.map(tr=>a.jsx(mn,{to:tr.to,onClick:()=>o(!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)),me.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Specialty"}),me.map(tr=>a.jsx(mn,{to:tr.to,onClick:()=>o(!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&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Cities"}),T.map(tr=>a.jsx(mn,{to:`/homes-for-sale-in-${tr.city_slug}`,onClick:()=>o(!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?a.jsx(tK,{dark:!0,onNavigate:()=>o(!1)}):Me?a.jsx("button",{onClick:()=>{s(!0),o(!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]})})]}),a.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!we&&a.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:a.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),a.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||Z)&&a.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[W&&a.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[eG(e.licenseState)," #",W]}),Z&&a.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",Z]})]}),((nn=e.agent)==null?void 0:nn.phone)&&a.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," ",e.agent.phone]}),((cr=e.agent)==null?void 0:cr.email)&&a.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," ",e.agent.email]}),a.jsx(LK,{siteConfig:e,className:"mt-6",iconClassName:"border-white/20"})]}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Quick Links"}),a.jsxs("ul",{className:"space-y-3",children:[at.map(tr=>a.jsx("li",{children:a.jsx(mn,{to:tr.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:tr.label})},tr.to)),be&&a.jsx("li",{children:a.jsx("a",{href:be,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:fT},children:"Schedule a Free Consultation"})})]})]}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Get In Touch"}),a.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."}),a.jsxs("div",{className:"flex flex-col items-start gap-3",children:[be&&a.jsx(Pp,{bookingUrl:be,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),a.jsx(mn,{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"})]})]})]}),a.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[e.showTeamLogo&&e.teamLogoUrl&&a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:e.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),e.brokerageLegalName&&a.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:[a.jsxs("span",{children:[G," · ",e.brokerageLegalName]}),W&&a.jsxs("span",{children:[eG(e.licenseState)," #",W]}),Z&&a.jsxs("span",{children:["Brokerage #",Z]})]}),e.mlsDisclaimerText&&a.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&a.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),a.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),a.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[e.equalHousingEnabled&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:a.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),a.jsx("span",{children:"Equal Housing Opportunity"})]}),a.jsxs("span",{children:["© ",new Date().getFullYear()," ",G,". Powered by LevelUp."]})]})]})]})}),!we&&((xr=e.agent)==null?void 0:xr.avatar_url)&&a.jsx(WFt,{agent:e.agent,agentLicense:W,siteConfig:e,accentColor:Ae}),c&&a.jsx(JW,{open:c,mode:"optional",siteConfig:e,onComplete:()=>s(!1),onSkip:()=>s(!1),theme:"luxury",accentColor:Ae}),a.jsx(NK,{slug:e.subdomainSlug}),a.jsx(PK,{slug:e.subdomainSlug}),a.jsx(RK,{slug:e.subdomainSlug})]})}function WFt({agent:t,agentLicense:e,siteConfig:r,accentColor:n}){var s;const[i,o]=I.useState(!1),c=Gs();return t?a.jsx("div",{className:`fixed right-6 z-40 ${r.bookingUrl?"bottom-24 md:bottom-6":"bottom-6"}`,children:i?a.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:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:t.full_name}),a.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:t.title||"Real Estate Professional"})]})]}),e&&a.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[a.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:eG(r.licenseState)}),a.jsxs("p",{className:"text-xs text-white font-medium",children:["#",e]})]}),a.jsxs("div",{className:"space-y-2",children:[t.phone&&a.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:[a.jsx(ai,{className:"h-3.5 w-3.5"})," ",t.phone]}),t.email&&a.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:[a.jsx(Ti,{className:"h-3.5 w-3.5"})," Email Me"]}),a.jsx("button",{onClick:()=>{o(!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"})]})]}),a.jsx("button",{onClick:()=>o(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:a.jsx(Ds,{className:"h-4 w-4"})})]}):a.jsxs("button",{onClick:()=>o(!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:[a.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),a.jsxs("div",{className:"text-left",children:[a.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]}),a.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:n},children:"Let's connect →"})]})]})}):null}const cA="#2c1810",up="#b8860b";function KFt({children:t,siteConfig:e}){var Ce,Me,Ae;const r=Bi();Gs();const[n,i]=I.useState(!1),[o,c]=I.useState(!1);I.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&c(!0)},[]);const[s,f]=I.useState(!1),[p,y]=I.useState([]),[_,T]=I.useState(!1),E=I.useRef(null),{user:k,profile:P,signOut:R}=hT();sK(e,k==null?void 0:k.id),aK(e,k==null?void 0:k.id);const D=((Ce=e.agent)==null?void 0:Ce.full_name)||"Agent",M=e.siteTitle||`${D} Land & Ranch`,B=r.pathname==="/",V=e.leadRegistrationMode!=="disabled",G=ax(e);I.useEffect(()=>{const be=()=>T(window.scrollY>80);return window.addEventListener("scroll",be,{passive:!0}),()=>window.removeEventListener("scroll",be)},[]),I.useEffect(()=>{(async()=>{const{data:me}=await Re.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order");me&&y(me)})()},[e.id]),I.useEffect(()=>{const be=me=>{E.current&&!E.current.contains(me.target)&&f(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[]);const{data:W}=XW(e.agentId),{data:Z}=GF(e.agentId),Q=((W==null?void 0:W.length)??0)>0,re=((Z==null?void 0:Z.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?cA:"#ffffff",we=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`;return a.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[a.jsxs(Wo,{children:[a.jsx("title",{children:M}),a.jsx("meta",{property:"og:url",content:we+r.pathname}),a.jsx("link",{rel:"canonical",href:`${we}${r.pathname}`}),a.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"})]}),a.jsx(nK,{siteConfig:e}),a.jsx(iK,{siteConfig:e}),a.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${ue}`,children:[a.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:a.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[a.jsxs(mn,{to:"/",className:"flex items-center gap-2.5",children:[a.jsx(mee,{className:"w-7 h-7",style:{color:up}}),a.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:_e,fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),a.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[se.map(be=>a.jsx(mn,{to:be.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===be.path?up:_e},children:be.label},be.path)),p.length>0&&a.jsxs("div",{ref:E,className:"relative",children:[a.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 ",a.jsx(wc,{className:`w-3.5 h-3.5 transition-transform ${s?"rotate-180":""}`})]}),s&&a.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:p.map(be=>a.jsx(mn,{to:`/homes-for-sale-in-${be.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:cA},onClick:()=>f(!1),children:be.city_name},be.city_slug))})]}),k?a.jsx("div",{className:"ml-3",children:a.jsx(eK,{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?a.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:up},children:"Sign In"}):null]}),a.jsx("button",{onClick:()=>i(!n),className:"md:hidden p-2",style:{color:_e},children:n?a.jsx(Ds,{className:"w-6 h-6"}):a.jsx(IS,{className:"w-6 h-6"})})]})}),n&&a.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:a.jsxs("div",{className:"px-4 py-4 space-y-1",children:[se.map(be=>a.jsx(mn,{to:be.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===be.path?up:cA},onClick:()=>i(!1),children:be.label},be.path)),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Area Guides"}),p.map(be=>a.jsx(mn,{to:`/homes-for-sale-in-${be.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:cA},onClick:()=>i(!1),children:be.city_name},be.city_slug))]}),k&&a.jsx(tK,{onNavigate:()=>i(!1)}),!k&&V&&a.jsx("button",{onClick:()=>{c(!0),i(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:up},children:"Sign In"})]})})]}),a.jsx("main",{children:t}),a.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:cA},children:a.jsxs("div",{className:"max-w-6xl mx-auto",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx(mee,{className:"w-6 h-6",style:{color:up}}),a.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),a.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Personal guidance for buying and selling land, homes, and rural property."}),a.jsx(LK,{siteConfig:e,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),a.jsx("div",{className:"space-y-2",children:se.map(be=>a.jsx(mn,{to:be.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:be.label},be.path))})]}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),a.jsxs("div",{className:"space-y-3",children:[((Me=e.agent)==null?void 0:Me.phone)&&a.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[a.jsx(ai,{className:"w-4 h-4",style:{color:up}}),e.agent.phone]}),((Ae=e.agent)==null?void 0:Ae.email)&&a.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[a.jsx(Ti,{className:"w-4 h-4",style:{color:up}}),e.agent.email]})]})]})]}),a.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[a.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",M,". All rights reserved."]}),a.jsx("div",{className:"h-px w-16",style:{backgroundColor:up}})]})]})}),o&&a.jsx(JW,{open:o,mode:e.leadRegistrationMode==="required"?"required":"optional",siteConfig:e,onSkip:()=>c(!1),onComplete:()=>c(!1)}),a.jsx(NK,{slug:e.subdomainSlug}),a.jsx(PK,{slug:e.subdomainSlug}),a.jsx(RK,{slug:e.subdomainSlug})]})}function FR(){const{pathname:t}=Bi();return I.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[t]),null}const YFt=I.lazy(()=>Fe(()=>import("./LeadSiteHome-Dy_hVUOG.js"),__vite__mapDeps([10,11,12,13,14,15,16,17,18]))),ZFt=I.lazy(()=>Fe(()=>import("./LeadSiteLuxuryHome-BgX8M3M9.js"),__vite__mapDeps([19,20,14,15,21,18,22,23]))),XFt=I.lazy(()=>Fe(()=>import("./LeadSiteLandRanchHome-Cl8Ytng8.js"),__vite__mapDeps([24,11,12,13,14,15,16,25,26,27]))),BR=I.lazy(()=>Fe(()=>import("./LeadSiteSearch-QIkzG9es.js"),__vite__mapDeps([28,11,12,13,29,30,31,32]))),QFt=I.lazy(()=>Fe(()=>import("./LeadSiteLuxurySearch-BcMKZNdM.js"),__vite__mapDeps([33,11,12,13,29,30,31,32]))),zR=I.lazy(()=>Fe(()=>import("./LeadSiteListingDetail-DP_3MMIx.js"),__vite__mapDeps([34,35,36,26,37,38,39,40,41]))),JFt=I.lazy(()=>Fe(()=>import("./LeadSiteLuxuryListingDetail-BG0sQbW0.js"),__vite__mapDeps([42,35,36,26,37,38,39,40,41]))),e5t=I.lazy(()=>Fe(()=>import("./LeadSiteAbout-Bf42ZGMD.js"),__vite__mapDeps([43,17]))),t5t=I.lazy(()=>Fe(()=>import("./LeadSiteLuxuryAbout-CtN-ploN.js"),__vite__mapDeps([44,45]))),r5t=I.lazy(()=>Fe(()=>import("./LeadSiteContact-BTbSHtTQ.js"),[])),n5t=I.lazy(()=>Fe(()=>import("./LeadSiteLuxuryContact-D7ODJ7tR.js"),[])),u6=I.lazy(()=>Fe(()=>import("./LeadSiteConsumerDashboard-CpfgZPfA.js"),[])),Xg=I.lazy(()=>Fe(()=>import("./LeadSiteBlog-Biq8Zf1k.js"),__vite__mapDeps([46,47]))),d6=I.lazy(()=>Fe(()=>import("./LeadSiteCommunity-BJi6lTOs.js"),__vite__mapDeps([48,40,6,49,50,51,52]))),i5t=I.lazy(()=>Fe(()=>import("./LeadSiteSellers-BqfVC3_Y.js"),__vite__mapDeps([53,45]))),s5t=I.lazy(()=>Fe(()=>import("./LeadSiteCityPage-DNuxh0LP.js"),__vite__mapDeps([54,55,32,20,15]))),a5t=I.lazy(()=>Fe(()=>import("./LeadSiteSubdivisionPage-FX58tvTX.js"),[])),h6=I.lazy(()=>Fe(()=>import("./LeadSiteCustomPage-GE-g-tVP.js"),[])),o5t=I.lazy(()=>Fe(()=>import("./LeadSiteFocusPage-D_YjiIO4.js"),__vite__mapDeps([56,51]))),l5t=I.lazy(()=>Fe(()=>import("./LeadSiteExpReady-Ca7s6PpP.js"),__vite__mapDeps([57,58,50,22]))),c5t=I.lazy(()=>Fe(()=>import("./LeadSiteConsultation-CH7OS3AZ.js"),[])),rue=I.lazy(()=>Fe(()=>import("./LeadSiteReviews-DB2rDFhu.js"),[])),u5t=I.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-DK9QCT--.js"),[]).then(t=>({default:t.LeadSiteExchangeListingsIndex}))),d5t=I.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-DK9QCT--.js"),[]).then(t=>({default:t.LeadSiteSoldListingsIndex}))),h5t=I.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-DK9QCT--.js"),[]).then(t=>({default:t.LeadSiteExchangeListingDetail}))),f5t=I.lazy(()=>Fe(()=>import("./OrgSiteLayout-CMVDchqm.js"),__vite__mapDeps([59,60]))),m5t=I.lazy(()=>Fe(()=>import("./OrgSiteHome-CB_HBL_G.js"),__vite__mapDeps([61,60]))),p5t=I.lazy(()=>Fe(()=>import("./OrgSiteAgents-D0tjvDNn.js"),__vite__mapDeps([62,60,61,63]))),g5t=I.lazy(()=>Fe(()=>import("./OrgSiteAgents-D0tjvDNn.js"),__vite__mapDeps([62,60,61,63])).then(t=>({default:t.OrgSiteAgentProfile}))),nue=I.lazy(()=>Fe(()=>import("./OrgSiteListings-YG8jUT2x.js"),__vite__mapDeps([64,60,61,63]))),y5t=I.lazy(()=>Fe(()=>import("./OrgSiteListings-YG8jUT2x.js"),__vite__mapDeps([64,60,61,63])).then(t=>({default:t.OrgSiteListingDetail}))),x5t=I.lazy(()=>Fe(()=>import("./OrgSitePages-YpUZTaHB.js"),__vite__mapDeps([63,60,61])).then(t=>({default:t.OrgSiteAbout}))),_5t=I.lazy(()=>Fe(()=>import("./OrgSitePages-YpUZTaHB.js"),__vite__mapDeps([63,60,61])).then(t=>({default:t.OrgSiteContact}))),v5t=I.lazy(()=>Fe(()=>import("./OrgSitePages-YpUZTaHB.js"),__vite__mapDeps([63,60,61])).then(t=>({default:t.OrgSiteJoin})));function TA(){return a.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function b5t({siteConfig:t}){const{data:e,isLoading:r}=GF(t.agentId);return r?a.jsx(TA,{}):a.jsx(li,{to:e!=null&&e.length?"/listings":"/contact?interest=Property%20search",replace:!0})}function w5t(){I.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 S5t(){var T,E,k;const{siteConfig:t,themeConfig:e,isLoading:r,error:n}=WPt();if(w5t(),r)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),a.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!t)return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:a.jsxs("div",{className:"text-center max-w-md",children:[a.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),a.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});if(((T=t.themeConfig)==null?void 0:T.orgPreset)==="remaxcreative"){const P=cLt;return a.jsxs(wR,{siteConfig:t,children:[a.jsx(FR,{}),a.jsx(I.Suspense,{fallback:a.jsx(TA,{}),children:a.jsx(XRt,{siteConfig:t,children:a.jsxs(l_,{children:[a.jsx(Te,{path:"/",element:a.jsx(eLt,{siteConfig:t})}),a.jsx(Te,{path:"/buy",element:a.jsx(iLt,{siteConfig:t})}),a.jsx(Te,{path:"/sell",element:a.jsx(sLt,{siteConfig:t})}),a.jsx(Te,{path:"/about",element:a.jsx(aLt,{siteConfig:t})}),a.jsx(Te,{path:"/agents",element:a.jsx(tLt,{siteConfig:t})}),a.jsx(Te,{path:"/team",element:a.jsx(li,{to:"/agents",replace:!0})}),a.jsx(Te,{path:"/offices",element:a.jsx(rLt,{siteConfig:t})}),a.jsx(Te,{path:"/join",element:a.jsx(oLt,{siteConfig:t})}),a.jsx(Te,{path:"/communities",element:a.jsx(nLt,{siteConfig:t})}),a.jsx(Te,{path:"/contact",element:a.jsx(lLt,{siteConfig:t})}),a.jsx(Te,{path:"/search",element:a.jsx(P,{children:a.jsx(BR,{siteConfig:t})})}),a.jsx(Te,{path:"/listing/:mlsNumber",element:a.jsx(P,{children:a.jsx(zR,{siteConfig:t})})}),a.jsx(Te,{path:"/dashboard",element:a.jsx(P,{children:a.jsx(u6,{siteConfig:t})})}),a.jsx(Te,{path:"/account",element:a.jsx(li,{to:"/dashboard",replace:!0})}),a.jsx(Te,{path:"/blog",element:a.jsx(P,{children:a.jsx(Xg,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/blog/:slug",element:a.jsx(P,{children:a.jsx(Xg,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/community",element:a.jsx(P,{children:a.jsx(d6,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/p/:pageSlug",element:a.jsx(P,{children:a.jsx(h6,{siteConfig:t})})}),a.jsx(Te,{path:"/*",element:a.jsx(P,{children:a.jsx($R,{siteConfig:t})})})]})})})]})}if(t.ownerType==="brokerage"&&((E=t.themeConfig)==null?void 0:E.orgPreset)==="btb")return a.jsxs(wR,{siteConfig:t,children:[a.jsx(FR,{}),a.jsx(I.Suspense,{fallback:a.jsx(TA,{}),children:a.jsx(ERt,{children:a.jsxs(l_,{children:[a.jsx(Te,{path:"/",element:a.jsx(jRt,{siteConfig:t})}),a.jsx(Te,{path:"/buy",element:a.jsx(CRt,{siteConfig:t})}),a.jsx(Te,{path:"/sell",element:a.jsx(IRt,{siteConfig:t})}),["/real-estate","/construction","/design","/work","/work/*"].map(P=>a.jsx(Te,{path:P,element:a.jsx(li,{to:P==="/real-estate"?"/buy":"/",replace:!0})},P)),a.jsx(Te,{path:"/about",element:a.jsx(NRt,{siteConfig:t})}),a.jsx(Te,{path:"/team",element:a.jsx(PRt,{siteConfig:t})}),a.jsx(Te,{path:"/agents",element:a.jsx(li,{to:"/team",replace:!0})}),a.jsx(Te,{path:"/join",element:a.jsx(RRt,{siteConfig:t})}),a.jsx(Te,{path:"/communities",element:a.jsx(LRt,{siteConfig:t})}),a.jsx(Te,{path:"/contact",element:a.jsx(DRt,{siteConfig:t})}),a.jsx(Te,{path:"/search",element:a.jsx(Kg,{children:a.jsx(BR,{siteConfig:t})})}),a.jsx(Te,{path:"/listing/:mlsNumber",element:a.jsx(Kg,{children:a.jsx(zR,{siteConfig:t})})}),a.jsx(Te,{path:"/dashboard",element:a.jsx(Kg,{children:a.jsx(u6,{siteConfig:t})})}),a.jsx(Te,{path:"/account",element:a.jsx(li,{to:"/dashboard",replace:!0})}),a.jsx(Te,{path:"/blog",element:a.jsx(Kg,{children:a.jsx(Xg,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/blog/:slug",element:a.jsx(Kg,{children:a.jsx(Xg,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/community",element:a.jsx(Kg,{children:a.jsx(d6,{siteConfig:t,isLuxury:!1})})}),a.jsx(Te,{path:"/p/:pageSlug",element:a.jsx(Kg,{children:a.jsx(h6,{siteConfig:t})})}),a.jsx(Te,{path:"/*",element:a.jsx(Kg,{children:a.jsx($R,{siteConfig:t})})})]})})})]});if(t.ownerType==="brokerage"||t.ownerType==="team"){const P=t.orgTier==="pro";return a.jsxs(wR,{siteConfig:t,children:[a.jsx(FR,{}),a.jsx(I.Suspense,{fallback:a.jsx(TA,{}),children:a.jsx(f5t,{siteConfig:t,themeConfig:e??void 0,children:a.jsxs(l_,{children:[a.jsx(Te,{path:"/",element:a.jsx(m5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/listings",element:a.jsx(nue,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/sold",element:a.jsx(nue,{siteConfig:t,themeConfig:e??void 0,sold:!0})}),a.jsx(Te,{path:"/listings/:slug",element:a.jsx(y5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/agents",element:a.jsx(p5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/agents/:slug",element:a.jsx(g5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/about",element:a.jsx(x5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/contact",element:a.jsx(_5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/join",element:a.jsx(v5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/blog",element:a.jsx(Xg,{siteConfig:t,isLuxury:!1})}),a.jsx(Te,{path:"/blog/:slug",element:a.jsx(Xg,{siteConfig:t,isLuxury:!1})}),a.jsx(Te,{path:"/search",element:P?a.jsx(BR,{siteConfig:t}):a.jsx(li,{to:"/listings",replace:!0})}),a.jsx(Te,{path:"/listing/:mlsNumber",element:P?a.jsx(zR,{siteConfig:t}):a.jsx(li,{to:"/listings",replace:!0})}),a.jsx(Te,{path:"/*",element:a.jsx($R,{siteConfig:t,referralMode:!P})})]})})})]})}const i=(e==null?void 0:e.themeTier)==="luxury",o=(e==null?void 0:e.themeTier)==="land-ranch",c=o?KFt:i?HFt:$Ft,s=b2e(t),f=s||ax(t,e),p=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",y=!s&&ax(t,e),_=o?a.jsx(XFt,{siteConfig:t,themeConfig:e??void 0}):i?a.jsx(ZFt,{siteConfig:t,themeConfig:e??void 0}):a.jsx(YFt,{siteConfig:t,themeConfig:e??void 0});return a.jsxs(wR,{siteConfig:t,children:[a.jsx(FR,{}),a.jsxs(c,{siteConfig:t,children:[a.jsx(I.Suspense,{fallback:a.jsx(TA,{}),children:a.jsxs(l_,{children:[a.jsx(Te,{path:"/",element:_}),a.jsx(Te,{path:"/listings",element:a.jsx(u5t,{siteConfig:t})}),a.jsx(Te,{path:"/sold",element:a.jsx(d5t,{siteConfig:t})}),a.jsx(Te,{path:"/listings/:slug",element:a.jsx(h5t,{siteConfig:t})}),a.jsx(Te,{path:"/search",element:f?a.jsx(b5t,{siteConfig:t}):i?a.jsx(QFt,{siteConfig:t}):a.jsx(BR,{siteConfig:t})}),a.jsx(Te,{path:"/listing/:mlsNumber",element:f?a.jsx(li,{to:"/contact?interest=Property%20details",replace:!0}):i?a.jsx(JFt,{siteConfig:t}):a.jsx(zR,{siteConfig:t})}),a.jsx(Te,{path:"/about",element:i?a.jsx(t5t,{siteConfig:t}):a.jsx(e5t,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/contact",element:i?a.jsx(n5t,{siteConfig:t}):a.jsx(r5t,{siteConfig:t})}),a.jsx(Te,{path:"/account",element:a.jsx(u6,{siteConfig:t})}),a.jsx(Te,{path:"/blog",element:a.jsx(Xg,{siteConfig:t,isLuxury:i})}),a.jsx(Te,{path:"/blog/:slug",element:a.jsx(Xg,{siteConfig:t,isLuxury:i})}),a.jsx(Te,{path:"/sell",element:a.jsx(i5t,{siteConfig:t,themeConfig:e??void 0,isLuxury:i})}),a.jsx(Te,{path:"/community",element:a.jsx(d6,{siteConfig:t,isLuxury:i})}),a.jsx(Te,{path:"/schedule",element:t.id===nRt?a.jsx(c5t,{siteConfig:t}):a.jsx(rRt,{bookingUrl:t.bookingUrl,agentName:((k=t.agent)==null?void 0:k.full_name)||"your agent"})}),uje(t)&&a.jsx(Te,{path:"/exp-ready",element:a.jsx(l5t,{siteConfig:t})}),((e==null?void 0:e.focusPages)??[]).map(P=>a.jsx(Te,{path:`/${P.slug}`,element:a.jsx(o5t,{siteConfig:t,page:P,accentColor:(e==null?void 0:e.accentColor)||t.accentColor||"#c9a96e"})},P.slug)),a.jsx(Te,{path:"/reviews",element:a.jsx(rue,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/reviews/:slug",element:a.jsx(rue,{siteConfig:t,themeConfig:e??void 0})}),a.jsx(Te,{path:"/p/:pageSlug",element:a.jsx(h6,{siteConfig:t})}),a.jsx(Te,{path:"/*",element:a.jsx($R,{siteConfig:t,referralMode:y})})]})}),!p&&a.jsx(tRt,{bookingUrl:t.bookingUrl})]})]})}function $R({siteConfig:t,referralMode:e}){const r=Bi(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return a.jsx(a5t,{siteConfig:t,subdivisionSlug:n[1]});const i=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);if(i)return a.jsx(s5t,{siteConfig:t,citySlugOverride:i[1],referralMode:e});const o=r.pathname.match(/^\/communities\/([^/]+)\/?$/);if(o)return a.jsx(li,{to:`/homes-for-sale-in-${o[1]}${r.search}`,replace:!0});const c=r.pathname.match(/^\/([a-z0-9][a-z0-9-]*)\/?$/i);return c?a.jsx(T5t,{siteId:t==null?void 0:t.id,slug:c[1],search:r.search}):null}function T5t({siteId:t,slug:e,search:r}){const[n,i]=I.useState(null);return I.useEffect(()=>{let o=!1;if(!t){i(!1);return}return Re.from("lead_site_pages").select("id").eq("site_id",t).eq("slug",e).eq("is_published",!0).maybeSingle().then(({data:c})=>{o||i(!!c)}),()=>{o=!0}},[t,e]),n?a.jsx(li,{to:`/p/${e}${r}`,replace:!0}):null}function E5t(){const{user:t,loading:e}=Gn(),{data:r,isLoading:n}=gr({queryKey:["feature-entitlement","levelup_attract",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:o}=await Re.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key","levelup_attract").maybeSingle();if(o)throw o;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 A5t({children:t}){const{user:e,loading:r}=Gn(),{hasAccess:n,isLoading:i}=E5t(),o=Bi();return I.useEffect(()=>{!r&&!i&&e&&!n&&Gt.error("LevelUp Attract isn't available for your account yet.")},[r,i,e,n]),r||e&&i?a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?a.jsx(a.Fragment,{children:t}):a.jsx(li,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",o.pathname),a.jsx(li,{to:"/auth",replace:!0}))}function iue({children:t}){const{user:e,loading:r}=Gn(),{hasAccess:n,isLoading:i}=t7(),o=Bi();return r||e&&i?a.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?a.jsx(a.Fragment,{children:t}):a.jsx(li,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",o.pathname),a.jsx(li,{to:"/auth",replace:!0}))}const j5t=I.lazy(()=>Fe(()=>import("./CommercialMarketplace-CQzNtviw.js"),[])),sue=I.lazy(()=>Fe(()=>import("./PrivacyPolicy-CyUJl3yb.js"),[])),k5t=I.lazy(()=>Fe(()=>import("./CanvaSupport-pXnYyLld.js"),__vite__mapDeps([65,66]))),aue=I.lazy(()=>Fe(()=>import("./TermsOfService-fmjrBF6Z.js"),[])),C5t=I.lazy(()=>Fe(()=>import("./DataDeletion-DhsM2chW.js"),[])),oue=I.lazy(()=>Fe(()=>import("./McpDataUse-D27m-M8x.js"),[])),I5t=I.lazy(()=>Fe(()=>import("./SmsOptIn-BNwuFIzm.js"),__vite__mapDeps([67,68]))),f6=I.lazy(()=>Fe(()=>import("./OAuthConsent-CtjH-Xu3.js"),[])),N5t=I.lazy(()=>Fe(()=>import("./ConnectChatGPT-DuhVplw_.js"),__vite__mapDeps([69,70]))),lue=I.lazy(()=>Fe(()=>import("./LevelUpMCP-ECrlluhT.js"),[])),P5t=I.lazy(()=>Fe(()=>import("./SubscriptionSuccess-InG6Ryt1.js"),__vite__mapDeps([71,70]))),R5t=I.lazy(()=>Fe(()=>import("./Subscription-DzrNUmWa.js"),[])),L5t=I.lazy(()=>Fe(()=>import("./SetupBrokerage-C8Gj6lOm.js"),__vite__mapDeps([72,70]))),cue=I.lazy(()=>Fe(()=>import("./ClaimAccount-BJ-KmF-P.js"),[])),uue=I.lazy(()=>Fe(()=>import("./ConfirmPasswordReset-BAse-Jr6.js"),[])),D5t=I.lazy(()=>Fe(()=>import("./ActivateAccount-BsMZJ3Kf.js"),[])),M5t=I.lazy(()=>Fe(()=>import("./InviteSignup-OIPxll0j.js"),__vite__mapDeps([73,74]))),O5t=I.lazy(()=>Fe(()=>import("./CoachingHub-jC6TasGZ.js"),__vite__mapDeps([75,76]))),F5t=I.lazy(()=>Fe(()=>import("./CoachAgentWorkspace-oCGykJGe.js"),__vite__mapDeps([77,76,78,79,80]))),B5t=I.lazy(()=>Fe(()=>import("./MyCoach-BkUdeN6I.js"),__vite__mapDeps([81,76,78,82,83,79]))),z5t=I.lazy(()=>Fe(()=>import("./AdminCoaching-COO_pamw.js"),__vite__mapDeps([84,85,86,5,87]))),$5t=I.lazy(()=>Fe(()=>import("./CoachBilling-BOZwIQI3.js"),__vite__mapDeps([88,76,89]))),U5t=I.lazy(()=>Fe(()=>import("./CoachSettings-Bcfh1llz.js"),__vite__mapDeps([90,76,91,92,93,66,80,94]))),V5t=I.lazy(()=>Fe(()=>import("./GoogleCalendarReturn-BaYdza1s.js"),[])),q5t=I.lazy(()=>Fe(()=>import("./Microsoft365Return-CtGATC0B.js"),__vite__mapDeps([95,96,97]))),G5t=I.lazy(()=>Fe(()=>import("./CoachWaitlist-CaGYTdRF.js"),__vite__mapDeps([98,76,99]))),H5t=I.lazy(()=>Fe(()=>import("./CoachesDirectory-Ci2SioNZ.js"),[])),W5t=I.lazy(()=>Fe(()=>import("./CoachProfile-CE8guHnf.js"),__vite__mapDeps([100,82]))),K5t=I.lazy(()=>Fe(()=>import("./CoachApply-DTfQlC4s.js"),[])),Y5t=I.lazy(()=>Fe(()=>import("./Trial-BQFHSe7h.js"),__vite__mapDeps([101,102]))),Z5t=I.lazy(()=>Fe(()=>import("./TrialSuccess-B4C4bU3c.js"),__vite__mapDeps([103,104]))),X5t=I.lazy(()=>Fe(()=>import("./LaborDaySale-D7NOd0ls.js"),__vite__mapDeps([105,106,102,107,108]))),Q5t=I.lazy(()=>Fe(()=>import("./BrokerageLaborDaySale-Bp6Q6CNy.js"),__vite__mapDeps([109,106,102,107,108]))),J5t=I.lazy(()=>Fe(()=>import("./BrokerageSolutions-BwHUgJcV.js"),__vite__mapDeps([110,107,111,112,113,108]))),e4t=I.lazy(()=>Fe(()=>import("./Upgrade-CFfDAWyh.js"),__vite__mapDeps([114,115]))),t4t=I.lazy(()=>Fe(()=>import("./InstagramGift-D53xlWYV.js"),__vite__mapDeps([116,115,89]))),due=I.lazy(()=>Fe(()=>import("./VideoShare-sso_ILMR.js"),__vite__mapDeps([117,118,119,120,26,39,104,6,121,122,123]))),r4t=I.lazy(()=>Fe(()=>import("./VideoShareLayout-Bm6MfYQ1.js"),[])),n4t=I.lazy(()=>Fe(()=>import("./VideoOgRedirect-225Ujjp5.js"),[])),i4t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>AZe),void 0)),s4t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>vZe),void 0)),a4t=I.lazy(()=>Fe(()=>import("./NewListingChooser-DMGGRL5J.js"),[])),hue=I.lazy(()=>Fe(()=>import("./CommercialWizard-C2DIXnrh.js"),__vite__mapDeps([124,125,126]))),o4t=I.lazy(()=>Fe(()=>import("./CommercialWorkspace-Ck9kLo1D.js"),__vite__mapDeps([127,125,126,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,96,97,146,83,80,147,148]))),l4t=I.lazy(()=>Fe(()=>import("./CommercialPitchPreview-DF5yfQV9.js"),__vite__mapDeps([149,148]))),c4t=I.lazy(()=>Fe(()=>import("./PrivateListingView-BgdRUfY-.js"),[])),u4t=I.lazy(()=>Fe(()=>import("./PublicAgentCard-LERczoBM.js"),[])),d4t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>TPt),void 0)),fue=I.lazy(()=>Fe(()=>import("./PublicHomeValue-Jyz-AuXT.js"),[])),h4t=I.lazy(()=>Fe(()=>import("./PublicLiveEvent-DgzweO-s.js"),__vite__mapDeps([150,151,152,153,154]))),f4t=I.lazy(()=>Fe(()=>import("./LiveEvents-BJa6rWJQ.js"),__vite__mapDeps([155,156,157,158,146]))),m4t=I.lazy(()=>Fe(()=>import("./LiveEventConsole-iPcks758.js"),__vite__mapDeps([159,157,153,74,160,151,161]))),p4t=I.lazy(()=>Fe(()=>import("./Dashboard-tgdoy-RT.js"),__vite__mapDeps([162,163,164,76,165,166,167,168,169,170,125,126,171,172,173,174,3,39,79,175]))),g4t=I.lazy(()=>Fe(()=>import("./Profile-B8uxWCqa.js"),__vite__mapDeps([176,94,79,89,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,80,192,193,194,195,30,111,9,196]))),y4t=I.lazy(()=>Fe(()=>import("./Events-N2S_ogAg.js"),__vite__mapDeps([197,165,166,167,198,172,199,200,201]))),x4t=I.lazy(()=>Fe(()=>import("./EventDetail-CeaxAYo3.js"),__vite__mapDeps([202,165,166,167,203,204,70]))),_4t=I.lazy(()=>Fe(()=>import("./Apps-B6oEFeaD.js"),__vite__mapDeps([205,121,89,206,5,207]))),v4t=I.lazy(()=>Fe(()=>import("./Templates-C1Drzs_J.js"),__vite__mapDeps([208,94]))),b4t=I.lazy(()=>Fe(()=>import("./TemplateDetail-Ao6m_-NU.js"),__vite__mapDeps([209,137,163,203,204,94]))),w4t=I.lazy(()=>Fe(()=>import("./Programs-tJPe0uNg.js"),__vite__mapDeps([210,164]))),S4t=I.lazy(()=>Fe(()=>import("./ProgramDetail-Bl-sRSdb.js"),__vite__mapDeps([211,212,213,164,30,89]))),T4t=I.lazy(()=>Fe(()=>import("./ProgramEnroll-D5xhLmwp.js"),__vite__mapDeps([214,164,215,89]))),E4t=I.lazy(()=>Fe(()=>import("./ProgramWorkspace-BwSXmOOx.js"),__vite__mapDeps([216,164,217,218]))),A4t=I.lazy(()=>Fe(()=>import("./Programs-BMuJQCo3.js"),__vite__mapDeps([219,164,80,158,215,220,89,206,133,221,213,83,30]))),j4t=I.lazy(()=>Fe(()=>import("./Academy-C4aaYgP5.js"),[])),k4t=I.lazy(()=>Fe(()=>import("./AcademyVideoDetail-DWtd9cxQ.js"),__vite__mapDeps([222,137,163,203,204,223]))),C4t=I.lazy(()=>Fe(()=>import("./PublicAcademyWatch-8FQ3HvM0.js"),[])),I4t=I.lazy(()=>Fe(()=>import("./Toolbox-zcki-5iH.js"),[])),N4t=I.lazy(()=>Fe(()=>import("./ToolboxDetail-kMJjpJvG.js"),__vite__mapDeps([224,137,163,203,204,223]))),P4t=I.lazy(()=>Fe(()=>import("./SocialSwag-BzKKBrJv.js"),__vite__mapDeps([225,94]))),R4t=I.lazy(()=>Fe(()=>import("./SocialStudio-DmRfj0Jk.js"),__vite__mapDeps([226,137,227,228,31,229,230,231,232,126,233,191,234,218,235,236,237,238,66,158,239,240,241,242,80,243,166,83,70,244,129,130]))),L4t=I.lazy(()=>Fe(()=>import("./MarketingStudio-Qg9R0309.js"),__vite__mapDeps([245,39,246]))),D4t=I.lazy(()=>Fe(()=>import("./BrandKit-DMR7tLtc.js"),__vite__mapDeps([247,248]))),M4t=I.lazy(()=>Fe(()=>import("./BrandingBarEditor-CCKmnADb.js"),__vite__mapDeps([249,244,248,250,251]))),O4t=I.lazy(()=>Fe(()=>import("./ListingTemplates-D8iIXCOD.js"),__vite__mapDeps([252,253,254,248,215,5]))),F4t=I.lazy(()=>Fe(()=>import("./PersonalBranding-CrJlSD9S.js"),__vite__mapDeps([255,256,248,253]))),B4t=I.lazy(()=>Fe(()=>import("./SocialSwagDetail-BUElcx82.js"),__vite__mapDeps([257,137,163,203,204,94]))),z4t=I.lazy(()=>Fe(()=>import("./Community-BREF_PaX.js"),__vite__mapDeps([258,31,221,213,12,188,259,260,94,261,151]))),$4t=I.lazy(()=>Fe(()=>import("./Support-DrpNetRl.js"),__vite__mapDeps([262,137,263,264,175,146,70,83]))),U4t=I.lazy(()=>Fe(()=>import("./BrokerageResources-C73tsD-7.js"),__vite__mapDeps([265,94]))),V4t=I.lazy(()=>Fe(()=>import("./BrokerageResourceDetail-BDk55bsV.js"),[])),mue=I.lazy(()=>Fe(()=>import("./AdminDashboard-C1bu7dvH.js"),__vite__mapDeps([266,89,267,215,268,269,270]))),q4t=I.lazy(()=>Fe(()=>import("./Apps-BDfjZdnj.js"),[])),G4t=I.lazy(()=>Fe(()=>import("./MemberManagement-CMxdxeC8.js"),__vite__mapDeps([271,156,272,217,104,273,152,274,89,275,276,277,278,279,280,201,281,5,282,283,79,284,86,285,115]))),H4t=I.lazy(()=>Fe(()=>import("./UnassignedMembers-WF2ZfT4d.js"),__vite__mapDeps([286,156]))),W4t=I.lazy(()=>Fe(()=>import("./InviteCodes-CTWw6ivF.js"),__vite__mapDeps([287,156]))),K4t=I.lazy(()=>Fe(()=>import("./Events-C4u38cbD.js"),__vite__mapDeps([288,177,178,179,180,181,182,183,184,185,186,94,157,289,156,290]))),Y4t=I.lazy(()=>Fe(()=>import("./MCPAuditLog-adI1JNiK.js"),__vite__mapDeps([291,156,292]))),Z4t=I.lazy(()=>Fe(()=>import("./Templates-q3ap7P9w.js"),__vite__mapDeps([293,156,177,178,179,180,181,182,183,184,185,186,94,289]))),X4t=I.lazy(()=>Fe(()=>import("./Academy-CnpVDLuV.js"),__vite__mapDeps([294,156,177,178,179,180,181,182,183,184,185,186,94,295,218,289]))),Q4t=I.lazy(()=>Fe(()=>import("./Toolbox-BofQGCF0.js"),__vite__mapDeps([296,177,178,179,180,181,182,183,184,185,186,94,295,218,289]))),J4t=I.lazy(()=>Fe(()=>import("./SocialSwag-CDpVwIhY.js"),__vite__mapDeps([297,156,177,178,179,180,181,182,183,184,185,186,94,289]))),eBt=I.lazy(()=>Fe(()=>import("./SocialSwag2-DuH99XnS.js"),__vite__mapDeps([298,289,132,94,133]))),tBt=I.lazy(()=>Fe(()=>import("./Community-C1Hk1bx5.js"),__vite__mapDeps([299,156]))),rBt=I.lazy(()=>Fe(()=>import("./Analytics-Bv0N1J4w.js"),__vite__mapDeps([300,273,152,274,70,301,302,303,304,305]))),nBt=I.lazy(()=>Fe(()=>import("./BrokerageResources-UuD8aRQG.js"),__vite__mapDeps([306,177,178,179,180,181,182,183,184,185,186,94,215]))),iBt=I.lazy(()=>Fe(()=>import("./DashboardManagement-AW02Y8xn.js"),__vite__mapDeps([307,133,160,74]))),sBt=I.lazy(()=>Fe(()=>import("./SupportTickets-C15UxvKV.js"),__vite__mapDeps([308,137,263,264,175,146,9,70,83]))),aBt=I.lazy(()=>Fe(()=>import("./EmailTemplates-DVAiNG7R.js"),__vite__mapDeps([309,178,179,310,183,184,185,186,94,311,312,80,313]))),oBt=I.lazy(()=>Fe(()=>import("./AgentEmailTemplates-Du8PHG2w.js"),__vite__mapDeps([314,156,79]))),lBt=I.lazy(()=>Fe(()=>import("./BrokerageDashboard-DomdwKvc.js"),__vite__mapDeps([315,272,217,104,152,274,70,94,83,275,283,284,301,273,198,172,199,316]))),cBt=I.lazy(()=>Fe(()=>import("./MyBrokerage-XRpgm56k.js"),__vite__mapDeps([317,151,115,199,191,80,318,319,83,5]))),uBt=I.lazy(()=>Fe(()=>import("./BrokerageContent-ClYbAV_J.js"),__vite__mapDeps([320,170,79]))),dBt=I.lazy(()=>Fe(()=>import("./BrokerageContentDetail-QfpgWQwQ.js"),[])),hBt=I.lazy(()=>Fe(()=>import("./BrokerageHelpBoard-CcG0YtKi.js"),__vite__mapDeps([321,322,9]))),fBt=I.lazy(()=>Fe(()=>import("./BrokerageHelpBoardNew-CPUAzWXQ.js"),__vite__mapDeps([323,322]))),mBt=I.lazy(()=>Fe(()=>import("./BrokerageHelpBoardDetail-B-Bd1WNl.js"),__vite__mapDeps([324,322,12]))),pBt=I.lazy(()=>Fe(()=>import("./Newsletters-hD9bJsMS.js"),__vite__mapDeps([325,326,256,327,183,328,184,94,160,313,152,274,329,330,80,331,113,332,5,168,139,140,141,142,333,334,292,335,215,336,74]))),gBt=I.lazy(()=>Fe(()=>import("./NewsletterDetail-D9kDFFFv.js"),__vite__mapDeps([337,163,203,204,331,326,256,327,183,328,184,94,160,313,152,274,329,113,332,5,168,139,140,141,142,333,334,292,335,215,336,74]))),yBt=I.lazy(()=>Fe(()=>import("./Newsletters-s4du9FHV.js"),__vite__mapDeps([338,289,156,177,178,179,180,181,182,183,184,185,186,94,327,133,339]))),xBt=I.lazy(()=>Fe(()=>import("./MemberBroadcasts-DEvnNnKh.js"),__vite__mapDeps([340,156,177,178,179,180,181,182,183,184,185,186,94,218,201,311,341,80]))),_Bt=I.lazy(()=>Fe(()=>import("./BoostAnnouncements-Bs4Y7aEY.js"),__vite__mapDeps([342,156,7]))),vBt=I.lazy(()=>Fe(()=>import("./NewsletterGraphics-CQpoKoF7.js"),__vite__mapDeps([343,156,158]))),bBt=I.lazy(()=>Fe(()=>import("./Wishlist-CMJYnnQ6.js"),__vite__mapDeps([344,152]))),wBt=I.lazy(()=>Fe(()=>import("./WishlistDetail-y_y3p71o.js"),__vite__mapDeps([345,259,152]))),SBt=I.lazy(()=>Fe(()=>import("./Wishlist-B4cJLqWI.js"),[])),TBt=I.lazy(()=>Fe(()=>import("./LevelUpBrief-Bo-XmGxM.js"),__vite__mapDeps([346,156,177,178,179,180,181,182,183,184,185,186,94]))),EBt=I.lazy(()=>Fe(()=>import("./AdditionalServices-BlpsT24i.js"),__vite__mapDeps([347,177,178,179,180,181,182,183,184,185,186,94]))),ABt=I.lazy(()=>Fe(()=>import("./Discounts-DAxqDjQ_.js"),__vite__mapDeps([348,156]))),jBt=I.lazy(()=>Fe(()=>import("./Subscriptions-deZ-VfVG.js"),__vite__mapDeps([349,156,350,89,284]))),kBt=I.lazy(()=>Fe(()=>import("./InstagramGiftEmails-B28KksEN.js"),__vite__mapDeps([351,350,313]))),CBt=I.lazy(()=>Fe(()=>import("./Referrals-DRWIKPNn.js"),__vite__mapDeps([352,156,70,83]))),IBt=I.lazy(()=>Fe(()=>import("./OnboardingChecklist-BTyimF-N.js"),[])),NBt=I.lazy(()=>Fe(()=>import("./AgentOSControlCenter-DQXIlqcl.js"),__vite__mapDeps([353,156,121,119,133]))),PBt=I.lazy(()=>Fe(()=>import("./AdditionalServices-BSiMv-qk.js"),[])),RBt=I.lazy(()=>Fe(()=>import("./AdditionalServiceDetail-DukA8TAR.js"),[])),LBt=I.lazy(()=>Fe(()=>import("./AIToolkit-Cre-IfRO.js"),[])),DBt=I.lazy(()=>Fe(()=>import("./AskAI-DWYU8Ld3.js"),__vite__mapDeps([354,2,5]))),MBt=I.lazy(()=>Fe(()=>import("./InnerCircleHome-8S_36Ps5.js"),__vite__mapDeps([355,173,174,356,8,152,274,284,357,168,138,137,139,140,141,142,143,144,145,96,97,146,358,359,360,361,362,363,160]))),OBt=I.lazy(()=>Fe(()=>import("./InnerCircleContacts-5BGCEHUu.js"),__vite__mapDeps([364,365,221,213,366,256,152,274,367,368,278,275,279,280,201,281,5,282,356,369,370,8,371,333,215,229,372,174,373,217,374,359,137,375,376,377,378,379,380,234,335,381,313,382,383,384,119,195,94,139,138,140,141,142,143,144,145,96,97,146,168,334,341,385,386,387,388,389,39,390,196,9,80,125,126,74,391,184]))),FBt=I.lazy(()=>Fe(()=>import("./InnerCircleContactDetail-DoW3kQUC.js"),__vite__mapDeps([392,393,394,389,137,365,168,139,138,140,141,142,143,144,145,96,97,146,395,384,370,174,333,369,356,8,371,215,229,372,396,284,390,9,80,196,388,397,398,221,213,399,400,201,270,401,402,267,292,358,359,360,361]))),BBt=I.lazy(()=>Fe(()=>import("./SentEmails-Ca_Dc-tA.js"),__vite__mapDeps([403,168,138,137,139,140,141,142,143,144,145,96,97,146,398,189,160,196,83,372]))),zBt=I.lazy(()=>Fe(()=>import("./InnerCirclePlans-DPVtimWy.js"),__vite__mapDeps([404,70,405,80,284,357]))),$Bt=I.lazy(()=>Fe(()=>import("./CMAList-CTZHdRbj.js"),__vite__mapDeps([406,395,407,140,408]))),UBt=I.lazy(()=>Fe(()=>import("./CMABuilder-CiY9ZNZh.js"),__vite__mapDeps([409,395,407,140,382,410,161,411,412,413,414,313,5,8,80]))),VBt=I.lazy(()=>Fe(()=>import("./ListingPresentations-Dh3ghvE3.js"),__vite__mapDeps([415,416,417,129,418]))),qBt=I.lazy(()=>Fe(()=>import("./ListingPresentationBuilder-Cv9bl_fA.js"),__vite__mapDeps([419,137,212,213,420,421,129,416,417,422,158,5,218,152,274,418,80,341,423]))),GBt=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>wnt),void 0)),HBt=I.lazy(()=>Fe(()=>import("./InnerCirclePopbys-CBXw4bvU.js"),__vite__mapDeps([424,365,370,425,426,70]))),WBt=I.lazy(()=>Fe(()=>import("./ListingExchange-C4qimD-M.js"),__vite__mapDeps([427,125,126,428,121,134,52,429,333,386,387,385,141,142,215,199,430,400]))),KBt=I.lazy(()=>Fe(()=>import("./ListingDetail-BhP9AiO-.js"),__vite__mapDeps([431,128,125,126,129,130,430,134,428,121,135,136,137,138,139,140,141,142,143,144,145,96,97,146,229,9,52,148]))),pue=I.lazy(()=>Fe(()=>import("./ListingForm-qJglCrSt.js"),__vite__mapDeps([432,132,125,126,131,133,384,339,128,129,130,74]))),YBt=I.lazy(()=>Fe(()=>import("./CustomizeListingPage-Cpe6rj3Q.js"),__vite__mapDeps([433,313,80,303,434,94,133])));function ZBt(){const{search:t}=Bi();return a.jsx(li,{to:`/video-studio${t}`,replace:!0})}const XBt=I.lazy(()=>Fe(()=>import("./VideoStudio-CBfBIpsJ.js"),__vite__mapDeps([435,436,332,230,231,384,437,118,119,120,26,39,104,6,121,122,123,221,213,145,96,97,137,375,168,94,191,238,66,158,438,439,269,440,86,115,441,151,282,414,442,443,444,445,412,161,281,446,447,448,449,52,8,411,74,313,339,450,80,5,235,451,234,148]))),gue=I.lazy(()=>Fe(()=>import("./MainStageGate-CR9rl-Xn.js"),__vite__mapDeps([452,453,439,438,200,443,414,442,454,79,455,282,456,441,235,390,115]))),QBt=I.lazy(()=>Fe(()=>import("./MainStageAdmin-DJ9H0iPH.js"),__vite__mapDeps([457,453,313,439,80,158]))),JBt=I.lazy(()=>Fe(()=>import("./StudioKitsAdmin-C3Yy0-b6.js"),__vite__mapDeps([458,230,231,444,80]))),ezt=I.lazy(()=>Fe(()=>import("./StudioGuestJoin-BKN45m-y.js"),__vite__mapDeps([459,445,230,231,412,161,281,443,449,442,454,414,451]))),tzt=I.lazy(()=>Fe(()=>import("./VideoLibrary-Dn_AzY2F.js"),__vite__mapDeps([460,384,383,437,118,119,120,26,39,104,6,121,122,123,221,213,145,96,97,137,375,168,94,302,238,66,158,461,462,311]))),rzt=I.lazy(()=>Fe(()=>import("./DealPipeline-CC27PGAe.js"),__vite__mapDeps([463,464,112,186,185,465,401,436,466,467,274,85,279,152,468,469,161,470,9,30,49,183,341,434,381,471,122,400,285,92,472,37,473,474,475,58,305,70,476,83,449,477,478,479,120,335,311,123,267,368,283,480,89,284,270,121,281,241,455,36,74,481,482,483,175,484,147,217,485,264,119,269,411,79,486,487,488,489,133,490,282,462,12,181,182,491,492,201,493,233,158,447,87,107,372,494,218,339,94,336,184,495,362,425,496,115,99,363,497,498,196,391,13,199,499,500,246,501,502,442,414,456,206,413,313,27,503,160,302,504,423,231,52,426,505,448,303,146,104,8,357,405,113,454,261,151,51,506,507,508,148,111,509,367,290,260,5,189,220,80,450,510,235,292,511,512,268,513,68,207,39,154,388,361,280,6,451,514,215,461,515,38,516,26,50,22,441,517,234,328,332,229,66,204,86,518,519,195,390,520,312,40,108,188,371,125,126,396,521,221,213,522,523,524,525,382,526,410,412,384,168,527,212,393,528,529,530,531]))),nzt=I.lazy(()=>Fe(()=>import("./FormsLibrary-CW5oKrma.js"),__vite__mapDeps([532,524,533,80,421,503,381,234,515,523,481,152,274,455,401,484]))),izt=I.lazy(()=>Fe(()=>import("./TransactionCoordinator-DLGy9RXf.js"),__vite__mapDeps([534,527,212,213,290]))),szt=I.lazy(()=>Fe(()=>import("./PortalReferrals-DlYEx_d9.js"),__vite__mapDeps([535,536]))),azt=I.lazy(()=>Fe(()=>import("./AgentVendors-80FLyR_4.js"),__vite__mapDeps([537,538,74]))),ozt=I.lazy(()=>Fe(()=>import("./BrokerageForms-n5vl1iaa.js"),__vite__mapDeps([539,524,533,80,421,503,381,234,515,486,487,401]))),lzt=I.lazy(()=>Fe(()=>import("./BrokerageVendors-BTPMnC9v.js"),__vite__mapDeps([540,538,74]))),czt=I.lazy(()=>Fe(()=>import("./ClientPortalsHub-DJgmEVGW.js"),__vite__mapDeps([541,530,80,396,525,133,229,382,526,410,161,411,412,413,414,313,5,8,384,94,9,168,465,500,401,542,537,538,74,535,536,108]))),uzt=I.lazy(()=>Fe(()=>import("./ClientPortalDetail-iNnxEFY-.js"),__vite__mapDeps([543,396,536,525,133,229,382,526,410,161,411,412,413,414,313,5,8,384,94,80,9,168,542,500,465,401]))),dzt=I.lazy(()=>Fe(()=>import("./MyCardEditor-PhaaA2FA.js"),__vite__mapDeps([544,187,188,189,190,545,215,133,152,274,74,246,136,313,89,148,160]))),hzt=I.lazy(()=>Fe(()=>import("./Integrations-CTjGJJmx.js"),__vite__mapDeps([546,221,213,366,256,152,274,70,461,547,97,548,137,329,80,228,31,238,66,158,549,96,231,520,235]))),fzt=I.lazy(()=>Fe(()=>import("./BrowserExtension-CzdzFWq-.js"),__vite__mapDeps([550,305]))),mzt=I.lazy(()=>Fe(()=>import("./IntegrationsGmailCallback-1ObFkgk0.js"),__vite__mapDeps([551,70,83]))),pzt=I.lazy(()=>Fe(()=>import("./IntegrationsCanvaCallback-qi0nsCRJ.js"),[])),gzt=I.lazy(()=>Fe(()=>import("./IntegrationsMetaCallback-COkQJi3U.js"),__vite__mapDeps([552,70,83]))),yzt=I.lazy(()=>Fe(()=>import("./ScorecardAdmin-DIOLJqs2.js"),[])),xzt=I.lazy(()=>Fe(()=>import("./AgentActivation-D-ekz1VT.js"),__vite__mapDeps([553,156,99,390]))),yue=I.lazy(()=>Fe(()=>import("./ScorecardAgentView-D0mB0dNX.js"),[])),_zt=I.lazy(()=>Fe(()=>import("./ListingExchange-DLeKdzSX.js"),[])),vzt=I.lazy(()=>Fe(()=>import("./ListingLeads-D9vcUVgM.js"),[])),bzt=I.lazy(()=>Fe(()=>import("./PublicSiteLeads-BHDBMLt1.js"),[])),wzt=I.lazy(()=>Fe(()=>import("./MembershipReviews-DE4wWt0v.js"),__vite__mapDeps([554,156]))),Szt=I.lazy(()=>Fe(()=>import("./LeadNotifications-DRiLYpz3.js"),__vite__mapDeps([555,156]))),Tzt=I.lazy(()=>Fe(()=>import("./WeeklyDigest-DMDpAu5x.js"),__vite__mapDeps([556,83]))),Ezt=I.lazy(()=>Fe(()=>import("./AgentPoints-BxUtwwVU.js"),__vite__mapDeps([557,201]))),Azt=I.lazy(()=>Fe(()=>import("./AgentCards-Ber6IDUs.js"),__vite__mapDeps([558,187,188,189,190,545,215,133,152,274,74,246,514]))),jzt=I.lazy(()=>Fe(()=>import("./Marketplace-BUEYX6-n.js"),__vite__mapDeps([559,158,215,79]))),kzt=I.lazy(()=>Fe(()=>import("./RewardStore-iRtpUJ3l.js"),__vite__mapDeps([560,561,79,94,80]))),Czt=I.lazy(()=>Fe(()=>import("./Integrations-CryLvWSe.js"),__vite__mapDeps([562,156,228,31,227,229,269,547,97,70]))),Izt=I.lazy(()=>Fe(()=>import("./SocialConnections-BG-rHpJL.js"),__vite__mapDeps([563,156]))),Nzt=I.lazy(()=>Fe(()=>import("./SocialAutopilot-CRNynGSx.js"),__vite__mapDeps([564,156,230,231,232,80]))),Pzt=I.lazy(()=>Fe(()=>import("./McpUpdates-D06ziFoY.js"),__vite__mapDeps([565,156]))),Rzt=I.lazy(()=>Fe(()=>import("./RefreshMcpTools-FYMC3ayo.js"),[])),Lzt=I.lazy(()=>Fe(()=>import("./NotificationSettings-CR4HTBhq.js"),__vite__mapDeps([566,156]))),Dzt=I.lazy(()=>Fe(()=>import("./PresentationAnalytics-LMLAAUOv.js"),__vite__mapDeps([567,273,152,274,160]))),Mzt=I.lazy(()=>Fe(()=>import("./ListingPresentationStudioAdmin-DSgWSsr_.js"),__vite__mapDeps([568,156]))),Ozt=I.lazy(()=>Fe(()=>import("./ListingRevivalAdmin-MTNfIl_0.js"),__vite__mapDeps([569,156,570]))),Fzt=I.lazy(()=>Fe(()=>import("./GuestBookAnalytics-CCb74CX9.js"),__vite__mapDeps([571,70]))),Bzt=I.lazy(()=>Fe(()=>import("./IntegrationsCallback-Dtc4Vzh5.js"),__vite__mapDeps([572,70,83]))),zzt=I.lazy(()=>Fe(()=>import("./Prospector-BEBJanGB.js"),[])),$zt=I.lazy(()=>Fe(()=>import("./AdminRecruiting-37gqPIG8.js"),__vite__mapDeps([573,574,133,137,410,161,411,412,413,414,313,5,8,384,80,302,217,152,274,83,483,87,339,167,221,213,548,97,178,179,310,575,183,328,475,181,182,491,184,185,186,94,312,160,497,12,39,6,141,142,70,511]))),Uzt=I.lazy(()=>Fe(()=>import("./BrokerageRecruiting-Cb0OrOCk.js"),__vite__mapDeps([576,574,133,137,410,161,411,412,413,414,313,5,8,384,80,302,217,152,274,83,483,87,339,167,221,213,548,97,178,179,310,575,183,328,475,181,182,491,184,185,186,94,312,160,497,12,39,6,141,142,70,520,477,363,519,241,577]))),Vzt=I.lazy(()=>Fe(()=>import("./BrokerageOnboarding-BPWsNxft.js"),__vite__mapDeps([578,318,319,83,5,80,169,520,477,481,518,152,274,577]))),qzt=I.lazy(()=>Fe(()=>import("./BrokerageTransactions-IQ1JlEkZ.js"),__vite__mapDeps([579,522,201,485,83,580,531,481,79]))),Gzt=I.lazy(()=>Fe(()=>import("./BrokerageOperations-DuYEZ2EA.js"),__vite__mapDeps([581,582,531,318,495]))),Hzt=I.lazy(()=>Fe(()=>import("./WebsitesHub-CpugxUXL.js"),__vite__mapDeps([583,584]))),Wzt=I.lazy(()=>Fe(()=>import("./TeamWebsite-CFrRUPVS.js"),__vite__mapDeps([585,586,60,74,587,584]))),Kzt=I.lazy(()=>Fe(()=>import("./BrokerageWebsite-4xti_wD5.js"),__vite__mapDeps([588,586,60,74,587,584]))),Yzt=I.lazy(()=>Fe(()=>import("./BrokerageCommissionPlans-Dn5FmNN7.js"),__vite__mapDeps([589,521,531,417,483,582,493,104,367,161,111,580,390]))),Zzt=I.lazy(()=>Fe(()=>import("./BrokerageContentActivity-CdLkQiVd.js"),__vite__mapDeps([590,156]))),Xzt=I.lazy(()=>Fe(()=>import("./BetaSocialPostGenerator-hfieDzGZ.js"),__vite__mapDeps([591,156,171,253,254,215,5]))),Qzt=I.lazy(()=>Fe(()=>import("./AdminLMS-DYqcUCsi.js"),__vite__mapDeps([592,593,184,513,74]))),Jzt=I.lazy(()=>Fe(()=>import("./AdminCourseDetail-rWBasbaX.js"),__vite__mapDeps([594,593,184,513,74,158,80]))),e$t=I.lazy(()=>Fe(()=>import("./AdminLMSStats-CCVRxhIu.js"),[])),t$t=I.lazy(()=>Fe(()=>import("./LevelUpU-DYWYELfV.js"),__vite__mapDeps([595,593,184,513]))),r$t=I.lazy(()=>Fe(()=>import("./LevelUpUCourse-CCPCn58_.js"),__vite__mapDeps([596,593]))),n$t=I.lazy(()=>Fe(()=>import("./MobileAgentApp-DvgetW7C.js"),__vite__mapDeps([597,87,168,333,138,137,139,140,141,142,143,144,145,96,97,146,215,37,39,281]))),i$t=I.lazy(()=>Fe(()=>import("./StagingStudio-BL8VxtBn.js"),__vite__mapDeps([598,212,213,599,478,455,50,158,600,601,36,602,192,193,235,79,447]))),s$t=I.lazy(()=>Fe(()=>import("./StagingLibrary-B9ZawrS2.js"),__vite__mapDeps([603,599,478,455,50,600,192,486,79,447]))),a$t=I.lazy(()=>Fe(()=>import("./StagingCredits-BYlflo60.js"),__vite__mapDeps([604,602,192,193,89]))),o$t=I.lazy(()=>Fe(()=>import("./AgentWallet-CS2FKzFC.js"),__vite__mapDeps([605,402,192,606,269,193,292]))),l$t=I.lazy(()=>Fe(()=>import("./StagingSharePage-BJe5vZGA.js"),__vite__mapDeps([607,601]))),c$t=I.lazy(()=>Fe(()=>import("./StagingStudioAdmin-CvCOWaWN.js"),__vite__mapDeps([608,599,478,455,50,4,192,601,447,85]))),u$t=I.lazy(()=>Fe(()=>import("./ContactFinderAdmin-C2sSF_gX.js"),__vite__mapDeps([609,402]))),d$t=I.lazy(()=>Fe(()=>import("./PostcardManager-DMFRmM27.js"),__vite__mapDeps([610,611,250,251,612,234,185,80]))),h$t=I.lazy(()=>Fe(()=>import("./MailStudioTemplates-D_JtiA1r.js"),__vite__mapDeps([613,611,250,251,612,234,185,80,152,274]))),f$t=I.lazy(()=>Fe(()=>import("./HomeReelManager-BYwCPuNI.js"),__vite__mapDeps([614,606,269,615,52,8,339,313,132,504,234,449,133,279,450,80,270,267,430,341]))),m$t=I.lazy(()=>Fe(()=>import("./AdminMusicVideos-BJznJfQn.js"),__vite__mapDeps([616,52]))),p$t=I.lazy(()=>Fe(()=>import("./AdminVideoLab-C0a2SAII.js"),__vite__mapDeps([617,615,52,449,8,158,5,509]))),g$t=I.lazy(()=>Fe(()=>import("./BoostPreview-DKzvQLa8.js"),__vite__mapDeps([618,1,2,3,4,5,6]))),y$t=I.lazy(()=>Fe(()=>import("./AdminCredits-B3nI5Sd5.js"),__vite__mapDeps([619,156,201,476]))),x$t=I.lazy(()=>Fe(()=>import("./AdminCleanup-DnUqLmI9.js"),[])),_$t=I.lazy(()=>Fe(()=>import("./MailStudio-CrWIViMv.js"),__vite__mapDeps([620,612,250,251,417,80,234,158,5,423,185,186,469,386,387,621,360,283,13,461,622,191,440,215,121,229,420,421,359,161,508,148,201,623]))),v$t=()=>{const t=Bi();return a.jsx(li,{to:`/mission-control/direct-mail${t.search}`,replace:!0})},b$t=I.lazy(()=>Fe(()=>import("./InnerCirclePopbyMap-BfiyHZnu.js"),__vite__mapDeps([624,370,425,426,70]))),w$t=I.lazy(()=>Fe(()=>import("./SphereMap-C2oQS8Lq.js"),__vite__mapDeps([625,387,137,448,389,359,621,426,333,376,377,378,379,380,256,234,335,381,313,382,383,384,119,195,152,274,94,138,139,140,141,142,143,144,145,96,97,146,168,215,391,220,402,372,332,434,494]))),S$t=I.lazy(()=>Fe(()=>import("./PropertyIntelligenceDashboard-CPtHuDy8.js"),__vite__mapDeps([626,399,471,270,400]))),T$t=I.lazy(()=>Fe(()=>import("./LiveVisitorFeed-DbPRq-XF.js"),__vite__mapDeps([627,280]))),E$t=I.lazy(()=>Fe(()=>import("./LeadSites-DbdCRuhu.js"),__vite__mapDeps([628,507,506]))),xue=I.lazy(()=>Fe(()=>import("./LeadSiteEditor-Ddnco6Rk.js"),__vite__mapDeps([629,104,630,379,380,47,464,112,186,185,465,401,436,466,467,274,85,279,152,468,469,161,470,9,30,49,183,341,434,381,471,122,400,285,92,472,37,473,474,475,58,305,70,476,83,449,477,478,479,120,335,311,123,267,368,283,480,89,284,270,121,281,241,455,36,74,481,482,483,175,484,147,217,485,264,119,269,411,79,486,487,488,489,133,490,282,462,12,181,182,491,492,201,493,233,158,447,87,107,372,494,218,339,94,336,184,495,362,425,496,115,99,363,497,498,196,391,13,199,499,500,246,501,502,442,414,456,206,413,313,27,503,160,302,504,423,231,52,426,505,448,303,146,8,357,405,113,454,261,151,51,506,507,508,148,111,509,367,290,260,5,189,220,80,450,510,235,292,511,512,268,513,68,207,39,154,388,361,280,6,451,514,215,461,515,38,516,26,50,22,441,517,234,328,332,229,66,204,86,518,519,195,390,520,312,40,108,188,631,132,632,55,408]))),A$t=I.lazy(()=>Fe(()=>import("./AdminLeadSiteThemes-Du73jChV.js"),__vite__mapDeps([633,630,632,303,234,284,489]))),j$t=I.lazy(()=>Fe(()=>import("./AdminFreeWebsiteOffers-UdfWLruH.js"),[])),k$t=I.lazy(()=>Fe(()=>import("./AdminPartnerships-B3v3rOgt.js"),[])),C$t=I.lazy(()=>Fe(()=>import("./MyPartnership-DApGgFbf.js"),[])),I$t=I.lazy(()=>Fe(()=>import("./UpgradeFeature-BD8Qguv0.js"),[])),N$t=I.lazy(()=>Fe(()=>import("./CoachingOnboarding-CpbljFmd.js"),[])),P$t=I.lazy(()=>Fe(()=>import("./AdminFreeWebsiteOfferStudio-mqvybYl4.js"),__vite__mapDeps([634,630,631,132,632,12,13,27,303,133,74,234,121,26,80]))),R$t=I.lazy(()=>Fe(()=>import("./AdminMlsFeeds-YZaiBWCv.js"),__vite__mapDeps([635,270]))),L$t=I.lazy(()=>Fe(()=>import("./AdminLeadSiteAnalytics-YO2ZstZb.js"),[])),D$t=I.lazy(()=>Fe(()=>import("./AdminWebsiteInterests-2QytJ0KG.js"),[])),M$t=I.lazy(()=>Fe(()=>import("./AdminWebsiteRequests-DKQ8sbjB.js"),__vite__mapDeps([636,83]))),O$t=I.lazy(()=>Fe(()=>import("./NeedAWebsite-D-ta1UQm.js"),__vite__mapDeps([637,194,218,160,468]))),F$t=I.lazy(()=>Fe(()=>import("./AdminMlsFeeTracker-DrEeP6ah.js"),[])),B$t=I.lazy(()=>Fe(()=>import("./MLSListings-ByAPDZcA.js"),__vite__mapDeps([638,408,12,430,429,333,386,387,385,141,142,215,235,74,341,52]))),z$t=I.lazy(()=>Fe(()=>import("./MLSListingDetail-LVvgJvPh.js"),__vite__mapDeps([639,168,139,140,333,215,74,382,41,137,136,417,508,148,517]))),$$t=I.lazy(()=>Fe(()=>import("./MarketReportPage-A1RzA9s0.js"),[]));I.lazy(()=>Fe(()=>import("./WebsiteActivityPage-CkPklE9w.js"),__vite__mapDeps([640,168,138,137,139,140,141,142,143,144,145,96,97,146,13])));const U$t=I.lazy(()=>Fe(()=>import("./PublicRecruitForm-vhTv1Ng2.js"),__vite__mapDeps([641,25,483]))),V$t=I.lazy(()=>Fe(()=>import("./PublicRecruitVideo-JfQ5txfI.js"),[])),q$t=I.lazy(()=>Fe(()=>import("./PublicRecruitUnsubscribe-CFP8O8f1.js"),[])),G$t=I.lazy(()=>Fe(()=>import("./PublicEventInviteUnsubscribe-BUVyIPzp.js"),__vite__mapDeps([642,472]))),H$t=I.lazy(()=>Fe(()=>import("./SocialConnections-oByQsA5K.js"),__vite__mapDeps([643,238,66,158,70,231,269,83]))),W$t=I.lazy(()=>Fe(()=>import("./SocialConnectionsCallback-_-on99YE.js"),__vite__mapDeps([644,70,83]))),K$t=I.lazy(()=>Fe(()=>import("./SocialConnectionsGoogleCallback-wdz7crxE.js"),[])),Y$t=I.lazy(()=>Fe(()=>import("./LinkedInCallback-AjpANj5t.js"),__vite__mapDeps([645,70,83]))),Z$t=I.lazy(()=>Fe(()=>import("./TikTokCallback-Dclqb4oT.js"),__vite__mapDeps([646,242,70,83,231]))),X$t=I.lazy(()=>Fe(()=>import("./MarketplaceProductDetail-Bv8XZ_Sl.js"),[])),Q$t=I.lazy(()=>Fe(()=>import("./MarketplaceCart-CXrsC7RT.js"),__vite__mapDeps([647,137,268]))),J$t=I.lazy(()=>Fe(()=>import("./MarketplaceOrders-BXxYJXMK.js"),[])),e6t=I.lazy(()=>Fe(()=>import("./MarketplaceOrderDetail-BsQe-3dE.js"),__vite__mapDeps([648,137,175,516,22]))),t6t=I.lazy(()=>Fe(()=>import("./MarketplaceSuccess-BYDk-MkI.js"),[])),r6t=I.lazy(()=>Fe(()=>import("./RewardStore-BZU7D4Vn.js"),__vite__mapDeps([649,561,221,213,268]))),n6t=I.lazy(()=>Fe(()=>import("./ReferFriends-Cf04-dox.js"),__vite__mapDeps([650,137,168]))),i6t=I.lazy(()=>Fe(()=>import("./SmartPresentations-DjdW2V97.js"),__vite__mapDeps([651,652,401]))),_ue=I.lazy(()=>Fe(()=>import("./SmartPresentationCreate-DDzvNb3Z.js"),__vite__mapDeps([653,177,178,179,180,181,182,183,184,185,186,94,410,161,411,412,413,414,313,5,8,654,74,384,70,382,652,168,138,137,139,140,141,142,143,144,145,96,97,146,133,158]))),s6t=I.lazy(()=>Fe(()=>import("./PublicPresentation-BQhrfUt5.js"),[])),a6t=I.lazy(()=>Fe(()=>import("./GuestBook-B0RpZS2w.js"),__vite__mapDeps([655,137,136,377,388,133,446,447,382,87,401,168,141,94,215,148,374,359,158,201,74,508]))),o6t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>NXe),void 0)),l6t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>DXe),void 0)),c6t=I.lazy(()=>Fe(()=>import("./PublicResourceLanding-Cqzv5qwT.js"),[])),u6t=I.lazy(()=>Fe(()=>import("./SignDocument-BQ6vR6vc.js"),__vite__mapDeps([656,421,83,234,515,455]))),d6t=I.lazy(()=>Fe(()=>import("./Blog-CeSsLzgv.js"),__vite__mapDeps([657,658]))),h6t=I.lazy(()=>Fe(()=>import("./BlogPost-BJWo5qy1.js"),__vite__mapDeps([659,658,480,517]))),f6t=I.lazy(()=>Fe(()=>import("./AdminBlog-8gXmvGfx.js"),__vite__mapDeps([660,137,178,180,575,183,328,182,491,184,311,185,186,94,158,74]))),m6t=I.lazy(()=>Fe(()=>import("./ReviewLanding-gIv5ucvi.js"),__vite__mapDeps([661,662,410,161,411,412,413,414,313,5,8]))),p6t=I.lazy(()=>Fe(()=>import("./PublicReviewsPage-C4ZxEagF.js"),__vite__mapDeps([663,468,501]))),g6t=I.lazy(()=>Fe(()=>import("./PublicReviewSubmit-DEbcVco_.js"),__vite__mapDeps([664,662,410,161,411,412,413,414,313,5,8]))),y6t=I.lazy(()=>Fe(()=>import("./Reviews-CgmhvyZT.js"),__vite__mapDeps([665,136,129,236,237,239,230,231,235,468,151,260,74,66,335,148,372]))),x6t=I.lazy(()=>Fe(()=>import("./ClientPortalPage-DX4YhpSi.js"),[])),_6t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>ynt),void 0)),v6t=I.lazy(()=>Fe(()=>import("./LenderHub-S_fBHTmO.js"),__vite__mapDeps([666,529,667,204]))),b6t=I.lazy(()=>Fe(()=>import("./LendersLanding-BwqlFfxa.js"),__vite__mapDeps([668,667,468,473]))),w6t=I.lazy(()=>Fe(()=>import("./LendingPartners-BigV0Ze9.js"),__vite__mapDeps([669,667,468,316,393,528,529,394,497,466]))),S6t=I.lazy(()=>Fe(()=>import("./AdminLenders-CoqNwuiI.js"),__vite__mapDeps([670,667,468,74]))),T6t=I.lazy(()=>Fe(()=>import("./CardStudio-CmFXRX5j.js"),__vite__mapDeps([671,384,526,410,161,411,412,413,414,313,5,8,382,237,168,144]))),E6t=I.lazy(()=>Fe(()=>import("./ListingStudio-BCT6YhbL.js"),__vite__mapDeps([672,158,284,121,482,104,414,51,363,30]))),A6t=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>cPt),void 0)),j6t=I.lazy(()=>Fe(()=>import("./SmartDrips-C-6yoCsj.js"),__vite__mapDeps([673,137,168,507,405,382,526,410,161,411,412,413,414,313,5,8,384,377,378,379,380,256,234,335,381,383,119,195,152,274,94,397,333,215,372,285]))),k6t=I.lazy(()=>Fe(()=>import("./WeeklyReels-FYaCmvMJ.js"),__vite__mapDeps([674,212,213,675,137,221,676,449,243,235]))),C6t=I.lazy(()=>Fe(()=>import("./WeeklyReelsOnboarding-C3nJN8Nx.js"),__vite__mapDeps([677,676]))),I6t=I.lazy(()=>Fe(()=>import("./WeeklyReelsAdmin-DISH1hy_.js"),__vite__mapDeps([678,243,676,675,137,221,213,449]))),N6t=I.lazy(()=>Fe(()=>import("./AttractLayout-BrxaU7JW.js"),__vite__mapDeps([679,680,681,682,154,6,241]))),P6t=I.lazy(()=>Fe(()=>import("./AttractToday-CmTA4UzA.js"),__vite__mapDeps([683,221,213,681,684,685,686,687,688,372,339,492,689,690,520,285,502,691,512]))),R6t=I.lazy(()=>Fe(()=>import("./AttractRelationships-CHxdMzns.js"),__vite__mapDeps([692,693,689,685,690,217,694,401,686,681,684,520]))),L6t=I.lazy(()=>Fe(()=>import("./AttractFollowUp-vY8ZasUZ.js"),__vite__mapDeps([695,693,686,685,123]))),D6t=I.lazy(()=>Fe(()=>import("./AttractResources-O05djgyz.js"),[])),M6t=I.lazy(()=>Fe(()=>import("./AttractTemplates-CNSOATMs.js"),__vite__mapDeps([696,123,290]))),O6t=I.lazy(()=>Fe(()=>import("./AttractReports-BH2sewcr.js"),__vite__mapDeps([697,693,685,687,690,304]))),F6t=I.lazy(()=>Fe(()=>import("./AttractSettings-CsrupXBW.js"),__vite__mapDeps([698,693,680,5]))),B6t=I.lazy(()=>Fe(()=>import("./AttractToolkit-CRGkk0BY.js"),__vite__mapDeps([699,693,246,512,285,339]))),z6t=I.lazy(()=>Fe(()=>import("./Objections-Otx5uwaQ.js"),__vite__mapDeps([700,512]))),$6t=I.lazy(()=>Fe(()=>import("./AttractCalculator-DFc8zylx.js"),__vite__mapDeps([701,693,702,508]))),U6t=I.lazy(()=>Fe(()=>import("./AttractEventList-CieuGmxE.js"),__vite__mapDeps([703,691]))),vue=I.lazy(()=>Fe(()=>import("./AttractEventBuilder-Cv0L3W69.js"),__vite__mapDeps([704,137,691,705,94,80]))),V6t=I.lazy(()=>Fe(()=>import("./AttractEventDetail-BtDAPuWz.js"),__vite__mapDeps([706,691,685,148,246]))),q6t=I.lazy(()=>Fe(()=>import("./AttractEventCheckIn-BYsQ00Qx.js"),__vite__mapDeps([707,440,691,148]))),G6t=I.lazy(()=>Fe(()=>import("./AttractOnboarding--jGZwPOC.js"),__vite__mapDeps([708,680,154,490,285]))),H6t=I.lazy(()=>Fe(()=>import("./ContentStudio-Che7zqBM.js"),__vite__mapDeps([709,693,510]))),W6t=I.lazy(()=>Fe(()=>import("./KitList-BeA53PFs.js"),__vite__mapDeps([710,705,339,113]))),bue=I.lazy(()=>Fe(()=>import("./KitBuilder-pBS6sH6b.js"),__vite__mapDeps([711,705,685,693,712,94,246,152,274,313,161]))),K6t=I.lazy(()=>Fe(()=>import("./KitAnalytics-BacOuerW.js"),__vite__mapDeps([713,705,693,160,304]))),Y6t=I.lazy(()=>Fe(()=>import("./KitTemplates-Dm13xRMq.js"),__vite__mapDeps([714,705,693]))),Z6t=I.lazy(()=>Fe(()=>import("./AttractAgentDetail-DRkjv8QD.js"),__vite__mapDeps([715,694,685,401,138,137,139,140,141,142,143,144,145,96,97,146,168,681,686,682,688,372,339,492,690,6,280,279,520,39]))),X6t=I.lazy(()=>Fe(()=>import("./AttractOpportunities-D__St6Oa.js"),__vite__mapDeps([716,681,684,688,372,339,492]))),Q6t=I.lazy(()=>Fe(()=>import("./AttractIntelligenceDebug-CTzDBXKX.js"),__vite__mapDeps([717,681,682,470]))),J6t=I.lazy(()=>Fe(()=>import("./AttractToolsQA-DFAiVsPZ.js"),[])),eUt=I.lazy(()=>Fe(()=>import("./PublicAttractKit-j4diF7eW.js"),__vite__mapDeps([718,712,94,246]))),tUt=I.lazy(()=>Fe(()=>import("./PublicAttractEvent-L2cExoBj.js"),__vite__mapDeps([719,691]))),rUt=I.lazy(()=>Fe(()=>import("./PublicAttractEventCheckIn-BBIeRz8N.js"),[])),nUt=I.lazy(()=>Fe(()=>import("./PublicAttractionPage-D41HTTcs.js"),__vite__mapDeps([720,721,212,213]))),iUt=I.lazy(()=>Fe(()=>import("./RevivalLanding-DTzV6oR4.js"),__vite__mapDeps([722,723]))),wue=I.lazy(()=>Fe(()=>import("./RevivalPlan-_rWiyUfe.js"),__vite__mapDeps([724,725,136,723,417,440]))),sUt=I.lazy(()=>Fe(()=>import("./ListingRevival-Cus2Dq9K.js"),__vite__mapDeps([726,727,723,570,479,217,148,728,218,235,401,465]))),aUt=I.lazy(()=>Fe(()=>import("./RevivalCampaignWizard-BGDkX2wG.js"),__vite__mapDeps([729,422,416,417,158,727,723,730,253,622]))),oUt=I.lazy(()=>Fe(()=>import("./RevivalCampaignDetail-EEupn-cT.js"),__vite__mapDeps([731,136,730,253,417,622,732,195,488,80,374,359,727,723,725,440,410,161,411,412,413,414,313,5,8,384,70,422,416,158,74,148,220,508,483,30]))),lUt=I.lazy(()=>Fe(()=>import("./FsboBreakthrough-BdmD3dOb.js"),__vite__mapDeps([733,734,735,736,422,416,417,158,148,728,218,235,401,465]))),cUt=I.lazy(()=>Fe(()=>import("./FsboCampaignWizard-u3m9z2mB.js"),__vite__mapDeps([737,422,416,417,158,734,735,730,253,622]))),uUt=I.lazy(()=>Fe(()=>import("./FsboCampaignDetail-Bb8vuH2e.js"),__vite__mapDeps([738,136,730,253,417,622,732,195,488,80,734,735,374,359,736,422,416,158,191,483,508]))),dUt=I.lazy(()=>Fe(()=>import("./FsboLanding-Cvy0PryD.js"),__vite__mapDeps([739,735,740]))),hUt=I.lazy(()=>Fe(()=>import("./FsboGuide-ytYDLII7.js"),__vite__mapDeps([741,740]))),fUt=I.lazy(()=>Fe(()=>import("./FsboBreakthroughAdmin-B1E48rqJ.js"),__vite__mapDeps([742,734,148,728]))),mUt=I.lazy(()=>Fe(()=>import("./AttractLandingPageBuilder-CgWw1CvX.js"),__vite__mapDeps([743,702,721,212,213,80]))),pUt=I.lazy(()=>Fe(()=>import("./AttractAccess-nv0dHJvv.js"),__vite__mapDeps([744,156,201,83]))),gUt=I.lazy(()=>Fe(()=>import("./Teams-DiDq8hMM.js"),__vite__mapDeps([745,275,284,276,277,278,279,280,201,281,5,282,283,79,86]))),yUt=I.lazy(()=>Fe(()=>import("./MyTeam-DB9G-CJi.js"),__vite__mapDeps([746,275,278,279,280,201,281,5,282,277,747,284,283,79]))),xUt=I.lazy(()=>Fe(()=>import("./TeamHub-Db8E_ABy.js"),__vite__mapDeps([748,275,278,279,280,201,281,5,282,277,747,586,60,74,284,283,79]))),_Ut=I.lazy(()=>Fe(()=>import("./SchedulerSettings-CQ0QBMgf.js"),__vite__mapDeps([749,91,92,93,66,137,499,83,549,96,97,235]))),vUt=I.lazy(()=>Fe(()=>import("./MyCalendar-DLupxMyI.js"),__vite__mapDeps([750,93,237,240,239,241]))),bUt=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>mPt),void 0)),wUt=I.lazy(()=>Fe(()=>import("./BookingManagePage-Cew2uH68.js"),__vite__mapDeps([751,83]))),SUt=I.lazy(()=>Fe(()=>import("./LandingPages-DlQVKEq3.js"),__vite__mapDeps([752,136,148]))),TUt=I.lazy(()=>Fe(()=>import("./BuyerMatch-x3tx7eBC.js"),__vite__mapDeps([753,754,326,256,327,183,328,184,94,160,313,152,274,329,139,140,333,386,387,215,8,401]))),EUt=I.lazy(()=>Fe(()=>import("./BuyerMatchEditor-CiCJoDVs.js"),__vite__mapDeps([755,136,754,326,256,327,183,328,184,94,160,313,152,274,329,139,140,333,386,387,215,138,137,141,142,143,144,145,96,97,146,756,80]))),AUt=I.lazy(()=>Fe(()=>import("./PublicBuyerMatch-Bh4CWH-H.js"),__vite__mapDeps([757,756,496,83]))),jUt=I.lazy(()=>Fe(()=>import("./LandingPageEditor-CdKcG9OB.js"),__vite__mapDeps([758,136,160,132,148,80,133]))),kUt=I.lazy(()=>Fe(()=>import("./LandingPageDefaults-DWGauuDZ.js"),__vite__mapDeps([759,80]))),CUt=I.lazy(()=>Fe(()=>Promise.resolve().then(()=>MPt),void 0)),IUt=I.lazy(()=>Fe(()=>import("./WebsiteAppsHub-CHsF_kks.js"),__vite__mapDeps([760,761,284,762,464,112,186,185,465,401,436,466,467,274,85,279,152,468,469,161,470,9,30,49,183,341,434,381,471,122,400,285,92,472,37,473,474,475,58,305,70,476,83,449,477,478,479,120,335,311,123,267,368,283,480,89,270,121,281,241,455,36,74,481,482,483,175,484,147,217,485,264,119,269,411,79,486,487,488,489,133,490,282,462,12,181,182,491,492,201,493,233,158,447,87,107,372,494,218,339,94,336,184,495,362,425,496,115,99,363,497,498,196,391,13,199,499,500,246,501,502,442,414,456,206,413,313,27,503,160,302,504,423,231,52,426,505,448,303,146,104,8,357,405,113,454,261,151,51,506,507,508,148,111,509,367,290,260,5,189,220,80,450,510,235,292,511,512,268,513,68,207,39,154,388,361,280,6,451,514,215,461,515,38,516,26,50,22,441,517,234,328,332,229,66,204,86,518,519,195,390,520,312,40,108,188]))),NUt=I.lazy(()=>Fe(()=>import("./ClaimWebsite-Bi7CSp_m.js"),__vite__mapDeps([763,761,284]))),PUt=I.lazy(()=>Fe(()=>import("./VideoGreeterEditor-BtlIRawG.js"),__vite__mapDeps([764,762,382,632,410,161,411,412,413,414,313,5,8,654,74,384,70]))),RUt=I.lazy(()=>Fe(()=>import("./ExitIntentEditor-sKAxD0iC.js"),__vite__mapDeps([765,762,766]))),LUt=I.lazy(()=>Fe(()=>import("./LeadMagnetEditor-Cujj-60d.js"),__vite__mapDeps([767,762,766]))),DUt=I.lazy(()=>Fe(()=>import("./EmbedVideoGreeter-D61i-uFQ.js"),[])),MUt=I.lazy(()=>Fe(()=>import("./EmbedLeadMagnet-BGo2ayb2.js"),[])),OUt=I.lazy(()=>Fe(()=>import("./RelationshipScorecard-BVE7obpy.js"),__vite__mapDeps([768,373,174,467,357,167]))),FUt=I.lazy(()=>Fe(()=>import("./SphereGaps-EuybS2Zb.js"),__vite__mapDeps([769,143,168,138,137,139,140,141,142,144,145,96,97,146,333,505,215,80]))),BUt=I.lazy(()=>Fe(()=>import("./Signals-BTK_n8_0.js"),[])),zUt=I.lazy(()=>Fe(()=>import("./ConnectPageSettings-CC3j2Nmq.js"),__vite__mapDeps([770,143]))),$Ut=I.lazy(()=>Fe(()=>import("./WebsiteActivityPage-CkPklE9w.js"),__vite__mapDeps([640,168,138,137,139,140,141,142,143,144,145,96,97,146,13]))),UUt=I.lazy(()=>Fe(()=>import("./EmailCampaigns-BUwUn_TF.js"),__vite__mapDeps([771,772,97,139,70]))),VUt=I.lazy(()=>Fe(()=>import("./EmailCompliance-B_9R7RHk.js"),__vite__mapDeps([773,498]))),qUt=I.lazy(()=>Fe(()=>import("./EmailCampaignComposer-C9bzL80b.js"),__vite__mapDeps([774,772,97,140,775,178,180,310,179,183,181,182,184,185,186,94,461,400,218,329,341,79,382,330,311,146]))),GUt=I.lazy(()=>Fe(()=>import("./EmailCampaignDetail-BUh7I9pC.js"),__vite__mapDeps([776,302,161]))),HUt=I.lazy(()=>Fe(()=>import("./SharedCampaignTemplates-BXSllPag.js"),__vite__mapDeps([777,778,775,178,180,310,179,183,181,182,184,185,186,94,461,400,218,341,311]))),WUt=I.lazy(()=>Fe(()=>import("./AgentTemplates-DxTfyiEC.js"),__vite__mapDeps([779,778,775,178,180,310,179,183,181,182,184,185,186,94,461,400,218,341,311,79]))),Sue=I.lazy(()=>Fe(()=>import("./TheLocalMoveHome-CCqZM9DZ.js"),__vite__mapDeps([780,781,283,474,122]))),Tue=I.lazy(()=>Fe(()=>import("./TheLocalMoveGetStarted-DPS7KYln.js"),__vite__mapDeps([782,781]))),Eue=I.lazy(()=>Fe(()=>import("./TheLocalMoveCheckout-tKpZMdHZ.js"),__vite__mapDeps([783,241]))),Aue=I.lazy(()=>Fe(()=>import("./TheLocalMoveCheckoutSuccess-CVh3h39u.js"),[])),KUt=I.lazy(()=>Fe(()=>import("./AdminWebsiteOrders-UHn-mTVr.js"),__vite__mapDeps([784,215]))),YUt=new XFe({defaultOptions:{queries:{refetchOnWindowFocus:!1,staleTime:5*60*1e3}}}),ZUt=()=>{const t=window.location.hostname;return t==="listings.relevelup.com"||t.startsWith("listings.")},XUt=()=>{const t=window.location.hostname;return t==="commercial.relevelup.com"||t.startsWith("commercial.")},QUt=()=>{const t=window.location.hostname;return t==="cards.relevelup.com"||t.startsWith("cards.")},JUt=()=>{const t=window.location.hostname;return t==="presentations.relevelup.com"||t.startsWith("presentations.")},eVt=()=>{const t=window.location.hostname;return t==="guestbook.relevelup.com"||t.startsWith("guestbook.")},tVt=()=>{const t=window.location.hostname;return t==="clients.relevelup.com"||t.startsWith("clients.")},rVt=()=>{const t=window.location.hostname;return t==="cma.relevelup.com"||t.startsWith("cma.")},nVt=()=>{const t=window.location.hostname;return t==="cardstudio.relevelup.com"||t.startsWith("cardstudio.")},iVt=()=>{const t=window.location.hostname;return t==="booking.relevelup.com"||t.startsWith("booking.")},sVt=()=>{const t=window.location.hostname;return t==="contacts.relevelup.com"||t.startsWith("contacts.")},aVt=()=>{const t=window.location.hostname;return t==="pages.relevelup.com"||t.startsWith("pages.")},dje=()=>{const t=window.location.hostname;return t==="thelocalmove.com"||t==="www.thelocalmove.com"},oVt=new Set(["app","www","api","admin","embed","cdn","static","assets"]),lVt=()=>{const t=window.location.hostname;if(new URLSearchParams(window.location.search).get("previewSlug"))return!0;if(Xhe(t))return!(window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"));if(!t.endsWith(".thelocalmove.com")||dje())return!1;const e=t.replace(/\.thelocalmove\.com$/,"").split(".").pop()||"";return!(oVt.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 cVt=()=>a.jsx(r5e,{client:YUt,children:a.jsx(Qpe,{children:a.jsxs(vpe,{children:[a.jsx(fMe,{}),a.jsx(GMe,{}),a.jsx(u3e,{}),a.jsx(d4e,{future:{v7_startTransition:!0},children:a.jsx(l$e,{children:a.jsx(f$e,{children:a.jsx(p$e,{children:a.jsxs(h$e,{children:[a.jsx(m$e,{}),a.jsx(rUe,{}),a.jsx(kYe,{}),nVt()?a.jsx(uPt,{}):QUt()?a.jsx(iXe,{}):XUt()?a.jsx(IZe,{}):ZUt()?a.jsx(kZe,{}):JUt()?a.jsx(lXe,{}):eVt()?a.jsx(Brt,{}):tVt()?a.jsx(xnt,{}):rVt()?a.jsx(Snt,{}):iVt()?a.jsx(pPt,{}):sVt()?a.jsx(EPt,{}):aVt()?a.jsx(OPt,{}):dje()?a.jsxs(l_,{children:[a.jsx(Te,{path:"/get-started",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Tue,{})})}),a.jsx(Te,{path:"/checkout",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Eue,{})})}),a.jsx(Te,{path:"/checkout/success",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Aue,{})})}),a.jsx(Te,{path:"/privacy-policy",element:a.jsx(sue,{})}),a.jsx(Te,{path:"/terms-of-service",element:a.jsx(aue,{})}),a.jsx(Te,{path:"/mcp-data-use",element:a.jsx(oue,{})}),a.jsx(Te,{path:"*",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Sue,{})})})]}):lVt()?a.jsx(S5t,{}):a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsxs(l_,{children:[a.jsx(Te,{path:"/",element:a.jsx(znt,{})}),a.jsx(Te,{path:"/the-local-move",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Sue,{})})}),a.jsx(Te,{path:"/get-started",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Tue,{})})}),a.jsx(Te,{path:"/local-move/checkout",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Eue,{})})}),a.jsx(Te,{path:"/local-move/checkout/success",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(Aue,{})})}),a.jsx(Te,{path:"/privacy-policy",element:a.jsx(sue,{})}),a.jsx(Te,{path:"/terms-of-service",element:a.jsx(aue,{})}),a.jsx(Te,{path:"/data-deletion",element:a.jsx(C5t,{})}),a.jsx(Te,{path:"/mcp-data-use",element:a.jsx(oue,{})}),a.jsx(Te,{path:"/canva-support",element:a.jsx(k5t,{})}),a.jsx(Te,{path:"/sms-opt-in",element:a.jsx(I5t,{})}),a.jsx(Te,{path:"/oauth-connect",element:a.jsx(f6,{})}),a.jsx(Te,{path:"/.lovable/oauth/consent",element:a.jsx(f6,{})}),a.jsx(Te,{path:"/oauth/consent",element:a.jsx(f6,{})}),a.jsx(Te,{path:"/mcp",element:a.jsx(lue,{})}),a.jsx(Te,{path:"/connect-chatgpt",element:a.jsx(lue,{})}),a.jsx(Te,{path:"/connect-chatgpt/classic",element:a.jsx(N5t,{})}),a.jsx(Te,{path:"/public/listings",element:a.jsx(i4t,{})}),a.jsx(Te,{path:"/public/commercial",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(j5t,{})})}),a.jsx(Te,{path:"/public/listing/:slugOrId",element:a.jsx(s4t,{})}),a.jsx(Te,{path:"/listing/:slugOrId",element:a.jsx(uVt,{})}),a.jsx(Te,{path:"/private-listing",element:a.jsx(c4t,{})}),a.jsx(Te,{path:"/commercial-pitch/:token",element:a.jsx(l4t,{})}),a.jsx(Te,{path:"/card/:slug",element:a.jsx(u4t,{})}),a.jsx(Te,{path:"/join-brokerage/:slug",element:a.jsx(U$t,{})}),a.jsx(Te,{path:"/recruit-unsubscribe",element:a.jsx(q$t,{})}),a.jsx(Te,{path:"/event-invite-unsubscribe",element:a.jsx(G$t,{})}),a.jsx(Te,{path:"/recruit-video/:shareToken",element:a.jsx(V$t,{})}),a.jsx(Te,{path:"/connect/:slug",element:a.jsx(d4t,{})}),a.jsx(Te,{path:"/home-value",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(fue,{})})}),a.jsx(Te,{path:"/whats-my-home-worth",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(fue,{})})}),a.jsx(Te,{path:"/live/:slug",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(h4t,{})})}),a.jsx(Te,{path:"/auth",element:a.jsx(mie,{})}),a.jsx(Te,{path:"/login",element:a.jsx(mie,{})}),a.jsx(Te,{path:"/subscription-success",element:a.jsx(P5t,{})}),a.jsx(Te,{path:"/subscription",element:a.jsx(ut,{children:a.jsx(R5t,{})})}),a.jsxs(Te,{path:"/share/video",element:a.jsx(r4t,{}),children:[a.jsx(Te,{path:":shareToken",element:a.jsx(due,{})}),a.jsx(Te,{path:":shareToken/r/:recipientToken",element:a.jsx(due,{})})]}),a.jsx(Te,{path:"/p/:shareToken",element:a.jsx(s6t,{})}),a.jsx(Te,{path:"/portal/:slug",element:a.jsx(x6t,{})}),a.jsx(Te,{path:"/portal/:slug/refer",element:a.jsx(_6t,{})}),a.jsx(Te,{path:"/lender/:token",element:a.jsx(v6t,{})}),a.jsx(Te,{path:"/lenders",element:a.jsx(I.Suspense,{fallback:null,children:a.jsx(b6t,{})})}),a.jsx(Te,{path:"/og/video/:token",element:a.jsx(n4t,{})}),a.jsx(Te,{path:"/setup-brokerage",element:a.jsx(ut,{children:a.jsx(L5t,{})})}),a.jsx(Te,{path:"/claim-account",element:a.jsx(cue,{})}),a.jsx(Te,{path:"/claim",element:a.jsx(cue,{})}),a.jsx(Te,{path:"/activate",element:a.jsx(D5t,{})}),a.jsx(Te,{path:"/auth/confirm-reset",element:a.jsx(uue,{})}),a.jsx(Te,{path:"/auth/continue",element:a.jsx(uue,{})}),a.jsx(Te,{path:"/join",element:a.jsx(M5t,{})}),a.jsx(Te,{path:"/trial",element:a.jsx(Y5t,{})}),a.jsx(Te,{path:"/trial/success",element:a.jsx(Z5t,{})}),a.jsx(Te,{path:"/labor-day",element:a.jsx(X5t,{})}),a.jsx(Te,{path:"/brokerage-labor-day",element:a.jsx(Q5t,{})}),a.jsx(Te,{path:"/brokerage-solutions",element:a.jsx(J5t,{})}),a.jsx(Te,{path:"/upgrade",element:a.jsx(e4t,{})}),a.jsx(Te,{path:"/instagram",element:a.jsx(t4t,{})}),a.jsx(Te,{path:"/dashboard",element:a.jsx(ut,{children:a.jsx(p4t,{})})}),a.jsx(Te,{path:"/coaching",element:a.jsx(ut,{children:a.jsx(O5t,{})})}),a.jsx(Te,{path:"/coaching/billing",element:a.jsx(ut,{children:a.jsx($5t,{})})}),a.jsx(Te,{path:"/coaching/settings",element:a.jsx(ut,{children:a.jsx(U5t,{})})}),a.jsx(Te,{path:"/coaching/waitlist",element:a.jsx(ut,{children:a.jsx(G5t,{})})}),a.jsx(Te,{path:"/coaching/agent/:id",element:a.jsx(ut,{children:a.jsx(F5t,{})})}),a.jsx(Te,{path:"/my-coach",element:a.jsx(ut,{children:a.jsx(B5t,{})})}),a.jsx(Te,{path:"/admin/coaching",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(z5t,{})})}),a.jsx(Te,{path:"/oauth/google-calendar/return",element:a.jsx(V5t,{})}),a.jsx(Te,{path:"/oauth/microsoft-365/return",element:a.jsx(q5t,{})}),a.jsxs(Te,{path:"/attract",element:a.jsx(ut,{children:a.jsx(A5t,{children:a.jsx(N6t,{})})}),children:[a.jsx(Te,{index:!0,element:a.jsx(P6t,{})}),a.jsx(Te,{path:"agents",element:a.jsx(R6t,{})}),a.jsx(Te,{path:"agents/:agentId",element:a.jsx(Z6t,{})}),a.jsx(Te,{path:"attract-page",element:a.jsx(mUt,{})}),a.jsx(Te,{path:"calculator",element:a.jsx($6t,{})}),a.jsx(Te,{path:"results",element:a.jsx(O6t,{})}),a.jsx(Te,{path:"onboarding",element:a.jsx(G6t,{})}),a.jsx(Te,{path:"opportunities",element:a.jsx(X6t,{})}),a.jsx(Te,{path:"follow-up",element:a.jsx(L6t,{})}),a.jsx(Te,{path:"settings",element:a.jsx(F6t,{})}),a.jsxs(Te,{path:"toolkit",element:a.jsx(B6t,{}),children:[a.jsx(Te,{index:!0,element:a.jsx(li,{to:"/attract/toolkit/kits",replace:!0})}),a.jsx(Te,{path:"kits",element:a.jsx(W6t,{})}),a.jsx(Te,{path:"scripts",element:a.jsx(M6t,{})}),a.jsx(Te,{path:"objections",element:a.jsx(z6t,{})}),a.jsx(Te,{path:"events",element:a.jsx(U6t,{})}),a.jsx(Te,{path:"content",element:a.jsx(H6t,{})}),a.jsx(Te,{path:"resources",element:a.jsx(D6t,{})})]}),a.jsx(Te,{path:"toolkit/kits/templates",element:a.jsx(Y6t,{})}),a.jsx(Te,{path:"toolkit/kits/new",element:a.jsx(bue,{})}),a.jsx(Te,{path:"toolkit/kits/:kitId/edit",element:a.jsx(bue,{})}),a.jsx(Te,{path:"toolkit/kits/:kitId/analytics",element:a.jsx(K6t,{})}),a.jsx(Te,{path:"events/new",element:a.jsx(vue,{})}),a.jsx(Te,{path:"events/:eventId",element:a.jsx(V6t,{})}),a.jsx(Te,{path:"events/:eventId/edit",element:a.jsx(vue,{})}),a.jsx(Te,{path:"events/:eventId/checkin",element:a.jsx(q6t,{})}),a.jsx(Te,{path:"relationships",element:a.jsx(li,{to:"/attract/agents",replace:!0})}),a.jsx(Te,{path:"pipeline",element:a.jsx(li,{to:"/attract/agents",replace:!0})}),a.jsx(Te,{path:"plan",element:a.jsx(li,{to:"/attract/settings",replace:!0})}),a.jsx(Te,{path:"digest",element:a.jsx(li,{to:"/attract/results",replace:!0})}),a.jsx(Te,{path:"reports",element:a.jsx(li,{to:"/attract/results",replace:!0})}),a.jsx(Te,{path:"dashboard-legacy",element:a.jsx(li,{to:"/attract",replace:!0})}),a.jsx(Te,{path:"share",element:a.jsx(li,{to:"/attract/toolkit/kits",replace:!0})}),a.jsx(Te,{path:"create",element:a.jsx(li,{to:"/attract/toolkit/content",replace:!0})}),a.jsx(Te,{path:"templates",element:a.jsx(li,{to:"/attract/toolkit/scripts",replace:!0})}),a.jsx(Te,{path:"resources",element:a.jsx(li,{to:"/attract/toolkit/resources",replace:!0})}),a.jsx(Te,{path:"events",element:a.jsx(li,{to:"/attract/toolkit/events",replace:!0})}),a.jsx(Te,{path:"landing-page",element:a.jsx(li,{to:"/attract/attract-page",replace:!0})}),a.jsx(Te,{path:"provide/kits",element:a.jsx(li,{to:"/attract/toolkit/kits",replace:!0})}),a.jsx(Te,{path:"provide/kits/templates",element:a.jsx(li,{to:"/attract/toolkit/kits/templates",replace:!0})}),a.jsx(Te,{path:"provide/*",element:a.jsx(li,{to:"/attract/toolkit/kits",replace:!0})}),a.jsx(Te,{path:"influence/content-studio",element:a.jsx(li,{to:"/attract/toolkit/content",replace:!0})}),a.jsx(Te,{path:"influence/*",element:a.jsx(li,{to:"/attract/toolkit/content",replace:!0})}),a.jsx(Te,{path:"produce/*",element:a.jsx(li,{to:"/attract/results",replace:!0})}),a.jsx(Te,{path:"connect/*",element:a.jsx(li,{to:"/attract/toolkit/events",replace:!0})}),a.jsx(Te,{path:"connect",element:a.jsx(li,{to:"/attract/toolkit/events",replace:!0})}),a.jsx(Te,{path:"pillars/*",element:a.jsx(li,{to:"/attract",replace:!0})})]}),a.jsx(Te,{path:"/weekly-reels",element:a.jsx(ut,{children:a.jsx(iue,{children:a.jsx(k6t,{})})})}),a.jsx(Te,{path:"/weekly-reels/onboarding",element:a.jsx(ut,{children:a.jsx(iue,{children:a.jsx(C6t,{})})})}),a.jsx(Te,{path:"/admin/weekly-reels",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I6t,{})})}),a.jsx(Te,{path:"/admin/attract-access",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(pUt,{})})}),a.jsx(Te,{path:"/admin/attract-intelligence",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Q6t,{})})}),a.jsx(Te,{path:"/admin/attract-tools",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(J6t,{})})}),a.jsx(Te,{path:"/attract-kit/:shareToken",element:a.jsx(eUt,{})}),a.jsx(Te,{path:"/attract-event/:slug",element:a.jsx(tUt,{})}),a.jsx(Te,{path:"/attract-event-checkin/:token",element:a.jsx(rUt,{})}),a.jsx(Te,{path:"/join/:slug",element:a.jsx(nUt,{})}),a.jsx(Te,{path:"/revival/:slug",element:a.jsx(iUt,{})}),a.jsx(Te,{path:"/revival/:slug/plan",element:a.jsx(wue,{})}),a.jsx(Te,{path:"/fsbo/:slug",element:a.jsx(dUt,{})}),a.jsx(Te,{path:"/fsbo/:slug/guide",element:a.jsx(hUt,{})}),a.jsx(Te,{path:"/revival/:slug/plan",element:a.jsx(wue,{})}),a.jsx(Te,{path:"/coaches",element:a.jsx(H5t,{})}),a.jsx(Te,{path:"/coaches/apply",element:a.jsx(K5t,{})}),a.jsx(Te,{path:"/coaches/:slug",element:a.jsx(W5t,{})}),a.jsx(Te,{path:"/credits",element:a.jsx(ut,{children:a.jsx(o$t,{})})}),a.jsx(Te,{path:"/wallet",element:a.jsx(li,{to:"/credits",replace:!0})}),a.jsx(Te,{path:"/profile",element:a.jsx(ut,{children:a.jsx(g4t,{})})}),a.jsx(Te,{path:"/apps/*",element:a.jsx(ut,{children:a.jsx(_4t,{})})}),a.jsx(Te,{path:"/admin",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(mue,{})})}),a.jsx(Te,{path:"/admin/dashboard",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(mue,{})})}),a.jsx(Te,{path:"/admin/apps",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(q4t,{})})}),a.jsx(Te,{path:"/admin/members",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(G4t,{})})}),a.jsx(Te,{path:"/admin/unassigned-members",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(H4t,{})})}),a.jsx(Te,{path:"/admin/invite-codes",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(W4t,{})})}),a.jsx(Te,{path:"/admin/events",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(K4t,{})})}),a.jsx(Te,{path:"/admin/live",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(f4t,{})})})}),a.jsx(Te,{path:"/admin/live/:id",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{}),children:a.jsx(m4t,{})})})}),a.jsx(Te,{path:"/admin/mcp-audit",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Y4t,{})})}),a.jsx(Te,{path:"/events",element:a.jsx(ut,{children:a.jsx(y4t,{})})}),a.jsx(Te,{path:"/events/:eventId",element:a.jsx(ut,{children:a.jsx(x4t,{})})}),a.jsx(Te,{path:"/templates",element:a.jsx(ut,{children:a.jsx(v4t,{})})}),a.jsx(Te,{path:"/templates/:templateId",element:a.jsx(ut,{children:a.jsx(b4t,{})})}),a.jsx(Te,{path:"/admin/templates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Z4t,{})})}),a.jsx(Te,{path:"/programs",element:a.jsx(ut,{children:a.jsx(w4t,{})})}),a.jsx(Te,{path:"/programs/:slug",element:a.jsx(ut,{children:a.jsx(S4t,{})})}),a.jsx(Te,{path:"/programs/:slug/enroll",element:a.jsx(ut,{children:a.jsx(T4t,{})})}),a.jsx(Te,{path:"/programs/:slug/workspace",element:a.jsx(ut,{children:a.jsx(E4t,{})})}),a.jsx(Te,{path:"/admin/programs",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(A4t,{})})}),a.jsx(Te,{path:"/watch/:slug",element:a.jsx(C4t,{})}),a.jsx(Te,{path:"/academy",element:a.jsx(ut,{children:a.jsx(j4t,{})})}),a.jsx(Te,{path:"/academy/:videoId",element:a.jsx(ut,{children:a.jsx(k4t,{})})}),a.jsx(Te,{path:"/admin/academy",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(X4t,{})})}),a.jsx(Te,{path:"/toolbox",element:a.jsx(ut,{children:a.jsx(I4t,{})})}),a.jsx(Te,{path:"/toolbox/:kitId",element:a.jsx(ut,{children:a.jsx(N4t,{})})}),a.jsx(Te,{path:"/admin/toolbox",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Q4t,{})})}),a.jsx(Te,{path:"/admin/blog",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(f6t,{})})}),a.jsx(Te,{path:"/social-swag",element:a.jsx(ut,{children:a.jsx(P4t,{})})}),a.jsx(Te,{path:"/social-studio",element:a.jsx(ut,{children:a.jsx(R4t,{})})}),a.jsx(Te,{path:"/social-swag-2",element:a.jsx(li,{to:"/social-studio?tab=gallery",replace:!0})}),a.jsx(Te,{path:"/marketing-studio",element:a.jsx(ut,{children:a.jsx(L4t,{})})}),a.jsx(Te,{path:"/marketing-studio/brand-kit",element:a.jsx(ut,{children:a.jsx(D4t,{})})}),a.jsx(Te,{path:"/marketing-studio/branding-bar",element:a.jsx(ut,{children:a.jsx(M4t,{})})}),a.jsx(Te,{path:"/marketing-studio/listing-templates",element:a.jsx(ut,{children:a.jsx(O4t,{})})}),a.jsx(Te,{path:"/marketing-studio/personal-branding",element:a.jsx(ut,{children:a.jsx(F4t,{})})}),a.jsx(Te,{path:"/social-swag/:swagId",element:a.jsx(ut,{children:a.jsx(B4t,{})})}),a.jsx(Te,{path:"/social-connections",element:a.jsx(ut,{children:a.jsx(H$t,{})})}),a.jsx(Te,{path:"/social-connections/callback",element:a.jsx(ut,{children:a.jsx(W$t,{})})}),a.jsx(Te,{path:"/social-connections/linkedin-callback",element:a.jsx(ut,{children:a.jsx(Y$t,{})})}),a.jsx(Te,{path:"/social-connections/tiktok-callback",element:a.jsx(ut,{children:a.jsx(Z$t,{})})}),a.jsx(Te,{path:"/social-connections/google-callback",element:a.jsx(ut,{children:a.jsx(K$t,{})})}),a.jsx(Te,{path:"/admin/social-swag",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(J4t,{})})}),a.jsx(Te,{path:"/admin/social-swag-2",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(eBt,{})})}),a.jsx(Te,{path:"/community",element:a.jsx(ut,{children:a.jsx(z4t,{})})}),a.jsx(Te,{path:"/support",element:a.jsx(ut,{children:a.jsx($4t,{})})}),a.jsx(Te,{path:"/admin/community",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(tBt,{})})}),a.jsx(Te,{path:"/admin/support-tickets",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(sBt,{})})}),a.jsx(Te,{path:"/admin/email-templates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(aBt,{})})}),a.jsx(Te,{path:"/admin/agent-email-templates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(oBt,{})})}),a.jsx(Te,{path:"/admin/analytics",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(rBt,{})})}),a.jsx(Te,{path:"/admin/brokerage-resources",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(nBt,{})})}),a.jsx(Te,{path:"/admin/dashboard-management",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(iBt,{})})}),a.jsx(Te,{path:"/brokerage/dashboard",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(lBt,{})})}),a.jsx(Te,{path:"/brokerage/teams",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(gUt,{})})}),a.jsx(Te,{path:"/brokerage/recruiting",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(Uzt,{})})}),a.jsx(Te,{path:"/brokerage/onboarding",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(Vzt,{})})}),a.jsx(Te,{path:"/brokerage/commission-plans",element:a.jsx(ut,{children:a.jsx(Yzt,{})})}),a.jsx(Te,{path:"/brokerage/operations",element:a.jsx(ut,{children:a.jsx(Gzt,{})})}),a.jsx(Te,{path:"/brokerage/website",element:a.jsx(ut,{children:a.jsx(Kzt,{})})}),a.jsx(Te,{path:"/websites",element:a.jsx(ut,{children:a.jsx(Hzt,{})})}),a.jsx(Te,{path:"/team/website",element:a.jsx(ut,{children:a.jsx(Wzt,{})})}),a.jsx(Te,{path:"/brokerage/transactions",element:a.jsx(ut,{children:a.jsx(qzt,{})})}),a.jsx(Te,{path:"/team",element:a.jsx(ut,{children:a.jsx(xUt,{})})}),a.jsx(Te,{path:"/my-team",element:a.jsx(ut,{children:a.jsx(yUt,{})})}),a.jsx(Te,{path:"/my-brokerage",element:a.jsx(ut,{children:a.jsx(cBt,{})})}),a.jsx(Te,{path:"/brokerage/help-board",element:a.jsx(ut,{children:a.jsx(hBt,{})})}),a.jsx(Te,{path:"/brokerage/help-board/new",element:a.jsx(ut,{children:a.jsx(fBt,{})})}),a.jsx(Te,{path:"/brokerage/help-board/:id",element:a.jsx(ut,{children:a.jsx(mBt,{})})}),a.jsx(Te,{path:"/brokerage-content",element:a.jsx(ut,{children:a.jsx(uBt,{})})}),a.jsx(Te,{path:"/brokerage-content/:contentId",element:a.jsx(ut,{children:a.jsx(dBt,{})})}),a.jsx(Te,{path:"/brokerage-resources",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(U4t,{})})}),a.jsx(Te,{path:"/brokerage-resources/:resourceId",element:a.jsx(ut,{requireBrokerageManager:!0,children:a.jsx(V4t,{})})}),a.jsx(Te,{path:"/newsletters",element:a.jsx(ut,{children:a.jsx(pBt,{})})}),a.jsx(Te,{path:"/newsletters/:id",element:a.jsx(ut,{children:a.jsx(gBt,{})})}),a.jsx(Te,{path:"/wishlist",element:a.jsx(ut,{children:a.jsx(bBt,{})})}),a.jsx(Te,{path:"/wishlist/:itemId",element:a.jsx(ut,{children:a.jsx(wBt,{})})}),a.jsx(Te,{path:"/admin/wishlist",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(SBt,{})})}),a.jsx(Te,{path:"/admin/levelup-brief",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(TBt,{})})}),a.jsx(Te,{path:"/admin/boost-announcements",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(_Bt,{})})}),a.jsx(Te,{path:"/admin/broadcasts",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(xBt,{})})}),a.jsx(Te,{path:"/admin/newsletters",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(yBt,{})})}),a.jsx(Te,{path:"/admin/newsletter-graphics",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(vBt,{})})}),a.jsx(Te,{path:"/admin/additional-services",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(EBt,{})})}),a.jsx(Te,{path:"/admin/discounts",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(ABt,{})})}),a.jsx(Te,{path:"/admin/subscriptions",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(jBt,{})})}),a.jsx(Te,{path:"/admin/instagram-gift-emails",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(kBt,{})})}),a.jsx(Te,{path:"/admin/referrals",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(CBt,{})})}),a.jsx(Te,{path:"/admin/prospector",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(zzt,{})})}),a.jsx(Te,{path:"/admin/recruiting",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx($zt,{})})}),a.jsx(Te,{path:"/admin/beta/social-post-generator",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Xzt,{})})}),a.jsx(Te,{path:"/admin/credits",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(y$t,{})})})}),a.jsx(Te,{path:"/admin/cleanup",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(x$t,{})})})}),a.jsx(Te,{path:"/admin/beta/postcard-manager",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(d$t,{})})})}),a.jsx(Te,{path:"/admin/mail-studio/templates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(h$t,{})})})}),a.jsx(Te,{path:"/admin/beta/homereel",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(f$t,{})})})}),a.jsx(Te,{path:"/admin/beta/boost",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(g$t,{})})})}),a.jsx(Te,{path:"/admin/video-lab",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(p$t,{})})})}),a.jsx(Te,{path:"/admin/music-videos",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(m$t,{})})})}),a.jsx(Te,{path:"/admin/lms",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Qzt,{})})}),a.jsx(Te,{path:"/admin/lms/stats",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(e$t,{})})}),a.jsx(Te,{path:"/admin/lms/:courseId",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Jzt,{})})}),a.jsx(Te,{path:"/levelup-u",element:a.jsx(ut,{children:a.jsx(t$t,{})})}),a.jsx(Te,{path:"/levelup-u/:courseId",element:a.jsx(ut,{children:a.jsx(r$t,{})})}),a.jsx(Te,{path:"/admin/brokerage-content-activity",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Zzt,{})})}),a.jsx(Te,{path:"/admin/onboarding-checklist",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(IBt,{})})}),a.jsx(Te,{path:"/admin/marketplace",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(jzt,{})})}),a.jsx(Te,{path:"/admin/agent-points",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Ezt,{})})}),a.jsx(Te,{path:"/admin/reward-store",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(kzt,{})})}),a.jsx(Te,{path:"/admin/integrations",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Czt,{})})}),a.jsx(Te,{path:"/admin/mcp-updates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Pzt,{})})}),a.jsx(Te,{path:"/help/refresh-mcp-tools",element:a.jsx(ut,{children:a.jsx(Rzt,{})})}),a.jsx(Te,{path:"/admin/social-autopilot",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Nzt,{})})}),a.jsx(Te,{path:"/admin/social-connections",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Izt,{})})}),a.jsx(Te,{path:"/admin/integrations/callback",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Bzt,{})})}),a.jsx(Te,{path:"/admin/email-compliance",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(VUt,{})})})}),a.jsx(Te,{path:"/admin/email-campaigns",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(UUt,{})})})}),a.jsx(Te,{path:"/admin/email-campaigns/templates",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(HUt,{})})})}),a.jsx(Te,{path:"/email-campaigns/templates",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(WUt,{})})})}),a.jsx(Te,{path:"/admin/email-campaigns/new",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(qUt,{})})})}),a.jsx(Te,{path:"/admin/email-campaigns/:id",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(GUt,{})})})}),a.jsx(Te,{path:"/reward-store",element:a.jsx(ut,{children:a.jsx(r6t,{})})}),a.jsx(Te,{path:"/refer-friends",element:a.jsx(ut,{children:a.jsx(n6t,{})})}),a.jsx(Te,{path:"/additional-services",element:a.jsx(ut,{children:a.jsx(PBt,{})})}),a.jsx(Te,{path:"/additional-services/:serviceId",element:a.jsx(ut,{children:a.jsx(RBt,{})})}),a.jsx(Te,{path:"/ai-toolkit",element:a.jsx(ut,{children:a.jsx(LBt,{})})}),a.jsx(Te,{path:"/ask-ai",element:a.jsx(ut,{children:a.jsx(DBt,{})})}),a.jsx(Te,{path:"/mission-control",element:a.jsx(ut,{children:a.jsx(MBt,{})})}),a.jsx(Te,{path:"/mission-control/contacts",element:a.jsx(ut,{children:a.jsx(OBt,{})})}),a.jsx(Te,{path:"/mission-control/sphere-map",element:a.jsx(ut,{children:a.jsx(w$t,{})})}),a.jsx(Te,{path:"/mission-control/property-intelligence",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(S$t,{})})}),a.jsx(Te,{path:"/mission-control/contacts/:contactId",element:a.jsx(ut,{children:a.jsx(FBt,{})})}),a.jsx(Te,{path:"/mission-control/sent-emails",element:a.jsx(ut,{children:a.jsx(BBt,{})})}),a.jsx(Te,{path:"/mission-control/plans",element:a.jsx(ut,{children:a.jsx(zBt,{})})}),a.jsx(Te,{path:"/mission-control/cma",element:a.jsx(ut,{children:a.jsx($Bt,{})})}),a.jsx(Te,{path:"/mission-control/cma/:id",element:a.jsx(ut,{children:a.jsx(UBt,{})})}),a.jsx(Te,{path:"/cma/:token",element:a.jsx(GBt,{})}),a.jsx(Te,{path:"/apps/listing-presentation-studio",element:a.jsx(ut,{children:a.jsx(VBt,{})})}),a.jsx(Te,{path:"/apps/listing-presentation-studio/:id",element:a.jsx(ut,{children:a.jsx(qBt,{})})}),a.jsx(Te,{path:"/apps/listing-revival",element:a.jsx(ut,{children:a.jsx(sUt,{})})}),a.jsx(Te,{path:"/apps/listing-revival/new",element:a.jsx(ut,{children:a.jsx(aUt,{})})}),a.jsx(Te,{path:"/apps/listing-revival/campaigns/:id",element:a.jsx(ut,{children:a.jsx(oUt,{})})}),a.jsx(Te,{path:"/staged/:token",element:a.jsx(l$t,{})}),a.jsx(Te,{path:"/apps/staging-studio",element:a.jsx(ut,{children:a.jsx(Ez,{children:a.jsx(i$t,{})})})}),a.jsx(Te,{path:"/apps/staging-studio/library",element:a.jsx(ut,{children:a.jsx(Ez,{children:a.jsx(s$t,{})})})}),a.jsx(Te,{path:"/apps/staging-studio/credits",element:a.jsx(ut,{children:a.jsx(Ez,{children:a.jsx(a$t,{})})})}),a.jsx(Te,{path:"/apps/fsbo-breakthrough",element:a.jsx(ut,{children:a.jsx(lUt,{})})}),a.jsx(Te,{path:"/apps/fsbo-breakthrough/new",element:a.jsx(ut,{children:a.jsx(cUt,{})})}),a.jsx(Te,{path:"/apps/reviews",element:a.jsx(ut,{children:a.jsx(y6t,{})})}),a.jsx(Te,{path:"/apps/fsbo-breakthrough/campaigns/:id",element:a.jsx(ut,{children:a.jsx(uUt,{})})}),a.jsx(Te,{path:"/admin/fsbo-breakthrough",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(fUt,{})})}),a.jsx(Te,{path:"/mission-control/listing-presentations",element:a.jsx(li,{to:"/apps/listing-presentation-studio",replace:!0})}),a.jsx(Te,{path:"/mission-control/popbys",element:a.jsx(ut,{children:a.jsx(HBt,{})})}),a.jsx(Te,{path:"/mission-control/popbys/map",element:a.jsx(ut,{children:a.jsx(b$t,{})})}),a.jsx(Te,{path:"/admin/notification-settings",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Lzt,{})})}),a.jsx(Te,{path:"/admin/agent-os",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(NBt,{})})}),a.jsx(Te,{path:"/mission-control/listings",element:a.jsx(ut,{children:a.jsx(WBt,{})})}),a.jsx(Te,{path:"/mission-control/listing-studio",element:a.jsx(ut,{children:a.jsx(E6t,{})})}),a.jsx(Te,{path:"/mission-control/listings/new",element:a.jsx(ut,{children:a.jsx(a4t,{})})}),a.jsx(Te,{path:"/mission-control/listings/new/residential",element:a.jsx(ut,{children:a.jsx(pue,{})})}),a.jsx(Te,{path:"/mission-control/listings/new/commercial",element:a.jsx(ut,{children:a.jsx(hue,{})})}),a.jsx(Te,{path:"/mission-control/listings/:listingId/commercial",element:a.jsx(ut,{children:a.jsx(o4t,{})})}),a.jsx(Te,{path:"/mission-control/listings/:listingId/commercial/edit",element:a.jsx(ut,{children:a.jsx(hue,{})})}),a.jsx(Te,{path:"/mission-control/listings/:listingId",element:a.jsx(ut,{children:a.jsx(KBt,{})})}),a.jsx(Te,{path:"/mission-control/listings/:listingId/edit",element:a.jsx(ut,{children:a.jsx(pue,{})})}),a.jsx(Te,{path:"/mission-control/listings/:listingId/customize",element:a.jsx(ut,{children:a.jsx(YBt,{})})}),a.jsx(Te,{path:"/admin/listing-exchange",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(_zt,{})})}),a.jsx(Te,{path:"/admin/listing-leads",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(vzt,{})})}),a.jsx(Te,{path:"/admin/public-site-leads",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(bzt,{})})}),a.jsx(Te,{path:"/mission-control/lenders",element:a.jsx(ut,{children:a.jsx(w6t,{})})}),a.jsx(Te,{path:"/mission-control/pipeline",element:a.jsx(ut,{children:a.jsx(rzt,{})})}),a.jsx(Te,{path:"/mission-control/forms",element:a.jsx(ut,{children:a.jsx(nzt,{})})}),a.jsx(Te,{path:"/mission-control/tasks",element:a.jsx(ut,{children:a.jsx(JNt,{})})}),a.jsx(Te,{path:"/mission-control/transactions",element:a.jsx(ut,{children:a.jsx(izt,{})})}),a.jsx(Te,{path:"/mission-control/client-portals",element:a.jsx(ut,{children:a.jsx(czt,{})})}),a.jsx(Te,{path:"/mission-control/client-portals/:portalId",element:a.jsx(ut,{children:a.jsx(uzt,{})})}),a.jsx(Te,{path:"/mission-control/portal-referrals",element:a.jsx(ut,{children:a.jsx(szt,{})})}),a.jsx(Te,{path:"/mission-control/vendors",element:a.jsx(ut,{children:a.jsx(azt,{})})}),a.jsx(Te,{path:"/brokerage/forms",element:a.jsx(ut,{children:a.jsx(ozt,{})})}),a.jsx(Te,{path:"/brokerage/vendors",element:a.jsx(ut,{children:a.jsx(lzt,{})})}),a.jsx(Te,{path:"/mission-control/my-card",element:a.jsx(ut,{children:a.jsx(dzt,{})})}),a.jsx(Te,{path:"/mission-control/integrations",element:a.jsx(ut,{children:a.jsx(hzt,{})})}),a.jsx(Te,{path:"/mission-control/browser-extension",element:a.jsx(ut,{children:a.jsx(fzt,{})})}),a.jsx(Te,{path:"/mission-control/integrations/gmail/callback",element:a.jsx(ut,{children:a.jsx(mzt,{})})}),a.jsx(Te,{path:"/mission-control/integrations/canva/callback",element:a.jsx(pzt,{})}),a.jsx(Te,{path:"/mission-control/integrations/meta/callback",element:a.jsx(ut,{children:a.jsx(gzt,{})})}),a.jsx(Te,{path:"/mission-control/scorecard",element:a.jsx(ut,{children:a.jsx(KCt,{})})}),a.jsx(Te,{path:"/admin/scorecard",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(yzt,{})})}),a.jsx(Te,{path:"/admin/agent-activation",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(xzt,{})})}),a.jsx(Te,{path:"/admin/scorecard/:userId",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(yue,{})})}),a.jsx(Te,{path:"/mission-control/scorecard/:userId",element:a.jsx(ut,{children:a.jsx(yue,{})})}),a.jsx(Te,{path:"/mission-control/relationship-scorecard",element:a.jsx(ut,{children:a.jsx(OUt,{})})}),a.jsx(Te,{path:"/mission-control/sphere-gaps",element:a.jsx(ut,{children:a.jsx(FUt,{})})}),a.jsx(Te,{path:"/mission-control/signals",element:a.jsx(ut,{children:a.jsx(BUt,{})})}),a.jsx(Te,{path:"/mission-control/website-activity",element:a.jsx(ut,{children:a.jsx($Ut,{})})}),a.jsx(Te,{path:"/mission-control/connect-page",element:a.jsx(ut,{children:a.jsx(zUt,{})})}),a.jsx(Te,{path:"/admin/membership-reviews",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(wzt,{})})}),a.jsx(Te,{path:"/admin/lead-notifications",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Szt,{})})}),a.jsx(Te,{path:"/admin/weekly-digest",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Tzt,{})})}),a.jsx(Te,{path:"/studio/join/:roomId",element:a.jsx(I.Suspense,{fallback:null,children:a.jsx(ezt,{})})}),a.jsx(Te,{path:"/main-stage",element:a.jsx(I.Suspense,{fallback:null,children:a.jsx(gue,{})})}),a.jsx(Te,{path:"/main-stage/e/:eventId",element:a.jsx(I.Suspense,{fallback:null,children:a.jsx(gue,{})})}),a.jsx(Te,{path:"/admin/main-stage",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(QBt,{})})})}),a.jsx(Te,{path:"/admin/studio-kits",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(JBt,{})})})}),a.jsx(Te,{path:"/video-studio",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(XBt,{})})})}),a.jsx(Te,{path:"/mission-control/video/record",element:a.jsx(ZBt,{})}),a.jsx(Te,{path:"/mission-control/video-library",element:a.jsx(ut,{children:a.jsx(tzt,{})})}),a.jsx(Te,{path:"/my-partnership",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(C$t,{})})})}),a.jsx(Te,{path:"/upgrade/:featureKey",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(I$t,{})})})}),a.jsx(Te,{path:"/coaching/onboarding",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(N$t,{})})})}),a.jsx(Te,{path:"/admin/lenders",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(S6t,{})})})}),a.jsx(Te,{path:"/admin/partnerships",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:null,children:a.jsx(k$t,{})})})}),a.jsx(Te,{path:"/website-apps",element:a.jsx(ut,{children:a.jsx(IUt,{})})}),a.jsx(Te,{path:"/get-my-website",element:a.jsx(ut,{children:a.jsx(NUt,{})})}),a.jsx(Te,{path:"/need-a-website",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(O$t,{})})})}),a.jsx(Te,{path:"/website-apps/video_greeter",element:a.jsx(ut,{children:a.jsx(PUt,{})})}),a.jsx(Te,{path:"/website-apps/exit_intent",element:a.jsx(ut,{children:a.jsx(RUt,{})})}),a.jsx(Te,{path:"/website-apps/lead_magnet",element:a.jsx(ut,{children:a.jsx(LUt,{})})}),a.jsx(Te,{path:"/embed/video-greeter/:slug",element:a.jsx(DUt,{})}),a.jsx(Te,{path:"/embed/lead-magnet/:slug",element:a.jsx(MUt,{})}),a.jsx(Te,{path:"/marketplace",element:a.jsx(ut,{children:a.jsx(rPt,{})})}),a.jsx(Te,{path:"/marketplace/:productId",element:a.jsx(ut,{children:a.jsx(X$t,{})})}),a.jsx(Te,{path:"/marketplace/cart",element:a.jsx(ut,{children:a.jsx(Q$t,{})})}),a.jsx(Te,{path:"/marketplace/orders",element:a.jsx(ut,{children:a.jsx(J$t,{})})}),a.jsx(Te,{path:"/marketplace/orders/:orderId",element:a.jsx(ut,{children:a.jsx(e6t,{})})}),a.jsx(Te,{path:"/marketplace/success",element:a.jsx(ut,{children:a.jsx(t6t,{})})}),a.jsx(Te,{path:"/admin/agent-cards",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Azt,{})})}),a.jsx(Te,{path:"/admin/presentation-analytics",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Dzt,{})})}),a.jsx(Te,{path:"/admin/listing-presentation-studio",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Mzt,{})})}),a.jsx(Te,{path:"/admin/listing-revival",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Ozt,{})})}),a.jsx(Te,{path:"/admin/contact-finder",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(u$t,{})})}),a.jsx(Te,{path:"/admin/staging-studio",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(c$t,{})})}),a.jsx(Te,{path:"/admin/guest-book-analytics",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(Fzt,{})})}),a.jsx(Te,{path:"/mission-control/smart-drips",element:a.jsx(ut,{children:a.jsx(j6t,{})})}),a.jsx(Te,{path:"/mission-control/mail-studio",element:a.jsx(v$t,{})}),a.jsx(Te,{path:"/mission-control/direct-mail",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:a.jsx(_$t,{})})})}),a.jsx(Te,{path:"/mission-control/presentations",element:a.jsx(ut,{children:a.jsx(i6t,{})})}),a.jsx(Te,{path:"/mission-control/presentations/new",element:a.jsx(ut,{children:a.jsx(_ue,{})})}),a.jsx(Te,{path:"/mission-control/presentations/:id",element:a.jsx(ut,{children:a.jsx(_ue,{})})}),a.jsx(Te,{path:"/mission-control/guest-book",element:a.jsx(ut,{children:a.jsx(a6t,{})})}),a.jsx(Te,{path:"/mission-control/guest-book/live/:id",element:a.jsx(ut,{children:a.jsx(T$t,{})})}),a.jsx(Te,{path:"/guestbook/:slug",element:a.jsx(o6t,{})}),a.jsx(Te,{path:"/review/:token",element:a.jsx(m6t,{})}),a.jsx(Te,{path:"/reviews/:slug/new",element:a.jsx(g6t,{})}),a.jsx(Te,{path:"/reviews/:slug",element:a.jsx(p6t,{})}),a.jsx(Te,{path:"/rsvp/:slug",element:a.jsx(l6t,{})}),a.jsx(Te,{path:"/resources/:slug",element:a.jsx(c6t,{})}),a.jsx(Te,{path:"/sign/:token",element:a.jsx(u6t,{})}),a.jsx(Te,{path:"/blog",element:a.jsx(d6t,{})}),a.jsx(Te,{path:"/blog/:slug",element:a.jsx(h6t,{})}),a.jsx(Te,{path:"/mission-control/card-studio",element:a.jsx(ut,{children:a.jsx(T6t,{})})}),a.jsx(Te,{path:"/mission-control/scheduler",element:a.jsx(ut,{children:a.jsx(_Ut,{})})}),a.jsx(Te,{path:"/mission-control/calendar",element:a.jsx(ut,{children:a.jsx(vUt,{})})}),a.jsx(Te,{path:"/c/:shareToken",element:a.jsx(A6t,{})}),a.jsx(Te,{path:"/book/:slug",element:a.jsx(bUt,{})}),a.jsx(Te,{path:"/booking/manage/:token",element:a.jsx(wUt,{})}),a.jsx(Te,{path:"/page/:slug",element:a.jsx(CUt,{})}),a.jsx(Te,{path:"/buyer-match/:slug",element:a.jsx(AUt,{})}),a.jsx(Te,{path:"/mission-control/buyer-match",element:a.jsx(ut,{children:a.jsx(TUt,{})})}),a.jsx(Te,{path:"/mission-control/buyer-match/:campaignId",element:a.jsx(ut,{children:a.jsx(EUt,{})})}),a.jsx(Te,{path:"/mission-control/landing-pages",element:a.jsx(ut,{children:a.jsx(SUt,{})})}),a.jsx(Te,{path:"/mission-control/landing-pages/defaults",element:a.jsx(ut,{children:a.jsx(kUt,{})})}),a.jsx(Te,{path:"/mission-control/landing-pages/:pageId",element:a.jsx(ut,{children:a.jsx(jUt,{})})}),a.jsx(Te,{path:"/my-website/:siteId/edit",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(xue,{})})})}),a.jsx(Te,{path:"/my-website/mls-listings",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(B$t,{})})})}),a.jsx(Te,{path:"/my-website/mls-listings/:mlsId",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(z$t,{})})})}),a.jsx(Te,{path:"/my-website/market-report",element:a.jsx(ut,{children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx($$t,{})})})}),a.jsx(Te,{path:"/admin/lead-sites",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(E$t,{})})})}),a.jsx(Te,{path:"/admin/lead-sites/themes",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(A$t,{})})})}),a.jsx(Te,{path:"/admin/lead-sites/offers",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(j$t,{})})})}),a.jsx(Te,{path:"/admin/lead-sites/offers/:brokerageId",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(P$t,{})})})}),a.jsx(Te,{path:"/admin/lead-sites/:siteId/edit",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(xue,{})})})}),a.jsx(Te,{path:"/admin/mls-feeds",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(R$t,{})})})}),a.jsx(Te,{path:"/admin/lead-site-analytics",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(L$t,{})})})}),a.jsx(Te,{path:"/admin/website-interests",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(D$t,{})})})}),a.jsx(Te,{path:"/admin/website-requests",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(M$t,{})})})}),a.jsx(Te,{path:"/admin/website-orders",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(KUt,{})})})}),a.jsx(Te,{path:"/admin/mls-fee-tracker",element:a.jsx(ut,{requireAdmin:!0,children:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(F$t,{})})})}),a.jsx(Te,{path:"/m/*",element:a.jsx(I.Suspense,{fallback:a.jsx("div",{className:"flex min-h-screen items-center justify-center",children:a.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:a.jsx(n$t,{})})}),a.jsx(Te,{path:"*",element:a.jsx(h2e,{})})]})})]})})})})})]})})});function uVt(){const t=Bi(),e=t.pathname.replace(/^\/listing\//,"");return a.jsx(li,{to:`/public/listing/${e}${t.search}`,replace:!0})}const hje=window.location.hostname;/(\.lovable\.app|\.lovableproject\.com)$/.test(hje)&&/[?&]authorization_id=/.test(window.location.search)&&window.location.replace(`https://dashboard.relevelup.com/oauth-connect${window.location.search}`);if(hje==="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 tG="levelup:chunk-reload",dVt=t=>!!t&&/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module/i.test(t),DK=t=>{dVt(t)&&(sessionStorage.getItem(tG)||(sessionStorage.setItem(tG,"1"),window.location.reload()))};window.addEventListener("vite:preloadError",t=>{t.preventDefault(),DK("Failed to fetch dynamically imported module")});window.addEventListener("error",t=>DK(t.message));window.addEventListener("unhandledrejection",t=>{var e;return DK((e=t.reason)==null?void 0:e.message)});window.setTimeout(()=>sessionStorage.removeItem(tG),15e3);Zhe(document.getElementById("root")).render(a.jsx(cVt,{}));export{G1 as $,kfe as A,go as B,cve as C,Ire as D,iv as E,of as F,Wn as G,Wo as H,$r as I,Mr as J,wC as K,rDe as L,qs as M,_x as N,Ji as O,oD as P,OD as Q,Gt as R,hd as S,NS as T,Gn as U,px as V,id as W,sd as X,Mj as Y,Ru as Z,si as _,_a as a,tDe as a$,qLe as a0,xs as a1,fU as a2,PS as a3,ko as a4,dD as a5,ra as a6,wj as a7,ul as a8,ai as a9,bd as aA,lD as aB,$ye as aC,tu as aD,Cl as aE,tx as aF,_C as aG,Jh as aH,DA as aI,Rl as aJ,E3 as aK,yd as aL,xm as aM,vd as aN,xVt as aO,Fye as aP,$B as aQ,F_ as aR,Nfe as aS,sr as aT,Ww as aU,jp as aV,WA as aW,fDe as aX,yU as aY,rc as aZ,cD as a_,CO as aa,Sj as ab,im as ac,Lfe as ad,fd as ae,md as af,pd as ag,us as ah,q0e as ai,bm as aj,Nr as ak,Yy as al,V7 as am,N3 as an,kp as ao,yo as ap,aDe as aq,l9 as ar,cm as as,Uy as at,sm as au,Ni as av,io as aw,Ua as ax,ml as ay,Ko as az,aa as b,M8t as b$,LO as b0,r9 as b1,YS as b2,Ds as b3,mDe as b4,Pfe as b5,fee as b6,o9 as b7,gd as b8,uD as b9,mU as bA,P1 as bB,ZLe as bC,yDe as bD,xU as bE,knt as bF,IO as bG,hU as bH,eC as bI,m7 as bJ,T7 as bK,sl as bL,zo as bM,$o as bN,Uo as bO,Qh as bP,p7 as bQ,gDe as bR,La as bS,Mfe as bT,qfe as bU,jDe as bV,TVt as bW,Bi as bX,q8t as bY,G8t as bZ,W8t as b_,ru as ba,hie as bb,Tj as bc,_ee as bd,Ore as be,Lwe as bf,Cnt as bg,Int as bh,Nnt as bi,Pnt as bj,Rnt as bk,n9 as bl,PO as bm,R1 as bn,rf as bo,Jk as bp,IDe as bq,GLe as br,um as bs,lr as bt,kr as bu,t9 as bv,vDe as bw,K4e as bx,a3 as by,u3 as bz,Nre as c,oUe as c$,B8t as c0,H8t as c1,K8t as c2,Hme as c3,yVt as c4,g9 as c5,y9 as c6,_9 as c7,v9 as c8,x9 as c9,nv as cA,NZe as cB,es as cC,nXe as cD,eXe as cE,WLe as cF,zfe as cG,NDe as cH,CH as cI,IH as cJ,Yj as cK,Hl as cL,NH as cM,Wl as cN,HLe as cO,wc as cP,DGt as cQ,mGt as cR,RGt as cS,nKe as cT,vpe as cU,DFe as cV,MFe as cW,bpe as cX,Cfe as cY,pDe as cZ,i9 as c_,w9 as ca,b9 as cb,dZe as cc,O8t as cd,X8t as ce,Z8t as cf,$8t as cg,U8t as ch,hZe as ci,hee as cj,Q8t as ck,Y8t as cl,z8t as cm,F8t as cn,Az as co,V8t as cp,Rfe as cq,Bwe as cr,PH as cs,Sm as ct,Xe as cu,Yp as cv,rn as cw,vc as cx,hve as cy,CS as cz,fZe as d,pC as d$,aD as d0,j7 as d1,On as d2,Gi as d3,iit as d4,zwe as d5,Wnt as d6,JWe as d7,L7e as d8,Ts as d9,V1 as dA,QLe as dB,EVt as dC,pee as dD,Bfe as dE,TDe as dF,t7 as dG,UVt as dH,JLe as dI,l_ as dJ,Te as dK,li as dL,pVt as dM,nDe as dN,xee as dO,Zk as dP,Yo as dQ,dd as dR,Kn as dS,av as dT,Or as dU,Dl as dV,pl as dW,Po as dX,Dfe as dY,k7 as dZ,mC as d_,Ys as da,Ofe as db,N1 as dc,Jhe as dd,iYe as de,hDe as df,Qk as dg,pU as dh,UA as di,vee as dj,Yhe as dk,Bye as dl,yYe as dm,s9 as dn,oV as dp,Uye as dq,gUe as dr,r7 as ds,qye as dt,Gye as du,j8t as dv,k8t as dw,I8t as dx,N8t as dy,A8t as dz,va as e,PCt as e$,KLe as e0,qS as e1,Eu as e2,C_e as e3,I_e as e4,HEe as e5,WEe as e6,bL as e7,wL as e8,KA as e9,rv as eA,GO as eB,HO as eC,qO as eD,dUe as eE,OVt as eF,YLe as eG,qVt as eH,E7e as eI,Vfe as eJ,u9 as eK,iDe as eL,Age as eM,EDe as eN,zj as eO,$j as eP,Uj as eQ,Vj as eR,q1 as eS,ky as eT,R8t as eU,ULe as eV,dU as eW,Tx as eX,GS as eY,xV as eZ,C8 as e_,l2e as ea,Ffe as eb,Jl as ec,RWe as ed,Z0e as ee,gU as ef,Ql as eg,ds as eh,QFe as ei,Yee as ej,bVt as ek,wVt as el,f5e as em,Fe as en,VLe as eo,lDe as ep,xDe as eq,sDe as er,VS as es,G9 as et,H9 as eu,kS as ev,Dj as ew,Oye as ex,mx as ey,lC as ez,oa as f,Ife as f$,zF as f0,$F as f1,Vh as f2,fv as f3,RCt as f4,tg as f5,pF as f6,_i as f7,Oi as f8,NW as f9,gGt as fA,LGt as fB,NGt as fC,ait as fD,PGt as fE,rit as fF,vGt as fG,jH as fH,Hye as fI,_Ue as fJ,Hc as fK,Kd as fL,Hnt as fM,iGt as fN,sGt as fO,Y1 as fP,bDe as fQ,Ba as fR,wit as fS,yGt as fT,_Gt as fU,xGt as fV,RO as fW,XEe as fX,Jqt as fY,Awe as fZ,pGt as f_,nh as fa,$s as fb,fi as fc,X8 as fd,Wp as fe,oy as ff,EF as fg,Fi as fh,OGt as fi,qy as fj,Ip as fk,Xl as fl,FGt as fm,NC as fn,kF as fo,zEe as fp,LAt as fq,eDe as fr,UB as fs,nit as ft,sit as fu,Bj as fv,L7 as fw,YCt as fx,$W as fy,qF as fz,fn as g,_De as g$,Qqt as g0,wGt as g1,CGt as g2,bGt as g3,IGt as g4,SGt as g5,EGt as g6,AGt as g7,jGt as g8,kGt as g9,c8t as gA,lnt as gB,vA as gC,Zqt as gD,Xqt as gE,eGt as gF,KGt as gG,ZGt as gH,YGt as gI,QGt as gJ,XGt as gK,WGt as gL,kH as gM,BGt as gN,zGt as gO,$Gt as gP,JGt as gQ,HGt as gR,axe as gS,tGt as gT,rGt as gU,nGt as gV,mee as gW,XLe as gX,oDe as gY,IS as gZ,dDe as g_,TGt as ga,L9t as gb,t8 as gc,vnt as gd,Yh as ge,oZe as gf,e9t as gg,rIt as gh,nIt as gi,VGt as gj,t9t as gk,r9t as gl,qGt as gm,pUe as gn,NO as go,cDe as gp,uDe as gq,Yce as gr,kDe as gs,SA as gt,CDe as gu,C8t as gv,P8t as gw,iA as gx,GGt as gy,Bqt as gz,SDe as h,b9t as h$,wDe as h0,$fe as h1,Ufe as h2,ADe as h3,c9 as h4,$Le as h5,aie as h6,f8t as h7,d8t as h8,m8t as h9,aqt as hA,oqt as hB,qZe as hC,aGt as hD,Mwe as hE,Jnt as hF,Znt as hG,Sit as hH,e1e as hI,GEe as hJ,KEe as hK,J8t as hL,ePt as hM,s9t as hN,a9t as hO,o9t as hP,tPt as hQ,c9t as hR,u9t as hS,d9t as hT,h9t as hU,f9t as hV,m9t as hW,p9t as hX,g9t as hY,y9t as hZ,x9t as h_,KVt as ha,p8t as hb,g8t as hc,y8t as hd,x8t as he,WVt as hf,b7e as hg,Uqt as hh,Hqt as hi,qqt as hj,Gqt as hk,oie as hl,qrt as hm,Vqt as hn,zqt as ho,$qt as hp,Kqt as hq,Wrt as hr,Krt as hs,Wqt as ht,eqt as hu,tqt as hv,rqt as hw,nqt as hx,iqt as hy,sqt as hz,zt as i,l9t as i$,w9t as i0,i9t as i1,n9t as i2,xz as i3,th as i4,w8t as i5,v8t as i6,S8t as i7,u8t as i8,r8t as i9,lGt as iA,oGt as iB,uGt as iC,fGt as iD,FCt as iE,cqt as iF,uqt as iG,Lqt as iH,Dqt as iI,Mqt as iJ,twe as iK,fr as iL,C9t as iM,FPt as iN,YW as iO,b2e as iP,P9t as iQ,A9t as iR,j9t as iS,k9t as iT,dLt as iU,e7 as iV,$Vt as iW,cUe as iX,uUe as iY,wbe as iZ,efe as i_,h8t as ia,YVt as ib,ZVt as ic,EEe as id,_8t as ie,b8t as ig,l8t as ih,i8t as ii,s8t as ij,n8t as ik,a8t as il,o8t as im,e8t as io,t8t as ip,XVt as iq,QVt as ir,JVt as is,iKe as it,LUe as iu,JKe as iv,See as iw,VVt as ix,uYe as iy,cGt as iz,a as j,$9t as j$,N_e as j0,_9t as j1,v9t as j2,S9t as j3,T9t as j4,eYe as j5,oXe as j6,mqt as j7,gqt as j8,yqt as j9,Wr as jA,IC as jB,UGt as jC,tj as jD,HNt as jE,X0e as jF,PFt as jG,MFt as jH,BFt as jI,Ej as jJ,wPt as jK,D$ as jL,E9t as jM,ax as jN,D9t as jO,a1 as jP,R9t as jQ,GF as jR,F9t as jS,TRt as jT,B9t as jU,XW as jV,O9t as jW,I9t as jX,hT as jY,JW as jZ,KPt as j_,xqt as ja,_qt as jb,vqt as jc,bqt as jd,Aqt as je,wqt as jf,Sqt as jg,Tqt as jh,Eqt as ji,jqt as jj,hqt as jk,pqt as jl,kqt as jm,Cqt as jn,Nqt as jo,Pqt as jp,Rqt as jq,lqt as jr,dqt as js,fqt as jt,pnt as ju,zC as jv,Cte as jw,C7 as jx,B0e as jy,SF as jz,dl as k,G9t as k0,q9t as k1,Nk as k2,N9t as k3,eG as k4,uje as k5,qFt as k6,M9t as k7,H9t as k8,W9t as k9,fLt as ka,mLt as kb,nK as kc,hLt as kd,x3 as ke,iRt as kf,z9t as kg,QW as kh,U9t as ki,V9t as kj,Cbe as kk,het as kl,KV as km,dGt as kn,hGt as ko,MVt as kp,Zy as l,mZe as m,Pre as n,Re as o,uve as p,mn as q,I as r,kV as s,gee as t,gr as u,yee as v,a9 as w,Ti as x,ic as y,Gs as z};