const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BoostCompanion-YI4EjfiH.js","assets/BoostPanel-fmCjFgFY.js","assets/useAssistantChat-BycJgEqC.js","assets/useSmartQueue-B8T-KcMU.js","assets/useBoostGift-C4UvezB8.js","assets/sun-C8ELpobv.js","assets/announcements-CHWMrHjI.js","assets/chatWidget-B9XylLn5.js","assets/use-reduced-motion-wTUWOPhs.js","assets/pause-DrQ2ZkFT.js","assets/bell-off-BmUH_Md9.js","assets/LeadSiteHome-CFRJ9uvN.js","assets/ExchangeListingsSection-DT0ubgsL.js","assets/useLeadSiteSearchSuggestions-SCOzSoDe.js","assets/hash-Bhp-zk3I.js","assets/map-DnDcuNkY.js","assets/AgentReviewsSection-BhXudNoD.js","assets/credits-PIR_bev7.js","assets/leadSiteAgent--GbV6IdE.js","assets/ScrollLivingHero-C2Ml7zCm.js","assets/StudioSite-B9elUeug.js","assets/StudioCanvas-CbW8wpLB.js","assets/waves-BhXcCWYY.js","assets/mountain-DGFREAMr.js","assets/trees-D_ObIEgK.js","assets/arrow-down-B-jLN4k5.js","assets/StudioCanvas-Bjx_P9aK.css","assets/ThSignatureSite-DnKAQpjx.js","assets/thSignatureHomepage-DPd-ASR7.js","assets/ThSignatureSite-C-UjGvUT.css","assets/LeadSiteLuxuryHome-DP1oiimc.js","assets/RecentSalesSnapshot-BGLvW2sv.js","assets/LeadSiteExchangeListings-BIu06A-u.js","assets/crown-CeQJju6S.js","assets/chart-line-jowzsNe3.js","assets/truck-CowiSakv.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-BomNTAQL.js","assets/use-in-view-BQojpGI3.js","assets/tree-pine-owMJWtfX.js","assets/LeadSiteSearch-DK0Syo0l.js","assets/ListingCardExtras-CnGZ1_PF.js","assets/bell-ring-CyNBi8kd.js","assets/useInfiniteQuery-DUa21drx.js","assets/LeadSiteMap-Dk-yESdX.js","assets/LeadSiteLuxurySearch-B9bC7ipQ.js","assets/LeadSiteListingDetail-DBbHemBU.js","assets/ListingVideoTour-Ih4gfkQs.js","assets/expand-CW0MzEdO.js","assets/car-BLG60TaT.js","assets/thermometer-DG2TlG_1.js","assets/snowflake-C4uQRUc9.js","assets/useListingVideos-jxN4V_1d.js","assets/LeadSiteLuxuryListingDetail-BViTDvEE.js","assets/LeadSiteAbout-dtgKcDkt.js","assets/LeadSiteLuxuryAbout-BbGRIRUP.js","assets/ExpReadySpotlight-DwpgW9i5.js","assets/LeadSiteBlog-BOL4CEji.js","assets/BlogBody-R-KcZr2z.js","assets/rss-BgIZcKP-.js","assets/LeadSiteCommunity-BH4FIXe4.js","assets/wine-DzwyucQd.js","assets/plane-BTEZOrUx.js","assets/music-cZ5VLWEe.js","assets/LeadSiteSellers-BjGUfoCM.js","assets/LeadSiteCityPage-aRggrAuB.js","assets/CityFaqSection-CyQltPFJ.js","assets/LeadSiteFocusPage-CQnPwMJo.js","assets/LeadSiteExpReady-OmYgFZiA.js","assets/paintbrush-D_gXW35M.js","assets/VacationRentals-VHXkDRnZ.js","assets/header-BMs9eMe5.js","assets/paw-print-CdfgFWW8.js","assets/OrgSiteLayout-Dw3y5hKz.js","assets/orgSiteBrand-DKMUe12O.js","assets/OrgSiteHome-gK8eqN4z.js","assets/OrgSiteAgents-C7UjlgyK.js","assets/OrgSitePages-Bp83fsjI.js","assets/OrgSiteListings-CaouRJp5.js","assets/CanvaSupport-BbOLPfsi.js","assets/unplug-z_3naLa2.js","assets/SmsOptIn-ZwmgL6RI.js","assets/signpost-CmJh3GYM.js","assets/ConnectChatGPT-DObyx0oG.js","assets/circle-check-big-DbDqJY4R.js","assets/LevelUpMCP-BIkIx2Lv.js","assets/terminal-eu8SVG82.js","assets/SubscriptionSuccess-CaeIQYP-.js","assets/index-D321xUZe.js","assets/SetupBrokerage-D1lMdPeq.js","assets/LeadEngine-CSUgA3nJ.js","assets/brokerageLeads-DvPZSd42.js","assets/pricing-Dng7hbfz.js","assets/inbox-Dw_Sav5a.js","assets/shuffle-CPsgza4P.js","assets/list-filter-Dv3XS3gX.js","assets/circle-user-round-s_KhFdT0.js","assets/InviteSignup-BYyuBBgt.js","assets/eye-off-DWpb0gUw.js","assets/CoachingHub-Cu5BCdcH.js","assets/useCoaching-Bm6x779p.js","assets/CoachAgentWorkspace-DUpgGXJh.js","assets/CoachingFiles-r_uxWtet.js","assets/folder-open-DahogGIZ.js","assets/save-E1Rx1uJy.js","assets/MyCoach-C68XkEfO.js","assets/CoachReviews-Byh2SMPB.js","assets/circle-x-BE4T5ByT.js","assets/AdminCoaching-HjnyPpPP.js","assets/arrow-left-right---t9j4hF.js","assets/user-minus-B4LoBmJ9.js","assets/CoachBilling-D2gN8zgr.js","assets/credit-card-CSSbV0Mm.js","assets/CoachSettings-DX_rNDTU.js","assets/GoogleCalendarCard-B9ZNDtPy.js","assets/calendar-off-iOQNRl46.js","assets/useCoachGoogleCalendar-D7HXyBZl.js","assets/link-CIkeJfhP.js","assets/Microsoft365Return-C09yIxLv.js","assets/useMicrosoft365-oVa9K59c.js","assets/freshAccessToken-Cn5clbQg.js","assets/CoachWaitlist-DnXGXsxv.js","assets/mail-check-m47jGYGR.js","assets/CoachProfile-uaF04VmK.js","assets/Trial-cigz1Vz9.js","assets/testimonial-avatar-5-DBoTqx4u.js","assets/TrialSuccess-7gKXznIo.js","assets/party-popper-DAMBUsJq.js","assets/LaborDaySale-B8OKRRWi.js","assets/OpenHouseInviteModal-BpVkVC-2.js","assets/infinity-CYp6rx3_.js","assets/workflow-DYQSjGnb.js","assets/EndOfYearSale-BW_2EW6K.js","assets/social-studio.png.asset-VjxYcX-_.js","assets/BlackFridaySale-arYrwbED.js","assets/bfSale-BqD9_8Gc.js","assets/timer-BaBulxi7.js","assets/badge-check-BVK6Q8E5.js","assets/BlackFridayBrokerage-7C3CH9z4.js","assets/IdxStart-g8ZYdd6L.js","assets/IdxOnboarding-CIw0-x9g.js","assets/BrokerageImports-BIdCm1Yq.js","assets/papaparse.min-DY6eFDZU.js","assets/BrokerageLaborDaySale-C649qiwj.js","assets/BrokerageSolutions-0jwia3-y.js","assets/receipt-BdoBZhvL.js","assets/banknote-cc1C_WkP.js","assets/pencil-line-CfHj11UE.js","assets/Upgrade-id75iVPA.js","assets/log-in-DcsowpZS.js","assets/InstagramGift-D6fVh-nN.js","assets/VideoShare-DyzYphz5.js","assets/VideoPageTemplates-BKzregxf.js","assets/message-circle-heart-B3lbUdDZ.js","assets/door-open-Dr5JxS6Y.js","assets/brain-C3DY1XbH.js","assets/coffee-DFWZ6GEL.js","assets/CommercialWizard-C9yz1xv2.js","assets/useListingExchange-CGQPs1NC.js","assets/useTeamListingAccess-BCOq-Nvp.js","assets/CommercialWorkspace-BTO4XLnx.js","assets/useListingDocuments-BRqpN3hI.js","assets/ListingPhotoGrid-DiMq2qDV.js","assets/sortable.esm-CXKUY1gx.js","assets/grip-vertical-8gjQF_7Q.js","assets/ShareListingDialog-JMURaKuJ.js","assets/EmailListingToSphereDialog-CN6z401q.js","assets/index-BT3oYnph.js","assets/separator-CFuxpKhG.js","assets/GmailComposeDialog-CMn0EnVW.js","assets/edgeError-BFfnuvfJ.js","assets/useMassEmailReady-DvrK1GNb.js","assets/useSenderIdentity-B2ooHa2z.js","assets/useVerifiedSenderCheck-Dzq01lne.js","assets/VerifySenderRequiredDialog-Dg_u6iYu.js","assets/useContactIntakePage-iRzDSaID.js","assets/ToContactAutocomplete-Brj8XsEv.js","assets/outlookSend-BA7GPPzj.js","assets/paperclip-dZhg6hGC.js","assets/ListingSocialDialog-Btv7FBKn.js","assets/useAgentBrand-CqZfr-JL.js","assets/listingGraphic-Dz02nV1B.js","assets/file-search-BNjOjDiY.js","assets/qr-code-DWJ2KJZW.js","assets/CommercialPitchPreview-D2mEHCIv.js","assets/PublicLiveEvent-BwxcKwca.js","assets/pin-Yomy_XYN.js","assets/arrow-up-DxCCUcxC.js","assets/useLiveEngagement-SibGYzxQ.js","assets/sparkle-CxSkUUOB.js","assets/LiveEvents-BrI8aeGa.js","assets/AdminPageHeader-D36cEzTG.js","assets/useLiveEvents-Bd1NP2Vb.js","assets/image-plus-C0ivqY7q.js","assets/LiveEventConsole-BQ9Pi4fc.js","assets/mouse-pointer-click-BrDcdTDU.js","assets/ban-DvAnxM3C.js","assets/Dashboard-CYh0Ko4t.js","assets/useContentEngagement-4qQn_ya_.js","assets/timezone-DptPIDFf.js","assets/addMilliseconds-BV2OSTwK.js","assets/isWithinInterval-D7p-rBSJ.js","assets/useGmailIntegration-Capm-Asr.js","assets/GoalTargetsDialog-sowznmDm.js","assets/useBrokerageContent-CofSEkuT.js","assets/beta-badge-CxR34ldM.js","assets/useEventGamification-B6Mx_xot.js","assets/RelationshipHealthWidget-CkfTgWpC.js","assets/useRelationshipScore-Blpj_UzC.js","assets/file-image-DLI6hMa-.js","assets/Profile-D2Q1miiG.js","assets/RichTextEditor-Cqbwbuwv.js","assets/index-CKLO5wh8.js","assets/index-DkyeK2wo.js","assets/index-CbjhlMgc.js","assets/heading-1-Cw07CZ0B.js","assets/heading-2-B5rJLwdp.js","assets/undo-Bghh73pw.js","assets/list-ordered-BRE9zTbD.js","assets/align-left-zgbmzLxE.js","assets/align-right-Do3jQLUD.js","assets/ImageCropper-BB02ecRI.js","assets/zoom-out-DKEa2p8D.js","assets/rotate-cw-i-gOZ-g2.js","assets/ImageCropper-D8Md-CES.css","assets/SmsOptInCard-6KqTnOAx.js","assets/mail-x-BhHe8DbR.js","assets/useBrandKit-Dk-ZmUqu.js","assets/useStagingStudio-HV22qgzp.js","assets/checkoutTab-BL5Buakm.js","assets/BrokerageLogoUpload-D5sMPcsq.js","assets/user-round-DOdoGpuW.js","assets/Events-2-guXTma.js","assets/EventLeaderboard-j7G3suzb.js","assets/medal-BBKv13XE.js","assets/MainStageSchedule-y_dnFHa1.js","assets/history-DpgzmaiE.js","assets/EventDetail-DJ1zaSku.js","assets/ShareButton-B8lFiFBY.js","assets/user-cog-B4JSTWMx.js","assets/Apps-BtVyWUIN.js","assets/monitor-play-DTuIlcTM.js","assets/skip-forward-BOlyiPlF.js","assets/Templates-DX_tBy8-.js","assets/TemplateDetail-64B-ji1L.js","assets/Programs-D-MKehw5.js","assets/usePrograms-C9Y-ctSr.js","assets/ProgramDetail-BxALw--q.js","assets/accordion-1XaeygyV.js","assets/index-DVTa1vFi.js","assets/ProgramEnroll-ByaSZbZT.js","assets/tag-EMnudJeI.js","assets/ProgramWorkspace-D9wDEgrh.js","assets/file-spreadsheet-DRosfoJk.js","assets/layout-template-D1WR0ozD.js","assets/Programs-CoJIc25W.js","assets/route-1aPAAdkH.js","assets/collapsible-CEgZg-Lf.js","assets/AcademyVideoDetail-lFzQhdRZ.js","assets/LinkedTemplatePills-DLr4_K6h.js","assets/ToolboxDetail-BXXVB5kn.js","assets/SocialSwag-unk0NrIb.js","assets/SocialStudio-BNZshEXY.js","assets/CanvaImportDialog-B7J_R419.js","assets/useCanvaMailStudio-CDfXDYZ8.js","assets/unlink-DfWM9n7C.js","assets/platforms-DwcHkTbR.js","assets/music-2-yNT9vb70.js","assets/jpegConvert-DTLv72O4.js","assets/repeat-2-CRI58jXC.js","assets/useCalendarTimezone-ByI_7NyA.js","assets/calendarTz-JHe45SGp.js","assets/type-DPbrr0yv.js","assets/settings-2-_uJMRzyI.js","assets/scheduleTz-D-eZvdS-.js","assets/YouTubePublishing-Fh3ai91X.js","assets/CalendarSettingsDialog-C4s5MXXF.js","assets/earth-DsFg0egk.js","assets/tiktokCallbackError-HhZqZSBp.js","assets/lock-keyhole-DwMBQUIR.js","assets/clock-3-B79vsE1o.js","assets/jszip.min-Dx97MML1.js","assets/flask-conical-gsgx3vIy.js","assets/SocialStudio-Bwx1jhq8.css","assets/MarketingStudio-BHGTr-17.js","assets/message-square-quote-DCK9vg8E.js","assets/BrandKit-CtO3kIXx.js","assets/useBrandPresets-DkghQWr5.js","assets/BrandingBarEditor-SHiGCHCq.js","assets/ReactKonvaCore-BC1o9EVn.js","assets/index-CMqZMSmv.js","assets/ListingTemplates-0mtSr1nS.js","assets/index-xVp0PEHv.js","assets/EditorialTemplate-CWhCahur.js","assets/PersonalBranding-Co-xgBa1.js","assets/toggle-group-DZC43CAT.js","assets/SocialSwagDetail-BMlBniSS.js","assets/Community-DppGPg_i.js","assets/MentionTextarea-rsl1G-8Y.js","assets/reply-B8Sm4ILi.js","assets/pin-off-BOBUSZsh.js","assets/Support-ylraDgxG.js","assets/SupportAttachmentList-CbDPma-A.js","assets/file-video-CtQzrvB5.js","assets/BrokerageResources-Bcuvz1G7.js","assets/AdminDashboard-Du7GDtHl.js","assets/coins-BvRBgTt0.js","assets/shopping-bag-CIWVByIl.js","assets/database-BLE-VLbQ.js","assets/AdminAdEngine-2Pw5MUoR.js","assets/AdEngineOrders-eJoUN68m.js","assets/jspdf.es.min-DAf3o5K2.js","assets/AdEngineCheckout-UOY4oNRy.js","assets/MemberManagement-BhEsPzFc.js","assets/SendCelebrationDialog-BBW9yxMh.js","assets/sortable-table-head-DcKx7Ivx.js","assets/useTeams-MCVyG_Ou.js","assets/CreateTeamDialog-CqQcn4X6.js","assets/TeamSharedAssetsView-_EUlrREa.js","assets/LeadPondView-HFzzlD9e.js","assets/arrow-right-left-Cd4NrQFK.js","assets/sticky-note-DH7Wi6K0.js","assets/droplets-Deh7V0t-.js","assets/hand-B8qvRyuW.js","assets/contact-BzQ9Gsbf.js","assets/calendar-heart-BwcnEm18.js","assets/UnassignedMembers-CNxksavY.js","assets/InviteCodes-DdXnGvqU.js","assets/Events-DcELUxTv.js","assets/useNotifications-DZFsf6Ro.js","assets/repeat-Dogv5n8n.js","assets/MCPAuditLog-BbvSF5Uz.js","assets/shield-alert-Bat5emwZ.js","assets/Templates-Ccqmhxdq.js","assets/Academy-VOvQWUVF.js","assets/LinkedTemplatePicker-BxqHZYFy.js","assets/VideoLibraryPicker-CqnfzruL.js","assets/Toolbox-CXE-ykwb.js","assets/SocialSwag-BakVbdU-.js","assets/SocialSwag2-BUMZJzXi.js","assets/Community-DzY8AN_Z.js","assets/Analytics-tfIaE9ao.js","assets/ShareAnalytics-DXDKBq8X.js","assets/mouse-pointer-BuWFfQ1Z.js","assets/panels-top-left-DTuC-nZC.js","assets/LineChart-Cwp5SgFP.js","assets/chrome-D8Z1J24W.js","assets/BrokerageResources-C33Yu8xW.js","assets/DashboardManagement-BqGlbhEE.js","assets/SupportTickets-CCWoBaiV.js","assets/EmailTemplates-CYwDYrOy.js","assets/index-D3m3dBnJ.js","assets/code-NuWxiSBt.js","assets/variable-CowXVfuB.js","assets/monitor-Cg-uAAU3.js","assets/AgentEmailTemplates-CChb2gBd.js","assets/BrokerageDashboard-DnWBJHyd.js","assets/BrokerageLenderReport-DLvK1r5J.js","assets/MyBrokerage-C0V4jq6p.js","assets/useBrokerageOnboarding-B-u1IAul.js","assets/OnboardingChecklist-PyTNi5BM.js","assets/BrokerageContent-0WmOVTk9.js","assets/BrokerageHelpBoard-B3Lad0kD.js","assets/useBrokerageHelpBoard-CzghqyHv.js","assets/BrokerageHelpBoardNew-DQCWeyIU.js","assets/BrokerageHelpBoardDetail-C2UdZs7e.js","assets/Newsletters-BEdSXsN2.js","assets/VisualHtmlEditor-DIZ8J5aV.js","assets/NewsletterGraphicsPicker-DwtJMggm.js","assets/underline-BNWxOZlB.js","assets/uploadBase64Images-CvXcTRh4.js","assets/SendNewsletterDialog-DyClHtqi.js","assets/undo-2-lxeCj6M0.js","assets/useContactCustomTags-BsiQuPYa.js","assets/useSmartLists-tFmElDu4.js","assets/useMailingAddressGate-CJS0UBlQ.js","assets/SenderAddressDialog-DZW8gmRW.js","assets/code-xml-CelMbDfP.js","assets/NewsletterDetail-rVb3v5Fq.js","assets/Newsletters-DVfVPJDc.js","assets/library-DRVrvLkx.js","assets/MemberBroadcasts-ii0Za26A.js","assets/bookmark-plus-XUFNiiWn.js","assets/BoostAnnouncements-DVbQuJF8.js","assets/NewsletterGraphics-CxxYmFB9.js","assets/Wishlist-CszRsXYe.js","assets/WishlistDetail-C5gESUTe.js","assets/LevelUpBrief-CuE020h0.js","assets/AdditionalServices-QIH9glCo.js","assets/Discounts-BFoBDk4V.js","assets/Subscriptions-BCWR05eq.js","assets/instagramEmailReview-DK4Cq88H.js","assets/InstagramGiftEmails-CYjFDRw7.js","assets/InstagramCommentPilot-Nf8b9p82.js","assets/Referrals-9k41jpiS.js","assets/AgentOSControlCenter-BViCgNbd.js","assets/AskAI-ZD-dwbOL.js","assets/InnerCircleHome-OZflWn_-.js","assets/SnoozeContactDialog-Bl7u3jDS.js","assets/pen-tool-BVCccYYh.js","assets/milestoneMail-Cs6qfJaR.js","assets/handoff-B7AOa2Ye.js","assets/milestones-De303X1G.js","assets/stamp-uaOePBz_.js","assets/mail-open-B1_0H77H.js","assets/InnerCircleContacts-CZrrzsLE.js","assets/useCrmWorkspace-C1xIMVol.js","assets/mailingAddress-BJ5Zh-Ye.js","assets/SyncDirectionSelector-C7HGM-s-.js","assets/refresh-ccw-Cc_SQOOe.js","assets/merge-DnlhvShk.js","assets/ContactCriteriaForm-BvavlLGu.js","assets/usePopbys-ChmIAacY.js","assets/ContactTagChip-CeFxyWKI.js","assets/info-BIUQt0OW.js","assets/RelationshipScoreBadge-De0Lh3VK.js","assets/MailStudioHandoffButton-CU19v-F7.js","assets/useVideoShareTracking-CrGq8UR1.js","assets/EnrollContactsDialog-D0bXM3Js.js","assets/useDripCampaigns-wP4nT6Q3.js","assets/CampaignBuilderDialog-D_2XEnHV.js","assets/quill.snow-eMFwCF2x.js","assets/quill-BzY4kI8E.css","assets/braces-Db53_iGe.js","assets/holidayCalendar-BQjF-Tal.js","assets/VideoUploadDialog-DCaoxGle.js","assets/useVideoTouch-CXbN6jq2.js","assets/CardVideoRecorderDialog-BlobtOd1.js","assets/VideoRecorder-B_le7tEH.js","assets/flip-horizontal-zro69r0j.js","assets/videoSegmentation-23AN6N06.js","assets/monitor-up-DboA1Ezp.js","assets/mic-BPO93H3S.js","assets/folder-w0zf4QXT.js","assets/NeighborhoodFilter-DEEm5dj1.js","assets/useNeighborhoods-D9r-gX7X.js","assets/useSphereMap-D4CrKX7Y.js","assets/sphereMap-YB1M3Tvq.js","assets/sprout-_OXHSdpz.js","assets/ContactAvatar-BaVh0MoN.js","assets/user-x-BfXk0TVM.js","assets/map-pinned-o48Xghgp.js","assets/InnerCircleContactDetail-DD9qFJ0k.js","assets/useLenders-BlCcmnkz.js","assets/SendToLenderDialog-co5k9Of_.js","assets/HomeownerHubManager-C2UyRW3r.js","assets/EditHomeDetailsDialog-B7KLSOvV.js","assets/moon-D7MYzfUu.js","assets/useSentEmails-BUfo0ykq.js","assets/ContactResearchLinks-DbVpvmhe.js","assets/useCMA-xdH3rwEq.js","assets/useClientPortal-Bgd43dJ4.js","assets/AiCmaDialog-MEb23Rv9.js","assets/futureSeller-BR3mcgUq.js","assets/PublicPropertyFacts-Bgwofo2e.js","assets/PropertyLookupPanel-BvCKLkeL.js","assets/useContactFinder-BdZu9K2R.js","assets/SentEmails-DEGD6UWK.js","assets/ConstructionProjectsManager-CGMjP85V.js","assets/InnerCirclePlans-CjRuH0m5.js","assets/pen-749n_rFj.js","assets/CMAList-rUD1HOyC.js","assets/SendCMADialog-olFgUsh9.js","assets/UpgradeLockedCard-D9Z-gGef.js","assets/CMABuilder-DkzMjwi1.js","assets/ListingPresentations-C6ydLj3C.js","assets/session-B4XQOxDG.js","assets/SendPresentationDialog-Dh1I4hFd.js","assets/ListingPresentationBuilder-DlCk4N2w.js","assets/PdfCanvasPreview-B6u1W9YK.js","assets/pdf.worker.min-4_nM5LJx.js","assets/ImageUploadField-B4N7m8ja.js","assets/move-DrdMe4V-.js","assets/InnerCirclePopbys-BBjO_UvT.js","assets/locate-CbanToYP.js","assets/navigation-DeKgxndQ.js","assets/AdEngine-hFRTCUFz.js","assets/launchRunbook-Bp4m7sw7.js","assets/promotion-BIjG_EU8.js","assets/SmartSigns-zg32HYCH.js","assets/message-square-text-CwPikl84.js","assets/ListingExchange-CAsb-DLY.js","assets/ListingLaunchKitModal-BnZebxd2.js","assets/ListingSelectionBar-t77wJb3G.js","assets/musicVideoHandoff-Bs6IOG8F.js","assets/building-u6c3l1O7.js","assets/ListingDetail-C2vPMUvo.js","assets/ListingForm-CGoWRs5L.js","assets/CustomizeListingPage-pss1aEU-.js","assets/box-DlSbAbcT.js","assets/VideoStudio-CAeuryUN.js","assets/wifi-CspqbmKD.js","assets/VideoShareWithTemplate-DDcHDMdq.js","assets/useStageChat-BZagCRHE.js","assets/chatHistory-DtORk9Qs.js","assets/browser-CjSdxGTc.js","assets/tv-DV6E7s1a.js","assets/video-off-DYvMjQcq.js","assets/guestRoom-iXuPpPSz.js","assets/kits-DACmZcCF.js","assets/BackdropPanel-DYy5gyhx.js","assets/ListingPhotoImport-Bcmr5Yf_.js","assets/images-DZa-i1nJ.js","assets/panel-right-close-B-i0dEa1.js","assets/clapperboard-DTEJJ8Yi.js","assets/scissors-BlGm5Ruw.js","assets/switch-camera-Cx51Gdg7.js","assets/MainStageGate-DHpmfqOi.js","assets/arena-DPNRg9tz.js","assets/phone-off-Cgl7Rbi0.js","assets/eraser-DLA0ZSHl.js","assets/theater-DiS3mjZG.js","assets/MainStageAdmin-BM3BBaWL.js","assets/StudioKitsAdmin-BvqqTt1P.js","assets/StudioGuestJoin-CCLgIFal.js","assets/VideoLibrary-CR9S3hV4.js","assets/tags-DT4mZh_1.js","assets/hard-drive-D8wBJEqN.js","assets/DealPipeline-BWsj7LCQ.js","assets/lucide-react-CpCNKOzd.js","assets/archive-restore-BwELlOHU.js","assets/archive-CtqFqfps.js","assets/arrow-down-left-DTTuL6YB.js","assets/arrow-down-right-DdL0VnuL.js","assets/circle-user-CrhgFxuP.js","assets/beaker-BtqGrdzk.js","assets/brain-circuit-CjyGWZFT.js","assets/calendar-x-BpFr5Ckk.js","assets/file-code-2UVAXXau.js","assets/table-BkLOOxgG.js","assets/circle-dollar-sign-BPaQ37dY.js","assets/sunset-CGK2Ripk.js","assets/cloud-upload-CNTI-ADc.js","assets/corner-down-right-DRBTHRo0.js","assets/file-check-2-DGOb3I5R.js","assets/file-check-DeqJsH-B.js","assets/file-down-bRrNRpRc.js","assets/file-plus-2-ChAhpiPc.js","assets/piggy-bank-DEa_PLP2.js","assets/folder-plus-C8E51hoD.js","assets/footprints-C8738tFo.js","assets/gem-YxFFYgmC.js","assets/hand-heart-B_sPLAbF.js","assets/heading-3-CbQ4uV8D.js","assets/heart-handshake-AXQbBRyp.js","assets/id-card-CsPVdLR1.js","assets/locate-fixed-DFFZ9Wdm.js","assets/list-plus-CZm6jvXt.js","assets/mail-plus-BNqnnWMJ.js","assets/mail-warning-DCufz9qK.js","assets/message-square-more-BVplamHq.js","assets/message-square-plus-4vWS2xGw.js","assets/message-square-reply-DRMoYvoL.js","assets/messages-square-CQZz1GLC.js","assets/mouse-pointer-2-CnJHMoFw.js","assets/skip-back-DrLxMZ-c.js","assets/octagon-alert-CMy6mq5Q.js","assets/power-off-CajvoJxr.js","assets/power-SXXrJ7Dm.js","assets/rectangle-vertical-D_JRAjtM.js","assets/scroll-text-YaJ2b0lm.js","assets/shield-off-DcBLfFBn.js","assets/shield-question-DFw2oJuy.js","assets/table-2-CiFsCHVk.js","assets/text-cursor-input-6H9QR9Zw.js","assets/thumbs-down-TiHC27vZ.js","assets/twitter-BfL11D7w.js","assets/user-round-check-ClLQFWjD.js","assets/user-round-plus-D2zh2ze-.js","assets/user-round-search-CjjybiWE.js","assets/users-round-A5IUvXav.js","assets/useCommissionPlans-CRBsVwBA.js","assets/ComplianceMessageThread-Dsk58-8P.js","assets/SendForSignatureDialog-CtXiI3Px.js","assets/useFormEnvelopes-Bmm1Klx5.js","assets/PortalInviteDialog-Dkf0mtQP.js","assets/PlaybookLibraryDialog-C1C2flqu.js","assets/LenderPartnerDialog-D_M_GDb6.js","assets/PhotoUploadField-Ct2gQAWv.js","assets/PortalListView-DCrZZkZm.js","assets/complianceMetrics-Ce83UgLe.js","assets/FormsLibrary-DVABsYLg.js","assets/FormPlacementEditor-Bif7rdEx.js","assets/TransactionCoordinator-BX6fct5R.js","assets/PortalReferrals-Dutas1Jp.js","assets/usePortalReferrals-nPbh9jxA.js","assets/AgentVendors-BA3yft8j.js","assets/VendorFormDialog-CEBS1M7H.js","assets/BrokerageForms-CRjjuYz3.js","assets/BrokerageVendors-Owvs7qP6.js","assets/ClientPortalsHub-DzUSS2gQ.js","assets/PortalMessagesPanel-DKoEgYJI.js","assets/ClientPortalDetail-BlLpNkZJ.js","assets/MyCardEditor-K8GAAYE0.js","assets/CardBlocksEditor-Dlp1tdmX.js","assets/Integrations-C930C5iT.js","assets/SesIntegrationCard-Dceb_3E3.js","assets/RecruitVerifiedSenders-D3vFU3_j.js","assets/Microsoft365Card-YaBDj8e3.js","assets/BrowserExtension-DD9dFNxs.js","assets/IntegrationsGmailCallback-Dd3TsIa7.js","assets/IntegrationsMetaCallback-BvOZ7WKn.js","assets/AgentActivation-DPh6p7iV.js","assets/MembershipReviews-ykrOy59V.js","assets/LeadNotifications-CzQVLazd.js","assets/WeeklyDigest-DQ0Zoz4H.js","assets/AgentPoints-CcYDBEVk.js","assets/AgentCards-B-szwkjY.js","assets/Marketplace-C2j6SOtY.js","assets/RewardStore-D_6qbfLT.js","assets/usePointRewardSettings-m0nSUk5k.js","assets/Integrations-B7XU7byU.js","assets/SocialConnections-CX0iBLlq.js","assets/SocialAutopilot-pTFQAhiX.js","assets/McpUpdates-_Xz9-AN6.js","assets/NotificationSettings-C-9TN2n0.js","assets/PresentationAnalytics-C9JFbbya.js","assets/ListingPresentationStudioAdmin-DKKF_vW6.js","assets/ListingRevivalAdmin-Z2Po9ZTe.js","assets/useListingRevivalAccess-DG14XHOH.js","assets/GuestBookAnalytics-IW5HyDQ_.js","assets/IntegrationsCallback-BrNwTUYG.js","assets/AdminRecruiting-BGxhjWbE.js","assets/RecruitPipelineStageEditor-D3nrrSRK.js","assets/videoThumb-B7-rh5G3.js","assets/index-DT31IQdM.js","assets/BrokerageRecruiting-CCptqrsy.js","assets/600-BSKZD_mM.css","assets/BrokerageOnboarding-CsZWpw2Q.js","assets/BrokerageTransactions-dn6xKn8U.js","assets/AddDealDialog-b7ZAGYZL.js","assets/useDealEscrow-Cj-kHtIy.js","assets/BrokerageDeals-BkDMk395.js","assets/BrokerageOperations-DKKhhHUK.js","assets/renewals-DXhvNnDT.js","assets/WebsitesHub-Dgvev8ke.js","assets/useMyWebsites-BK7GxIzr.js","assets/SiteGrade-BsNjmZOw.js","assets/TeamWebsite-DkPd0f-e.js","assets/OrgSiteBuilder-DkRCKPYU.js","assets/SiteSwitcher-tyo7VNL9.js","assets/BrokerageWebsite-0QEe2xi9.js","assets/BrokerageAgentWebsites-DsfvSAfN.js","assets/BrokerageCommissionPlans-CsY3vtWB.js","assets/BrokerageContentActivity-B_c0TS_z.js","assets/BetaSocialPostGenerator-BRVVTd73.js","assets/AdminLMS-DkdiYSdr.js","assets/useLMS-Bw9uNMrx.js","assets/AdminCourseDetail-Bcgj67Yi.js","assets/LevelUpU-PsdO-PHA.js","assets/LevelUpUCourse-ZJgwFScD.js","assets/MobileAgentApp-DroIa_YQ.js","assets/StagingStudio-CtzDIRw8.js","assets/presets-D0MFEcHN.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-BXbjbMdy.js","assets/BuyCreditsDialog-CJec_zrn.js","assets/StagingLibrary-DMmPuTI5.js","assets/StagingCredits-DvBhLSZ5.js","assets/AgentWallet-RhO7Ej7G.js","assets/useHomeReel-BwBJYQdg.js","assets/Prospecting-CCDmvgFk.js","assets/ProspectHousePanel-8TwBsxyl.js","assets/types-kW6jHCE4.js","assets/recipients-DwRJtOvs.js","assets/aerial-DRzbvxys.js","assets/StagingSharePage-Ci0RVQKR.js","assets/StagingStudioAdmin-tCYdAUzC.js","assets/ContactFinderAdmin-CEmnVuqf.js","assets/PostcardManager-DpZPAoVn.js","assets/PostcardZoneEditor-OraN1_DA.js","assets/usePostcardZones-B_i23Wnq.js","assets/MailStudioTemplates-BfPI9Wu3.js","assets/HomeReelManager-c1HpUJft.js","assets/videoRenderSink-KDd1M0JO.js","assets/AdminMusicVideos-CRVl9kf0.js","assets/AdminVideoLab-CGgI9Vgb.js","assets/BoostPreview-nJlha_nn.js","assets/AdminCredits-BDMBU26_.js","assets/MailStudio-PAOU56h4.js","assets/farmToCrm-DkLH_qmy.js","assets/campaignMail-BaIV7NQq.js","assets/FsboLetter-CxYj2haz.js","assets/RevivalLetter-CBGmqh96.js","assets/types-CK1tolb7.js","assets/prepareCampaignLetter-BY3sMQ9e.js","assets/addressNormalization-R8Z0mzYu.js","assets/MailStudio-D-BotKHo.css","assets/InnerCirclePopbyMap-BQp9wLcM.js","assets/SphereMap-Cki9IGlQ.js","assets/PropertyIntelligenceDashboard-BY5hfy3o.js","assets/LiveVisitorFeed-C10RKJl8.js","assets/LeadSites-DE0Idruo.js","assets/LeadSiteEditor-Bptx3obz.js","assets/ModuleConfigPanel--IqerXgD.js","assets/ImageUrlField-CY82-YWP.js","assets/VideoUrlField-DMtuByEF.js","assets/LeadSiteEditor-MoQpsqOR.css","assets/AdminLeadSiteThemes-DCBJ27oI.js","assets/AdminFreeWebsiteOfferStudio-CfQULMbE.js","assets/AdminMlsFeeds-W8d4uSCG.js","assets/AdminWebsiteRequests-CXNEC5_M.js","assets/WebsitePackages-CvxjstI5.js","assets/NeedAWebsite-OqI112pN.js","assets/CreateWebsite-BfgXJpuo.js","assets/MLSListings-Dc0WXxCu.js","assets/MLSListingDetail-C7uF5g8B.js","assets/WebsiteActivityPage-7TetnCto.js","assets/PublicRecruitForm-D9Gu-XWb.js","assets/PublicEventInviteUnsubscribe-CDk8EYl4.js","assets/SocialConnections-CEEXfftd.js","assets/SocialConnectionsCallback-DpmzSs6l.js","assets/LinkedInCallback-CgNxIZnn.js","assets/TikTokCallback-CqdKAR6r.js","assets/MarketplaceCart-DML66ebt.js","assets/MarketplaceOrderDetail-DlLl4fKT.js","assets/RewardStore-CEAaOGrg.js","assets/ReferFriends-B8ZVgApn.js","assets/SmartPresentations-B6SobvdH.js","assets/useSmartPresentations-B6uIObUw.js","assets/SmartPresentationCreate-9JINVnNm.js","assets/TeleprompterOverlay-DjIKkchs.js","assets/GuestBook-DxLqnOTF.js","assets/SignDocument-DqtNz8lR.js","assets/Blog-N5VLsbV7.js","assets/TrialCTA-D9ByUzNu.js","assets/BlogPost-Dx3bRPKm.js","assets/AdminBlog-C4Z3DQ3O.js","assets/ReviewLanding-CiAhYAiJ.js","assets/ReviewIntake--K-m_zER.js","assets/PublicReviewsPage-BlyYaUpD.js","assets/PublicReviewSubmit-DCO3-Yi6.js","assets/Reviews-D3khAkt9.js","assets/NetSheets-Ba8JTlPN.js","assets/LenderHub-oXcgvvXB.js","assets/states-BVqvKcH4.js","assets/AdEngineSponsor-D-eO0T4e.js","assets/LendersLanding-DxFu5uJd.js","assets/LendingPartners-DQEBUvFy.js","assets/AdminLenders-B0T_k9kC.js","assets/CardStudio-olFwZEu6.js","assets/ListingStudio-q38pf_sI.js","assets/SmartDrips-CGhcqVWF.js","assets/WeeklyReels-DeQ7zhID.js","assets/ReelCard-DfwFJJWq.js","assets/useWeeklyReels-X0K8sR02.js","assets/WeeklyReelsOnboarding-BqTe9xiT.js","assets/WeeklyReelsAdmin-BM4obGS4.js","assets/AttractLayout-Ds7EtRWi.js","assets/useAttractSettings-DAf_K7En.js","assets/useAttractIntelligence-B3Z-GcGt.js","assets/HealthScoreBadge-CXaOPgut.js","assets/AttractToday-D066V-1x.js","assets/useAttractIntelSync-I9at57lN.js","assets/useAttractAgents-D_GPMXdm.js","assets/useAttractFollowUps-DnhrA9FQ.js","assets/useAttractActivities-9T6LLEPj.js","assets/RecommendationCard-DcEj5cFl.js","assets/QuickAddRelationship-ex4l1q7N.js","assets/relationshipStages-Buh5_cBI.js","assets/useAttractEvents-DutRMoII.js","assets/AttractRelationships-B2RkNmWE.js","assets/AgentEditSheet-CInwCguU.js","assets/AttractFollowUp-BGL3Gy1w.js","assets/AttractPageHeader-8ffA2AHc.js","assets/AttractTemplates-CqYJ2xU8.js","assets/AttractReports-D-SE9fPv.js","assets/AttractSettings-IiCf1KS4.js","assets/AttractToolkit-JA7UARce.js","assets/Objections-C5lyX6yu.js","assets/AttractCalculator-DGwJiRJH.js","assets/attractionPageTemplate-C9AaZMgq.js","assets/AttractEventList-CBUGdmWD.js","assets/AttractEventBuilder-BrhhbN-3.js","assets/useAttractKits-xozh3Nj5.js","assets/AttractEventDetail-CYK32on1.js","assets/AttractEventCheckIn-BE_6l9WQ.js","assets/AttractOnboarding-D_RS03zF.js","assets/ContentStudio-DIbCR41z.js","assets/KitList-e-Jgr-AV.js","assets/KitBuilder-B1d21o6S.js","assets/KitPreview-BowDVgW-.js","assets/KitAnalytics-9v2evcBh.js","assets/KitTemplates-DCmKRp6L.js","assets/AttractAgentDetail-DqPnQz7v.js","assets/AttractOpportunities-C6vDfxWY.js","assets/AttractIntelligenceDebug-UN9Fe6fT.js","assets/PublicAttractKit-BxKYzpOF.js","assets/PublicAttractEvent-j8OLKea2.js","assets/PublicAttractionPage-QlYo6urq.js","assets/AttractionPageView-Cbyu5-aP.js","assets/RevivalLanding-BtWTNaAh.js","assets/RevivalPlan-CYOqzti2.js","assets/revivalPdf-0hfMNwxa.js","assets/ListingRevival-UrRBKLav.js","assets/useListingRevival-BjHRXsXk.js","assets/AreaChart-Db7W4Eux.js","assets/RevivalCampaignWizard-DHUmLY3k.js","assets/RevivalCampaignDetail-sYk0Rebw.js","assets/LetterEditor-CV9kx2G-.js","assets/FsboBreakthrough-DuS-184Y.js","assets/useFsboBreakthrough-BQIG1gMq.js","assets/FsboPropertyDialog-BnRGFAo9.js","assets/FsboCampaignWizard-B04HQ7KZ.js","assets/FsboCampaignDetail-BIHoZrGd.js","assets/FsboLanding-BRbxn4Zk.js","assets/publicApi-BEaFpcRg.js","assets/FsboGuide-BS5iiOSd.js","assets/FsboBreakthroughAdmin-B0viRUQP.js","assets/AttractLandingPageBuilder-qLYY_Zrc.js","assets/AttractAccess-L5JP7ZDs.js","assets/Teams-uKnfZcRj.js","assets/MyTeam-Olpt2ptS.js","assets/TeamLeaderSettings-DwqRZoLP.js","assets/TeamHub-D7qNG2U_.js","assets/SchedulerSettings-BtsMPm0k.js","assets/MyCalendar-D7H5LYuQ.js","assets/BookingManagePage-CWAVTn3q.js","assets/LandingPages-D1rvfY-o.js","assets/BuyerMatch-tIEx3Czs.js","assets/SendBuyerMatchEmailDialog-OBUJaAeK.js","assets/BuyerMatchEditor-BrUhrAOQ.js","assets/matching-BdEgbJjD.js","assets/PublicBuyerMatch-hUCGdsAu.js","assets/LandingPageEditor-B9dOfUsl.js","assets/LandingPageDefaults-CYv3XnpB.js","assets/WebsiteAppsHub-DN0yVNQq.js","assets/ClaimFreeLeadSiteCard-DkaLn-lv.js","assets/useWebsiteApps-B5jZkLjc.js","assets/ClaimWebsite-CY6gvP-g.js","assets/VideoGreeterEditor-DPms5DYv.js","assets/ExitIntentEditor-DEL8CeZG.js","assets/widgetTemplates-keLygp7O.js","assets/LeadMagnetEditor-Cqi0MNMb.js","assets/RelationshipScorecard-DwNqf9uv.js","assets/SphereGaps-B9sTQ42a.js","assets/ConnectPageSettings-DzMslCGv.js","assets/BehaviorAlerts-DD6CDVhJ.js","assets/HomeownerHubs-CAtEEOE1.js","assets/EmailCampaigns-BLfKSuss.js","assets/sesRequest-MAv9amP_.js","assets/EmailCompliance-BKQQ1AjK.js","assets/EmailCampaignComposer-D7cyMd_R.js","assets/EditorModeSelector-Cy2e4ibz.js","assets/EmailCampaignDetail-GvgM9295.js","assets/SharedCampaignTemplates-LAUQMGiV.js","assets/TemplateEditorDialog-BdkCpa8p.js","assets/AgentTemplates-BBZ9XzGs.js","assets/TheLocalMoveHome-BU3aeSz2.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-DHVVUt_H.js","assets/TheLocalMoveCheckout-xwfHO9yN.js","assets/AdminWebsiteOrders-EsKKAUni.js"])))=>i.map(i=>d[i]); var QMe=Object.defineProperty;var Vte=t=>{throw TypeError(t)};var JMe=(t,e,r)=>e in t?QMe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Vr=(t,e,r)=>JMe(t,typeof e!="symbol"?e+"":e,r),yz=(t,e,r)=>e.has(t)||Vte("Cannot "+r);var Ct=(t,e,r)=>(yz(t,e,"read from private field"),r?r.call(t):e.get(t)),os=(t,e,r)=>e.has(t)?Vte("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Sn=(t,e,r,n)=>(yz(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Zs=(t,e,r)=>(yz(t,e,"access private method"),r);var qR=(t,e,r,n)=>({set _(i){Sn(t,e,i,r)},get _(){return Ct(t,e,n)}});function eDe(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 fc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function wi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function tDe(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 Ame={exports:{}},t3={},Nme={exports:{}},ai={};/** * @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 _C=Symbol.for("react.element"),rDe=Symbol.for("react.portal"),nDe=Symbol.for("react.fragment"),sDe=Symbol.for("react.strict_mode"),iDe=Symbol.for("react.profiler"),aDe=Symbol.for("react.provider"),oDe=Symbol.for("react.context"),lDe=Symbol.for("react.forward_ref"),cDe=Symbol.for("react.suspense"),uDe=Symbol.for("react.memo"),dDe=Symbol.for("react.lazy"),qte=Symbol.iterator;function hDe(t){return t===null||typeof t!="object"?null:(t=qte&&t[qte]||t["@@iterator"],typeof t=="function"?t:null)}var Cme={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ime=Object.assign,Pme={};function GT(t,e,r){this.props=t,this.context=e,this.refs=Pme,this.updater=r||Cme}GT.prototype.isReactComponent={};GT.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")};GT.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Rme(){}Rme.prototype=GT.prototype;function N7(t,e,r){this.props=t,this.context=e,this.refs=Pme,this.updater=r||Cme}var C7=N7.prototype=new Rme;C7.constructor=N7;Ime(C7,GT.prototype);C7.isPureReactComponent=!0;var Gte=Array.isArray,Lme=Object.prototype.hasOwnProperty,I7={current:null},Mme={key:!0,ref:!0,__self:!0,__source:!0};function Dme(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)Lme.call(e,n)&&!Mme.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1>>1,xe=me[Ee];if(0>>1;Eei(lt,Pe))wti(yt,lt)?(me[Ee]=yt,me[wt]=Pe,Ee=wt):(me[Ee]=lt,me[Ze]=Pe,Ee=Ze);else if(wti(yt,Pe))me[Ee]=yt,me[wt]=Pe,Ee=wt;else break e}}return ke}function i(me,ke){var Pe=me.sortIndex-ke.sortIndex;return Pe!==0?Pe:me.id-ke.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;t.unstable_now=function(){return o.now()}}else{var c=Date,a=c.now();t.unstable_now=function(){return c.now()-a}}var f=[],m=[],y=1,v=null,w=3,j=!1,A=!1,C=!1,I=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,D=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function F(me){for(var ke=r(m);ke!==null;){if(ke.callback===null)n(m);else if(ke.startTime<=me)n(m),ke.sortIndex=ke.expirationTime,e(f,ke);else break;ke=r(m)}}function z(me){if(C=!1,F(me),!A)if(r(f)!==null)A=!0,Se(q);else{var ke=r(m);ke!==null&&ve(z,ke.startTime-me)}}function q(me,ke){A=!1,C&&(C=!1,M(J),J=-1),j=!0;var Pe=w;try{for(F(ke),v=r(f);v!==null&&(!(v.expirationTime>ke)||me&&!oe());){var Ee=v.callback;if(typeof Ee=="function"){v.callback=null,w=v.priorityLevel;var xe=Ee(v.expirationTime<=ke);ke=t.unstable_now(),typeof xe=="function"?v.callback=xe:v===r(f)&&n(f),F(ke)}else n(f);v=r(f)}if(v!==null)var Ue=!0;else{var Ze=r(m);Ze!==null&&ve(z,Ze.startTime-ke),Ue=!1}return Ue}finally{v=null,w=Pe,j=!1}}var H=!1,K=null,J=-1,Q=5,ee=-1;function oe(){return!(t.unstable_now()-eeme||125Ee?(me.sortIndex=Pe,e(m,me),r(f)===null&&me===r(m)&&(C?(M(J),J=-1):C=!0,ve(z,Pe-Ee))):(me.sortIndex=xe,e(f,me),A||j||(A=!0,Se(q))),me},t.unstable_shouldYield=oe,t.unstable_wrapCallback=function(me){var ke=w;return function(){var Pe=w;w=ke;try{return me.apply(this,arguments)}finally{w=Pe}}}})(zme);$me.exports=zme;var SDe=$me.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 TDe=N,Bd=SDe;function Yr(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"),PV=Object.prototype.hasOwnProperty,jDe=/^[: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]*$/,Wte={},Kte={};function EDe(t){return PV.call(Kte,t)?!0:PV.call(Wte,t)?!1:jDe.test(t)?Kte[t]=!0:(Wte[t]=!0,!1)}function kDe(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 ADe(t,e,r,n){if(e===null||typeof e>"u"||kDe(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 Nu(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 xc={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){xc[t]=new Nu(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];xc[e]=new Nu(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){xc[t]=new Nu(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){xc[t]=new Nu(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){xc[t]=new Nu(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){xc[t]=new Nu(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){xc[t]=new Nu(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){xc[t]=new Nu(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){xc[t]=new Nu(t,5,!1,t.toLowerCase(),null,!1,!1)});var L7=/[\-:]([a-z])/g;function M7(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(L7,M7);xc[e]=new Nu(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(L7,M7);xc[e]=new Nu(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(L7,M7);xc[e]=new Nu(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){xc[t]=new Nu(t,1,!1,t.toLowerCase(),null,!1,!1)});xc.xlinkHref=new Nu("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){xc[t]=new Nu(t,1,!1,t.toLowerCase(),null,!0,!0)});function D7(t,e,r,n){var i=xc.hasOwnProperty(e)?xc[e]:null;(i!==null?i.type!==0:n||!(2a||i[c]!==o[a]){var f=` `+i[c].replace(" at new "," at ");return t.displayName&&f.includes("")&&(f=f.replace("",t.displayName)),f}while(1<=c&&0<=a);break}}}finally{_z=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?Fk(t):""}function NDe(t){switch(t.tag){case 5:return Fk(t.type);case 16:return Fk("Lazy");case 13:return Fk("Suspense");case 19:return Fk("SuspenseList");case 0:case 2:case 15:return t=bz(t.type,!1),t;case 11:return t=bz(t.type.render,!1),t;case 1:return t=bz(t.type,!0),t;default:return""}}function DV(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 $1:return"Fragment";case B1:return"Portal";case RV:return"Profiler";case O7:return"StrictMode";case LV:return"Suspense";case MV:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case qme:return(t.displayName||"Context")+".Consumer";case Vme:return(t._context.displayName||"Context")+".Provider";case F7:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case B7:return e=t.displayName||null,e!==null?e:DV(t.type)||"Memo";case Jy:e=t._payload,t=t._init;try{return DV(t(e))}catch{}}return null}function CDe(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 DV(e);case 8:return e===O7?"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 Vx(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Hme(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function IDe(t){var e=Hme(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 WR(t){t._valueTracker||(t._valueTracker=IDe(t))}function Wme(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=Hme(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function _D(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 OV(t,e){var r=e.checked;return _o({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function Zte(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=Vx(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 Kme(t,e){e=e.checked,e!=null&&D7(t,"checked",e,!1)}function FV(t,e){Kme(t,e);var r=Vx(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")?BV(t,e.type,r):e.hasOwnProperty("defaultValue")&&BV(t,e.type,Vx(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function Xte(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 BV(t,e,r){(e!=="number"||_D(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var Bk=Array.isArray;function lS(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=KR.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function MA(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var tA={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},PDe=["Webkit","ms","Moz","O"];Object.keys(tA).forEach(function(t){PDe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),tA[e]=tA[t]})});function Qme(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||tA.hasOwnProperty(t)&&tA[t]?(""+e).trim():e+"px"}function Jme(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=Qme(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var RDe=_o({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 UV(t,e){if(e){if(RDe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Yr(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Yr(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Yr(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Yr(62))}}function VV(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 qV=null;function $7(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var GV=null,cS=null,uS=null;function ere(t){if(t=SC(t)){if(typeof GV!="function")throw Error(Yr(280));var e=t.stateNode;e&&(e=a3(e),GV(t.stateNode,t.type,e))}}function epe(t){cS?uS?uS.push(t):uS=[t]:cS=t}function tpe(){if(cS){var t=cS,e=uS;if(uS=cS=null,ere(t),e)for(t=0;t>>=0,t===0?32:31-(qDe(t)/GDe|0)|0}var YR=64,ZR=4194304;function $k(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 TD(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 a=c&~i;a!==0?n=$k(a):(o&=c,o!==0&&(n=$k(o)))}else c=r&~i,c!==0?n=$k(c):o!==0&&(n=$k(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 bC(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Rf(e),t[e]=r}function YDe(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=nA),cre=" ",ure=!1;function bpe(t,e){switch(t){case"keyup":return SOe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function wpe(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var z1=!1;function jOe(t,e){switch(t){case"compositionend":return wpe(e);case"keypress":return e.which!==32?null:(ure=!0,cre);case"textInput":return t=e.data,t===cre&&ure?null:t;default:return null}}function EOe(t,e){if(z1)return t==="compositionend"||!K7&&bpe(t,e)?(t=vpe(),AM=G7=_x=null,z1=!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=mre(r)}}function Epe(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Epe(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function kpe(){for(var t=window,e=_D();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=_D(t.document)}return e}function Y7(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 MOe(t){var e=kpe(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&Epe(r.ownerDocument.documentElement,r)){if(n!==null&&Y7(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=pre(r,o);var c=pre(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,U1=null,XV=null,iA=null,QV=!1;function gre(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;QV||U1==null||U1!==_D(n)||(n=U1,"selectionStart"in n&&Y7(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),iA&&zA(iA,n)||(iA=n,n=kD(XV,"onSelect"),0G1||(t.current=s8[G1],s8[G1]=null,G1--)}function Ca(t,e){G1++,s8[G1]=t.current,t.current=e}var qx={},$c=h0(qx),Qu=h0(!1),U_=qx;function HS(t,e){var r=t.type.contextTypes;if(!r)return qx;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 Ju(t){return t=t.childContextTypes,t!=null}function ND(){Ha(Qu),Ha($c)}function Sre(t,e,r){if($c.current!==qx)throw Error(Yr(168));Ca($c,e),Ca(Qu,r)}function Dpe(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(Yr(108,CDe(t)||"Unknown",i));return _o({},r,n)}function CD(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||qx,U_=$c.current,Ca($c,t),Ca(Qu,Qu.current),!0}function Tre(t,e,r){var n=t.stateNode;if(!n)throw Error(Yr(169));r?(t=Dpe(t,e,U_),n.__reactInternalMemoizedMergedChildContext=t,Ha(Qu),Ha($c),Ca($c,t)):Ha(Qu),Ca(Qu,r)}var cg=null,o3=!1,Mz=!1;function Ope(t){cg===null?cg=[t]:cg.push(t)}function WOe(t){o3=!0,Ope(t)}function f0(){if(!Mz&&cg!==null){Mz=!0;var t=0,e=ra;try{var r=cg;for(ra=1;t>=c,i-=c,mg=1<<32-Rf(e)+i|r<J?(Q=K,K=null):Q=K.sibling;var ee=w(M,K,F[J],z);if(ee===null){K===null&&(K=Q);break}t&&K&&ee.alternate===null&&e(M,K),D=o(ee,D,J),H===null?q=ee:H.sibling=ee,H=ee,K=Q}if(J===F.length)return r(M,K),eo&&Qv(M,J),q;if(K===null){for(;JJ?(Q=K,K=null):Q=K.sibling;var oe=w(M,K,ee.value,z);if(oe===null){K===null&&(K=Q);break}t&&K&&oe.alternate===null&&e(M,K),D=o(oe,D,J),H===null?q=oe:H.sibling=oe,H=oe,K=Q}if(ee.done)return r(M,K),eo&&Qv(M,J),q;if(K===null){for(;!ee.done;J++,ee=F.next())ee=v(M,ee.value,z),ee!==null&&(D=o(ee,D,J),H===null?q=ee:H.sibling=ee,H=ee);return eo&&Qv(M,J),q}for(K=n(M,K);!ee.done;J++,ee=F.next())ee=j(K,M,J,ee.value,z),ee!==null&&(t&&ee.alternate!==null&&K.delete(ee.key===null?J:ee.key),D=o(ee,D,J),H===null?q=ee:H.sibling=ee,H=ee);return t&&K.forEach(function(de){return e(M,de)}),eo&&Qv(M,J),q}function I(M,D,F,z){if(typeof F=="object"&&F!==null&&F.type===$1&&F.key===null&&(F=F.props.children),typeof F=="object"&&F!==null){switch(F.$$typeof){case HR:e:{for(var q=F.key,H=D;H!==null;){if(H.key===q){if(q=F.type,q===$1){if(H.tag===7){r(M,H.sibling),D=i(H,F.props.children),D.return=M,M=D;break e}}else if(H.elementType===q||typeof q=="object"&&q!==null&&q.$$typeof===Jy&&kre(q)===H.type){r(M,H.sibling),D=i(H,F.props),D.ref=ek(M,H,F),D.return=M,M=D;break e}r(M,H);break}else e(M,H);H=H.sibling}F.type===$1?(D=P_(F.props.children,M.mode,z,F.key),D.return=M,M=D):(z=DM(F.type,F.key,F.props,null,M.mode,z),z.ref=ek(M,D,F),z.return=M,M=z)}return c(M);case B1:e:{for(H=F.key;D!==null;){if(D.key===H)if(D.tag===4&&D.stateNode.containerInfo===F.containerInfo&&D.stateNode.implementation===F.implementation){r(M,D.sibling),D=i(D,F.children||[]),D.return=M,M=D;break e}else{r(M,D);break}else e(M,D);D=D.sibling}D=Vz(F,M.mode,z),D.return=M,M=D}return c(M);case Jy:return H=F._init,I(M,D,H(F._payload),z)}if(Bk(F))return A(M,D,F,z);if(Y2(F))return C(M,D,F,z);nL(M,F)}return typeof F=="string"&&F!==""||typeof F=="number"?(F=""+F,D!==null&&D.tag===6?(r(M,D.sibling),D=i(D,F),D.return=M,M=D):(r(M,D),D=Uz(F,M.mode,z),D.return=M,M=D),c(M)):r(M,D)}return I}var KS=zpe(!0),Upe=zpe(!1),RD=h0(null),LD=null,K1=null,J7=null;function eH(){J7=K1=LD=null}function tH(t){var e=RD.current;Ha(RD),t._currentValue=e}function o8(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 hS(t,e){LD=t,J7=K1=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Yu=!0),t.firstContext=null)}function Ch(t){var e=t._currentValue;if(J7!==t)if(t={context:t,memoizedValue:e,next:null},K1===null){if(LD===null)throw Error(Yr(308));K1=t,LD.dependencies={lanes:0,firstContext:t}}else K1=K1.next=t;return e}var h_=null;function rH(t){h_===null?h_=[t]:h_.push(t)}function Vpe(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,rH(e)):(r.next=i.next,i.next=r),e.interleaved=r,Ag(t,n)}function Ag(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 ex=!1;function nH(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function qpe(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 vg(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Px(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,Ni&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Ag(t,r)}return i=n.interleaved,i===null?(e.next=e,rH(n)):(e.next=i.next,i.next=e),n.interleaved=e,Ag(t,r)}function CM(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,U7(t,r)}}function Are(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 MD(t,e,r,n){var i=t.updateQueue;ex=!1;var o=i.firstBaseUpdate,c=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var f=a,m=f.next;f.next=null,c===null?o=m:c.next=m,c=f;var y=t.alternate;y!==null&&(y=y.updateQueue,a=y.lastBaseUpdate,a!==c&&(a===null?y.firstBaseUpdate=m:a.next=m,y.lastBaseUpdate=f))}if(o!==null){var v=i.baseState;c=0,y=m=f=null,a=o;do{var w=a.lane,j=a.eventTime;if((n&w)===w){y!==null&&(y=y.next={eventTime:j,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var A=t,C=a;switch(w=e,j=r,C.tag){case 1:if(A=C.payload,typeof A=="function"){v=A.call(j,v,w);break e}v=A;break e;case 3:A.flags=A.flags&-65537|128;case 0:if(A=C.payload,w=typeof A=="function"?A.call(j,v,w):A,w==null)break e;v=_o({},v,w);break e;case 2:ex=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,w=i.effects,w===null?i.effects=[a]:w.push(a))}else j={eventTime:j,lane:w,tag:a.tag,payload:a.payload,callback:a.callback,next:null},y===null?(m=y=j,f=v):y=y.next=j,c|=w;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;w=a,a=w.next,w.next=null,i.lastBaseUpdate=w,i.shared.pending=null}}while(!0);if(y===null&&(f=v),i.baseState=f,i.firstBaseUpdate=m,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);G_|=c,t.lanes=c,t.memoizedState=v}}function Nre(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=Oz.transition;Oz.transition={};try{t(!1),e()}finally{ra=r,Oz.transition=n}}function oge(){return Ih().memoizedState}function XOe(t,e,r){var n=Lx(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},lge(t))cge(e,r);else if(r=Vpe(t,e,r,n),r!==null){var i=Tu();Lf(r,t,n,i),uge(r,e,n)}}function QOe(t,e,r){var n=Lx(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(lge(t))cge(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,a=o(c,r);if(i.hasEagerState=!0,i.eagerState=a,$f(a,c)){var f=e.interleaved;f===null?(i.next=i,rH(e)):(i.next=f.next,f.next=i),e.interleaved=i;return}}catch{}finally{}r=Vpe(t,e,i,n),r!==null&&(i=Tu(),Lf(r,t,n,i),uge(r,e,n))}}function lge(t){var e=t.alternate;return t===xo||e!==null&&e===xo}function cge(t,e){aA=OD=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function uge(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,U7(t,r)}}var FD={readContext:Ch,useCallback:Cc,useContext:Cc,useEffect:Cc,useImperativeHandle:Cc,useInsertionEffect:Cc,useLayoutEffect:Cc,useMemo:Cc,useReducer:Cc,useRef:Cc,useState:Cc,useDebugValue:Cc,useDeferredValue:Cc,useTransition:Cc,useMutableSource:Cc,useSyncExternalStore:Cc,useId:Cc,unstable_isNewReconciler:!1},JOe={readContext:Ch,useCallback:function(t,e){return Em().memoizedState=[t,e===void 0?null:e],t},useContext:Ch,useEffect:Ire,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,PM(4194308,4,rge.bind(null,e,t),r)},useLayoutEffect:function(t,e){return PM(4194308,4,t,e)},useInsertionEffect:function(t,e){return PM(4,2,t,e)},useMemo:function(t,e){var r=Em();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Em();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=XOe.bind(null,xo,t),[n.memoizedState,t]},useRef:function(t){var e=Em();return t={current:t},e.memoizedState=t},useState:Cre,useDebugValue:dH,useDeferredValue:function(t){return Em().memoizedState=t},useTransition:function(){var t=Cre(!1),e=t[0];return t=ZOe.bind(null,t[1]),Em().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=xo,i=Em();if(eo){if(r===void 0)throw Error(Yr(407));r=r()}else{if(r=e(),Kl===null)throw Error(Yr(349));q_&30||Kpe(n,e,r)}i.memoizedState=r;var o={value:r,getSnapshot:e};return i.queue=o,Ire(Zpe.bind(null,n,o,t),[t]),n.flags|=2048,YA(9,Ype.bind(null,n,o,r,e),void 0,null),r},useId:function(){var t=Em(),e=Kl.identifierPrefix;if(eo){var r=pg,n=mg;r=(n&~(1<<32-Rf(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=WA++,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[Mm]=e,t[qA]=n,_ge(t,e,!1,!1),e.stateNode=t;e:{switch(c=VV(r,n),r){case"dialog":Ua("cancel",t),Ua("close",t),i=n;break;case"iframe":case"object":case"embed":Ua("load",t),i=n;break;case"video":case"audio":for(i=0;iXS&&(e.flags|=128,n=!0,tk(o,!1),e.lanes=4194304)}else{if(!n)if(t=DD(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),tk(o,!0),o.tail===null&&o.tailMode==="hidden"&&!c.alternate&&!eo)return Ic(e),null}else 2*$o()-o.renderingStartTime>XS&&r!==1073741824&&(e.flags|=128,n=!0,tk(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=$o(),e.sibling=null,r=mo.current,Ca(mo,n?r&1|2:r&1),e):(Ic(e),null);case 22:case 23:return yH(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Ed&1073741824&&(Ic(e),e.subtreeFlags&6&&(e.flags|=8192)):Ic(e),null;case 24:return null;case 25:return null}throw Error(Yr(156,e.tag))}function o4e(t,e){switch(X7(e),e.tag){case 1:return Ju(e.type)&&ND(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return YS(),Ha(Qu),Ha($c),aH(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return iH(e),null;case 13:if(Ha(mo),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Yr(340));WS()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Ha(mo),null;case 4:return YS(),null;case 10:return tH(e.type._context),null;case 22:case 23:return yH(),null;case 24:return null;default:return null}}var iL=!1,Dc=!1,l4e=typeof WeakSet=="function"?WeakSet:Set,In=null;function Y1(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Co(t,e,n)}else r.current=null}function g8(t,e,r){try{r()}catch(n){Co(t,e,n)}}var Ure=!1;function c4e(t,e){if(JV=jD,t=kpe(),Y7(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,a=-1,f=-1,m=0,y=0,v=t,w=null;t:for(;;){for(var j;v!==r||i!==0&&v.nodeType!==3||(a=c+i),v!==o||n!==0&&v.nodeType!==3||(f=c+n),v.nodeType===3&&(c+=v.nodeValue.length),(j=v.firstChild)!==null;)w=v,v=j;for(;;){if(v===t)break t;if(w===r&&++m===i&&(a=c),w===o&&++y===n&&(f=c),(j=v.nextSibling)!==null)break;v=w,w=v.parentNode}v=j}r=a===-1||f===-1?null:{start:a,end:f}}else r=null}r=r||{start:0,end:0}}else r=null;for(e8={focusedElem:t,selectionRange:r},jD=!1,In=e;In!==null;)if(e=In,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,In=t;else for(;In!==null;){e=In;try{var A=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(A!==null){var C=A.memoizedProps,I=A.memoizedState,M=e.stateNode,D=M.getSnapshotBeforeUpdate(e.elementType===e.type?C:mf(e.type,C),I);M.__reactInternalSnapshotBeforeUpdate=D}break;case 3:var F=e.stateNode.containerInfo;F.nodeType===1?F.textContent="":F.nodeType===9&&F.documentElement&&F.removeChild(F.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Yr(163))}}catch(z){Co(e,e.return,z)}if(t=e.sibling,t!==null){t.return=e.return,In=t;break}In=e.return}return A=Ure,Ure=!1,A}function oA(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&&g8(e,r,o)}i=i.next}while(i!==n)}}function u3(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 y8(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 Sge(t){var e=t.alternate;e!==null&&(t.alternate=null,Sge(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Mm],delete e[qA],delete e[n8],delete e[GOe],delete e[HOe])),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 Tge(t){return t.tag===5||t.tag===3||t.tag===4}function Vre(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Tge(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 x8(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=AD));else if(n!==4&&(t=t.child,t!==null))for(x8(t,e,r),t=t.sibling;t!==null;)x8(t,e,r),t=t.sibling}function v8(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(v8(t,e,r),t=t.sibling;t!==null;)v8(t,e,r),t=t.sibling}var nc=null,yf=!1;function Dy(t,e,r){for(r=r.child;r!==null;)jge(t,e,r),r=r.sibling}function jge(t,e,r){if(qm&&typeof qm.onCommitFiberUnmount=="function")try{qm.onCommitFiberUnmount(r3,r)}catch{}switch(r.tag){case 5:Dc||Y1(r,e);case 6:var n=nc,i=yf;nc=null,Dy(t,e,r),nc=n,yf=i,nc!==null&&(yf?(t=nc,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):nc.removeChild(r.stateNode));break;case 18:nc!==null&&(yf?(t=nc,r=r.stateNode,t.nodeType===8?Lz(t.parentNode,r):t.nodeType===1&&Lz(t,r),BA(t)):Lz(nc,r.stateNode));break;case 4:n=nc,i=yf,nc=r.stateNode.containerInfo,yf=!0,Dy(t,e,r),nc=n,yf=i;break;case 0:case 11:case 14:case 15:if(!Dc&&(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)&&g8(r,e,c),i=i.next}while(i!==n)}Dy(t,e,r);break;case 1:if(!Dc&&(Y1(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(a){Co(r,e,a)}Dy(t,e,r);break;case 21:Dy(t,e,r);break;case 22:r.mode&1?(Dc=(n=Dc)||r.memoizedState!==null,Dy(t,e,r),Dc=n):Dy(t,e,r);break;default:Dy(t,e,r)}}function qre(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new l4e),e.forEach(function(n){var i=x4e.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function sf(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~o}if(n=i,n=$o()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*d4e(n/1960))-n,10t?16:t,bx===null)var n=!1;else{if(t=bx,bx=null,zD=0,Ni&6)throw Error(Yr(331));var i=Ni;for(Ni|=4,In=t.current;In!==null;){var o=In,c=o.child;if(In.flags&16){var a=o.deletions;if(a!==null){for(var f=0;f$o()-pH?I_(t,0):mH|=r),ed(t,e)}function Rge(t,e){e===0&&(t.mode&1?(e=ZR,ZR<<=1,!(ZR&130023424)&&(ZR=4194304)):e=1);var r=Tu();t=Ag(t,e),t!==null&&(bC(t,e,r),ed(t,r))}function y4e(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),Rge(t,r)}function x4e(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(Yr(314))}n!==null&&n.delete(e),Rge(t,r)}var Lge;Lge=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||Qu.current)Yu=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return Yu=!1,i4e(t,e,r);Yu=!!(t.flags&131072)}else Yu=!1,eo&&e.flags&1048576&&Fpe(e,PD,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;RM(t,e),t=e.pendingProps;var i=HS(e,$c.current);hS(e,r),i=lH(null,e,n,t,i,r);var o=cH();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,Ju(n)?(o=!0,CD(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,nH(e),i.updater=c3,e.stateNode=i,i._reactInternals=e,c8(e,n,t,r),e=h8(null,e,n,!0,o,r)):(e.tag=0,eo&&o&&Z7(e),fu(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(RM(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=_4e(n),t=mf(n,t),i){case 0:e=d8(null,e,n,t,r);break e;case 1:e=Bre(null,e,n,t,r);break e;case 11:e=Ore(null,e,n,t,r);break e;case 14:e=Fre(null,e,n,mf(n.type,t),r);break e}throw Error(Yr(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:mf(n,i),d8(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:mf(n,i),Bre(t,e,n,i,r);case 3:e:{if(yge(e),t===null)throw Error(Yr(387));n=e.pendingProps,o=e.memoizedState,i=o.element,qpe(t,e),MD(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=ZS(Error(Yr(423)),e),e=$re(t,e,n,r,i);break e}else if(n!==i){i=ZS(Error(Yr(424)),e),e=$re(t,e,n,r,i);break e}else for(Pd=Ix(e.stateNode.containerInfo.firstChild),Md=e,eo=!0,bf=null,r=Upe(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(WS(),n===i){e=Ng(t,e,r);break e}fu(t,e,n,r)}e=e.child}return e;case 5:return Gpe(e),t===null&&a8(e),n=e.type,i=e.pendingProps,o=t!==null?t.memoizedProps:null,c=i.children,t8(n,i)?c=null:o!==null&&t8(n,o)&&(e.flags|=32),gge(t,e),fu(t,e,c,r),e.child;case 6:return t===null&&a8(e),null;case 13:return xge(t,e,r);case 4:return sH(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=KS(e,null,n,r):fu(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:mf(n,i),Ore(t,e,n,i,r);case 7:return fu(t,e,e.pendingProps,r),e.child;case 8:return fu(t,e,e.pendingProps.children,r),e.child;case 12:return fu(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,Ca(RD,n._currentValue),n._currentValue=c,o!==null)if($f(o.value,c)){if(o.children===i.children&&!Qu.current){e=Ng(t,e,r);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var a=o.dependencies;if(a!==null){c=o.child;for(var f=a.firstContext;f!==null;){if(f.context===n){if(o.tag===1){f=vg(-1,r&-r),f.tag=2;var m=o.updateQueue;if(m!==null){m=m.shared;var y=m.pending;y===null?f.next=f:(f.next=y.next,y.next=f),m.pending=f}}o.lanes|=r,f=o.alternate,f!==null&&(f.lanes|=r),o8(o.return,r,e),a.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(Yr(341));c.lanes|=r,a=c.alternate,a!==null&&(a.lanes|=r),o8(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}fu(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,hS(e,r),i=Ch(i),n=n(i),e.flags|=1,fu(t,e,n,r),e.child;case 14:return n=e.type,i=mf(n,e.pendingProps),i=mf(n.type,i),Fre(t,e,n,i,r);case 15:return mge(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:mf(n,i),RM(t,e),e.tag=1,Ju(n)?(t=!0,CD(e)):t=!1,hS(e,r),dge(e,n,i),c8(e,n,i,r),h8(null,e,n,!0,t,r);case 19:return vge(t,e,r);case 22:return pge(t,e,r)}throw Error(Yr(156,e.tag))};function Mge(t,e){return lpe(t,e)}function v4e(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 wh(t,e,r,n){return new v4e(t,e,r,n)}function vH(t){return t=t.prototype,!(!t||!t.isReactComponent)}function _4e(t){if(typeof t=="function")return vH(t)?1:0;if(t!=null){if(t=t.$$typeof,t===F7)return 11;if(t===B7)return 14}return 2}function Mx(t,e){var r=t.alternate;return r===null?(r=wh(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 DM(t,e,r,n,i,o){var c=2;if(n=t,typeof t=="function")vH(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case $1:return P_(r.children,i,o,e);case O7:c=8,i|=8;break;case RV:return t=wh(12,r,e,i|2),t.elementType=RV,t.lanes=o,t;case LV:return t=wh(13,r,e,i),t.elementType=LV,t.lanes=o,t;case MV:return t=wh(19,r,e,i),t.elementType=MV,t.lanes=o,t;case Gme:return h3(r,i,o,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case Vme:c=10;break e;case qme:c=9;break e;case F7:c=11;break e;case B7:c=14;break e;case Jy:c=16,n=null;break e}throw Error(Yr(130,t==null?t:typeof t,""))}return e=wh(c,r,e,i),e.elementType=t,e.type=n,e.lanes=o,e}function P_(t,e,r,n){return t=wh(7,t,n,e),t.lanes=r,t}function h3(t,e,r,n){return t=wh(22,t,n,e),t.elementType=Gme,t.lanes=r,t.stateNode={isHidden:!1},t}function Uz(t,e,r){return t=wh(6,t,null,e),t.lanes=r,t}function Vz(t,e,r){return e=wh(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function b4e(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=Sz(0),this.expirationTimes=Sz(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Sz(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function _H(t,e,r,n,i,o,c,a,f){return t=new b4e(t,e,r,a,f),e===1?(e=1,o===!0&&(e|=8)):e=0,o=wh(3,null,null,e),t.current=o,o.stateNode=t,o.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},nH(o),t}function w4e(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Bge)}catch(t){console.error(t)}}Bge(),Bme.exports=Gd;var op=Bme.exports;const $ge=wi(op);var zge,Qre=op;zge=Qre.createRoot,Qre.hydrateRoot;const Jre="levelup:chunk-reload";function k4e(t){return!!(t&&/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(t))}function A4e(t,e,r){if(!k4e(t))return!1;try{if(e.getItem(Jre))return!1;e.setItem(Jre,"1")}catch{return!1}return r(),!0}function N4e(t,e){const r=t.payload,n=r instanceof Error?r.message:typeof r=="string"?r:void 0;e(n)}const C4e="modulepreload",I4e=function(t){return"/"+t},ene={},Oe=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),a=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(f=>{if(f=I4e(f),f in ene)return;ene[f]=!0;const m=f.endsWith(".css"),y=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const v=document.createElement("link");if(v.rel=m?"stylesheet":C4e,m||(v.as="script"),v.crossOrigin="",v.href=f,a&&v.setAttribute("nonce",a),document.head.appendChild(v),m)return new Promise((w,j)=>{v.addEventListener("load",w),v.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=c,window.dispatchEvent(a),!a.defaultPrevented)throw c}return i.then(c=>{for(const a of c||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})},P4e=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),R4e=t=>t.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function L4e(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")||P4e.has(t))}function Uge(t){return Vge(t)!==null}function Vge(t){const e=R4e(t);return L4e(e)?null:e}const M4e=1,D4e=1e6;let qz=0;function O4e(){return qz=(qz+1)%Number.MAX_SAFE_INTEGER,qz.toString()}const Gz=new Map,tne=t=>{if(Gz.has(t))return;const e=setTimeout(()=>{Gz.delete(t),uA({type:"REMOVE_TOAST",toastId:t})},D4e);Gz.set(t,e)},F4e=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,M4e)};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?tne(r):t.toasts.forEach(n=>{tne(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)}}},OM=[];let FM={toasts:[]};function uA(t){FM=F4e(FM,t),OM.forEach(e=>{e(FM)})}function Fi({...t}){const e=O4e(),r=i=>uA({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>uA({type:"DISMISS_TOAST",toastId:e});return uA({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function qge(){const[t,e]=N.useState(FM);return N.useEffect(()=>(OM.push(e),()=>{const r=OM.indexOf(e);r>-1&&OM.splice(r,1)}),[t]),{...t,toast:Fi,dismiss:r=>uA({type:"DISMISS_TOAST",toastId:r})}}function Gr(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 rne(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Cg(...t){return e=>{let r=!1;const n=t.map(i=>{const o=rne(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{children:c,...a}=o,f=N.useMemo(()=>a,Object.values(a));return s.jsx(r.Provider,{value:f,children:c})};n.displayName=t+"Provider";function i(o){const c=N.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 dl(t,e=[]){let r=[];function n(o,c){const a=N.createContext(c),f=r.length;r=[...r,c];const m=v=>{var M;const{scope:w,children:j,...A}=v,C=((M=w==null?void 0:w[t])==null?void 0:M[f])||a,I=N.useMemo(()=>A,Object.values(A));return s.jsx(C.Provider,{value:I,children:j})};m.displayName=o+"Provider";function y(v,w){var C;const j=((C=w==null?void 0:w[t])==null?void 0:C[f])||a,A=N.useContext(j);if(A)return A;if(c!==void 0)return c;throw new Error(`\`${v}\` must be used within \`${o}\``)}return[m,y]}const i=()=>{const o=r.map(c=>N.createContext(c));return function(a){const f=(a==null?void 0:a[t])||o;return N.useMemo(()=>({[`__scope${t}`]:{...a,[t]:f}}),[a,f])}};return i.scopeName=t,[n,$4e(i,...e)]}function $4e(...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((a,{useScope:f,scopeName:m})=>{const v=f(o)[`__scope${m}`];return{...a,...v}},{});return N.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])}};return r.scopeName=e.scopeName,r}function Gx(t){const e=z4e(t),r=N.forwardRef((n,i)=>{const{children:o,...c}=n,a=N.Children.toArray(o),f=a.find(U4e);if(f){const m=f.props.children,y=a.map(v=>v===f?N.Children.count(m)>1?N.Children.only(null):N.isValidElement(m)?m.props.children:null:v);return s.jsx(e,{...c,ref:i,children:N.isValidElement(m)?N.cloneElement(m,void 0,y):null})}return s.jsx(e,{...c,ref:i,children:o})});return r.displayName=`${t}.Slot`,r}var Gge=Gx("Slot");function z4e(t){const e=N.forwardRef((r,n)=>{const{children:i,...o}=r;if(N.isValidElement(i)){const c=q4e(i),a=V4e(o,i.props);return i.type!==N.Fragment&&(a.ref=n?Cg(n,c):c),N.cloneElement(i,a)}return N.Children.count(i)>1?N.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Hge=Symbol("radix.slottable");function Wge(t){const e=({children:r})=>s.jsx(s.Fragment,{children:r});return e.displayName=`${t}.Slottable`,e.__radixId=Hge,e}function U4e(t){return N.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Hge}function V4e(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]=(...a)=>{const f=o(...a);return i(...a),f}:i&&(r[n]=i):n==="style"?r[n]={...i,...o}:n==="className"&&(r[n]=[i,o].filter(Boolean).join(" "))}return{...t,...r}}function q4e(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 jC(t){const e=t+"CollectionProvider",[r,n]=dl(e),[i,o]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=C=>{const{scope:I,children:M}=C,D=Qe.useRef(null),F=Qe.useRef(new Map).current;return s.jsx(i,{scope:I,itemMap:F,collectionRef:D,children:M})};c.displayName=e;const a=t+"CollectionSlot",f=Gx(a),m=Qe.forwardRef((C,I)=>{const{scope:M,children:D}=C,F=o(a,M),z=is(I,F.collectionRef);return s.jsx(f,{ref:z,children:D})});m.displayName=a;const y=t+"CollectionItemSlot",v="data-radix-collection-item",w=Gx(y),j=Qe.forwardRef((C,I)=>{const{scope:M,children:D,...F}=C,z=Qe.useRef(null),q=is(I,z),H=o(y,M);return Qe.useEffect(()=>(H.itemMap.set(z,{ref:z,...F}),()=>void H.itemMap.delete(z))),s.jsx(w,{[v]:"",ref:q,children:D})});j.displayName=y;function A(C){const I=o(t+"CollectionConsumer",C);return Qe.useCallback(()=>{const D=I.collectionRef.current;if(!D)return[];const F=Array.from(D.querySelectorAll(`[${v}]`));return Array.from(I.itemMap.values()).sort((H,K)=>F.indexOf(H.ref.current)-F.indexOf(K.ref.current))},[I.collectionRef,I.itemMap])}return[{Provider:c,Slot:m,ItemSlot:j},A,n]}var G4e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],cn=G4e.reduce((t,e)=>{const r=Gx(`Primitive.${e}`),n=N.forwardRef((i,o)=>{const{asChild:c,...a}=i,f=c?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(f,{...a,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function TH(t,e){t&&op.flushSync(()=>t.dispatchEvent(e))}function go(t){const e=N.useRef(t);return N.useEffect(()=>{e.current=t}),N.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}function H4e(t,e=globalThis==null?void 0:globalThis.document){const r=go(t);N.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 W4e="DismissableLayer",T8="dismissableLayer.update",K4e="dismissableLayer.pointerDownOutside",Y4e="dismissableLayer.focusOutside",nne,Kge=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fb=N.forwardRef((t,e)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:c,onDismiss:a,...f}=t,m=N.useContext(Kge),[y,v]=N.useState(null),w=(y==null?void 0:y.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,j]=N.useState({}),A=is(e,K=>v(K)),C=Array.from(m.layers),[I]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),M=C.indexOf(I),D=y?C.indexOf(y):-1,F=m.layersWithOutsidePointerEventsDisabled.size>0,z=D>=M,q=X4e(K=>{const J=K.target,Q=[...m.branches].some(ee=>ee.contains(J));!z||Q||(i==null||i(K),c==null||c(K),K.defaultPrevented||a==null||a())},w),H=Q4e(K=>{const J=K.target;[...m.branches].some(ee=>ee.contains(J))||(o==null||o(K),c==null||c(K),K.defaultPrevented||a==null||a())},w);return H4e(K=>{D===m.layers.size-1&&(n==null||n(K),!K.defaultPrevented&&a&&(K.preventDefault(),a()))},w),N.useEffect(()=>{if(y)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(nne=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(y)),m.layers.add(y),sne(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=nne)}},[y,w,r,m]),N.useEffect(()=>()=>{y&&(m.layers.delete(y),m.layersWithOutsidePointerEventsDisabled.delete(y),sne())},[y,m]),N.useEffect(()=>{const K=()=>j({});return document.addEventListener(T8,K),()=>document.removeEventListener(T8,K)},[]),s.jsx(cn.div,{...f,ref:A,style:{pointerEvents:F?z?"auto":"none":void 0,...t.style},onFocusCapture:Gr(t.onFocusCapture,H.onFocusCapture),onBlurCapture:Gr(t.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Gr(t.onPointerDownCapture,q.onPointerDownCapture)})});fb.displayName=W4e;var Z4e="DismissableLayerBranch",Yge=N.forwardRef((t,e)=>{const r=N.useContext(Kge),n=N.useRef(null),i=is(e,n);return N.useEffect(()=>{const o=n.current;if(o)return r.branches.add(o),()=>{r.branches.delete(o)}},[r.branches]),s.jsx(cn.div,{...t,ref:i})});Yge.displayName=Z4e;function X4e(t,e=globalThis==null?void 0:globalThis.document){const r=go(t),n=N.useRef(!1),i=N.useRef(()=>{});return N.useEffect(()=>{const o=a=>{if(a.target&&!n.current){let f=function(){Zge(K4e,r,m,{discrete:!0})};const m={originalEvent:a};a.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 Q4e(t,e=globalThis==null?void 0:globalThis.document){const r=go(t),n=N.useRef(!1);return N.useEffect(()=>{const i=o=>{o.target&&!n.current&&Zge(Y4e,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 sne(){const t=new CustomEvent(T8);document.dispatchEvent(t)}function Zge(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?TH(i,o):i.dispatchEvent(o)}var J4e=fb,e3e=Yge,Ho=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},t3e="Portal",KT=N.forwardRef((t,e)=>{var a;const{container:r,...n}=t,[i,o]=N.useState(!1);Ho(()=>o(!0),[]);const c=r||i&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return c?$ge.createPortal(s.jsx(cn.div,{...n,ref:e}),c):null});KT.displayName=t3e;function r3e(t,e){return N.useReducer((r,n)=>e[r][n]??r,t)}var Pl=t=>{const{present:e,children:r}=t,n=n3e(e),i=typeof r=="function"?r({present:n.isPresent}):N.Children.only(r),o=is(n.ref,s3e(i));return typeof r=="function"||n.isPresent?N.cloneElement(i,{ref:o}):null};Pl.displayName="Presence";function n3e(t){const[e,r]=N.useState(),n=N.useRef(null),i=N.useRef(t),o=N.useRef("none"),c=t?"mounted":"unmounted",[a,f]=r3e(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{const m=lL(n.current);o.current=a==="mounted"?m:"none"},[a]),Ho(()=>{const m=n.current,y=i.current;if(y!==t){const w=o.current,j=lL(m);t?f("MOUNT"):j==="none"||(m==null?void 0:m.display)==="none"?f("UNMOUNT"):f(y&&w!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,f]),Ho(()=>{if(e){let m;const y=e.ownerDocument.defaultView??window,v=j=>{const C=lL(n.current).includes(j.animationName);if(j.target===e&&C&&(f("ANIMATION_END"),!i.current)){const I=e.style.animationFillMode;e.style.animationFillMode="forwards",m=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=I)})}},w=j=>{j.target===e&&(o.current=lL(n.current))};return e.addEventListener("animationstart",w),e.addEventListener("animationcancel",v),e.addEventListener("animationend",v),()=>{y.clearTimeout(m),e.removeEventListener("animationstart",w),e.removeEventListener("animationcancel",v),e.removeEventListener("animationend",v)}}else f("ANIMATION_END")},[e,f]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:N.useCallback(m=>{n.current=m?getComputedStyle(m):null,r(m)},[])}}function lL(t){return(t==null?void 0:t.animationName)||"none"}function s3e(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 i3e=R7[" useInsertionEffect ".trim().toString()]||Ho;function rd({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){const[i,o,c]=a3e({defaultProp:e,onChange:r}),a=t!==void 0,f=a?t:i;{const y=N.useRef(t!==void 0);N.useEffect(()=>{const v=y.current;v!==a&&console.warn(`${n} is changing from ${v?"controlled":"uncontrolled"} to ${a?"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=a},[a,n])}const m=N.useCallback(y=>{var v;if(a){const w=o3e(y)?y(t):y;w!==t&&((v=c.current)==null||v.call(c,w))}else o(y)},[a,t,o,c]);return[f,m]}function a3e({defaultProp:t,onChange:e}){const[r,n]=N.useState(t),i=N.useRef(r),o=N.useRef(e);return i3e(()=>{o.current=e},[e]),N.useEffect(()=>{var c;i.current!==r&&((c=o.current)==null||c.call(o,r),i.current=r)},[r,i]),[r,n,o]}function o3e(t){return typeof t=="function"}var Xge=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"}),l3e="VisuallyHidden",y3=N.forwardRef((t,e)=>s.jsx(cn.span,{...t,ref:e,style:{...Xge,...t.style}}));y3.displayName=l3e;var c3e=y3,jH="ToastProvider",[EH,u3e,d3e]=jC("Toast"),[Qge,jJt]=dl("Toast",[d3e]),[h3e,x3]=Qge(jH),Jge=t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:c}=t,[a,f]=N.useState(null),[m,y]=N.useState(0),v=N.useRef(!1),w=N.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${jH}\`. Expected non-empty \`string\`.`),s.jsx(EH.Provider,{scope:e,children:s.jsx(h3e,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:o,toastCount:m,viewport:a,onViewportChange:f,onToastAdd:N.useCallback(()=>y(j=>j+1),[]),onToastRemove:N.useCallback(()=>y(j=>j-1),[]),isFocusedToastEscapeKeyDownRef:v,isClosePausedRef:w,children:c})})};Jge.displayName=jH;var eye="ToastViewport",f3e=["F8"],j8="toast.viewportPause",E8="toast.viewportResume",tye=N.forwardRef((t,e)=>{const{__scopeToast:r,hotkey:n=f3e,label:i="Notifications ({hotkey})",...o}=t,c=x3(eye,r),a=u3e(r),f=N.useRef(null),m=N.useRef(null),y=N.useRef(null),v=N.useRef(null),w=is(e,v,c.onViewportChange),j=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),A=c.toastCount>0;N.useEffect(()=>{const I=M=>{var F;n.length!==0&&n.every(z=>M[z]||M.code===z)&&((F=v.current)==null||F.focus())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[n]),N.useEffect(()=>{const I=f.current,M=v.current;if(A&&I&&M){const D=()=>{if(!c.isClosePausedRef.current){const H=new CustomEvent(j8);M.dispatchEvent(H),c.isClosePausedRef.current=!0}},F=()=>{if(c.isClosePausedRef.current){const H=new CustomEvent(E8);M.dispatchEvent(H),c.isClosePausedRef.current=!1}},z=H=>{!I.contains(H.relatedTarget)&&F()},q=()=>{I.contains(document.activeElement)||F()};return I.addEventListener("focusin",D),I.addEventListener("focusout",z),I.addEventListener("pointermove",D),I.addEventListener("pointerleave",q),window.addEventListener("blur",D),window.addEventListener("focus",F),()=>{I.removeEventListener("focusin",D),I.removeEventListener("focusout",z),I.removeEventListener("pointermove",D),I.removeEventListener("pointerleave",q),window.removeEventListener("blur",D),window.removeEventListener("focus",F)}}},[A,c.isClosePausedRef]);const C=N.useCallback(({tabbingDirection:I})=>{const D=a().map(F=>{const z=F.ref.current,q=[z,...E3e(z)];return I==="forwards"?q:q.reverse()});return(I==="forwards"?D.reverse():D).flat()},[a]);return N.useEffect(()=>{const I=v.current;if(I){const M=D=>{var q,H,K;const F=D.altKey||D.ctrlKey||D.metaKey;if(D.key==="Tab"&&!F){const J=document.activeElement,Q=D.shiftKey;if(D.target===I&&Q){(q=m.current)==null||q.focus();return}const de=C({tabbingDirection:Q?"backwards":"forwards"}),ye=de.findIndex(we=>we===J);Hz(de.slice(ye+1))?D.preventDefault():Q?(H=m.current)==null||H.focus():(K=y.current)==null||K.focus()}};return I.addEventListener("keydown",M),()=>I.removeEventListener("keydown",M)}},[a,C]),s.jsxs(e3e,{ref:f,role:"region","aria-label":i.replace("{hotkey}",j),tabIndex:-1,style:{pointerEvents:A?void 0:"none"},children:[A&&s.jsx(k8,{ref:m,onFocusFromOutsideViewport:()=>{const I=C({tabbingDirection:"forwards"});Hz(I)}}),s.jsx(EH.Slot,{scope:r,children:s.jsx(cn.ol,{tabIndex:-1,...o,ref:w})}),A&&s.jsx(k8,{ref:y,onFocusFromOutsideViewport:()=>{const I=C({tabbingDirection:"backwards"});Hz(I)}})]})});tye.displayName=eye;var rye="ToastFocusProxy",k8=N.forwardRef((t,e)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...i}=t,o=x3(rye,r);return s.jsx(y3,{"aria-hidden":!0,tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:c=>{var m;const a=c.relatedTarget;!((m=o.viewport)!=null&&m.contains(a))&&n()}})});k8.displayName=rye;var EC="Toast",m3e="toast.swipeStart",p3e="toast.swipeMove",g3e="toast.swipeCancel",y3e="toast.swipeEnd",nye=N.forwardRef((t,e)=>{const{forceMount:r,open:n,defaultOpen:i,onOpenChange:o,...c}=t,[a,f]=rd({prop:n,defaultProp:i??!0,onChange:o,caller:EC});return s.jsx(Pl,{present:r||a,children:s.jsx(_3e,{open:a,...c,ref:e,onClose:()=>f(!1),onPause:go(t.onPause),onResume:go(t.onResume),onSwipeStart:Gr(t.onSwipeStart,m=>{m.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Gr(t.onSwipeMove,m=>{const{x:y,y:v}=m.detail.delta;m.currentTarget.setAttribute("data-swipe","move"),m.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${y}px`),m.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${v}px`)}),onSwipeCancel:Gr(t.onSwipeCancel,m=>{m.currentTarget.setAttribute("data-swipe","cancel"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),m.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Gr(t.onSwipeEnd,m=>{const{x:y,y:v}=m.detail.delta;m.currentTarget.setAttribute("data-swipe","end"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),m.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${y}px`),m.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${v}px`),f(!1)})})})});nye.displayName=EC;var[x3e,v3e]=Qge(EC,{onClose(){}}),_3e=N.forwardRef((t,e)=>{const{__scopeToast:r,type:n="foreground",duration:i,open:o,onClose:c,onEscapeKeyDown:a,onPause:f,onResume:m,onSwipeStart:y,onSwipeMove:v,onSwipeCancel:w,onSwipeEnd:j,...A}=t,C=x3(EC,r),[I,M]=N.useState(null),D=is(e,we=>M(we)),F=N.useRef(null),z=N.useRef(null),q=i||C.duration,H=N.useRef(0),K=N.useRef(q),J=N.useRef(0),{onToastAdd:Q,onToastRemove:ee}=C,oe=go(()=>{var Le;(I==null?void 0:I.contains(document.activeElement))&&((Le=C.viewport)==null||Le.focus()),c()}),de=N.useCallback(we=>{!we||we===1/0||(window.clearTimeout(J.current),H.current=new Date().getTime(),J.current=window.setTimeout(oe,we))},[oe]);N.useEffect(()=>{const we=C.viewport;if(we){const Le=()=>{de(K.current),m==null||m()},Se=()=>{const ve=new Date().getTime()-H.current;K.current=K.current-ve,window.clearTimeout(J.current),f==null||f()};return we.addEventListener(j8,Se),we.addEventListener(E8,Le),()=>{we.removeEventListener(j8,Se),we.removeEventListener(E8,Le)}}},[C.viewport,q,f,m,de]),N.useEffect(()=>{o&&!C.isClosePausedRef.current&&de(q)},[o,q,C.isClosePausedRef,de]),N.useEffect(()=>(Q(),()=>ee()),[Q,ee]);const ye=N.useMemo(()=>I?uye(I):null,[I]);return C.viewport?s.jsxs(s.Fragment,{children:[ye&&s.jsx(b3e,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:ye}),s.jsx(x3e,{scope:r,onClose:oe,children:op.createPortal(s.jsx(EH.ItemSlot,{scope:r,children:s.jsx(J4e,{asChild:!0,onEscapeKeyDown:Gr(a,()=>{C.isFocusedToastEscapeKeyDownRef.current||oe(),C.isFocusedToastEscapeKeyDownRef.current=!1}),children:s.jsx(cn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":C.swipeDirection,...A,ref:D,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Gr(t.onKeyDown,we=>{we.key==="Escape"&&(a==null||a(we.nativeEvent),we.nativeEvent.defaultPrevented||(C.isFocusedToastEscapeKeyDownRef.current=!0,oe()))}),onPointerDown:Gr(t.onPointerDown,we=>{we.button===0&&(F.current={x:we.clientX,y:we.clientY})}),onPointerMove:Gr(t.onPointerMove,we=>{if(!F.current)return;const Le=we.clientX-F.current.x,Se=we.clientY-F.current.y,ve=!!z.current,me=["left","right"].includes(C.swipeDirection),ke=["left","up"].includes(C.swipeDirection)?Math.min:Math.max,Pe=me?ke(0,Le):0,Ee=me?0:ke(0,Se),xe=we.pointerType==="touch"?10:2,Ue={x:Pe,y:Ee},Ze={originalEvent:we,delta:Ue};ve?(z.current=Ue,cL(p3e,v,Ze,{discrete:!1})):ine(Ue,C.swipeDirection,xe)?(z.current=Ue,cL(m3e,y,Ze,{discrete:!1}),we.target.setPointerCapture(we.pointerId)):(Math.abs(Le)>xe||Math.abs(Se)>xe)&&(F.current=null)}),onPointerUp:Gr(t.onPointerUp,we=>{const Le=z.current,Se=we.target;if(Se.hasPointerCapture(we.pointerId)&&Se.releasePointerCapture(we.pointerId),z.current=null,F.current=null,Le){const ve=we.currentTarget,me={originalEvent:we,delta:Le};ine(Le,C.swipeDirection,C.swipeThreshold)?cL(y3e,j,me,{discrete:!0}):cL(g3e,w,me,{discrete:!0}),ve.addEventListener("click",ke=>ke.preventDefault(),{once:!0})}})})})}),C.viewport)})]}):null}),b3e=t=>{const{__scopeToast:e,children:r,...n}=t,i=x3(EC,e),[o,c]=N.useState(!1),[a,f]=N.useState(!1);return T3e(()=>c(!0)),N.useEffect(()=>{const m=window.setTimeout(()=>f(!0),1e3);return()=>window.clearTimeout(m)},[]),a?null:s.jsx(KT,{asChild:!0,children:s.jsx(y3,{...n,children:o&&s.jsxs(s.Fragment,{children:[i.label," ",r]})})})},w3e="ToastTitle",sye=N.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(cn.div,{...n,ref:e})});sye.displayName=w3e;var S3e="ToastDescription",iye=N.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(cn.div,{...n,ref:e})});iye.displayName=S3e;var aye="ToastAction",oye=N.forwardRef((t,e)=>{const{altText:r,...n}=t;return r.trim()?s.jsx(cye,{altText:r,asChild:!0,children:s.jsx(kH,{...n,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${aye}\`. Expected non-empty \`string\`.`),null)});oye.displayName=aye;var lye="ToastClose",kH=N.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t,i=v3e(lye,r);return s.jsx(cye,{asChild:!0,children:s.jsx(cn.button,{type:"button",...n,ref:e,onClick:Gr(t.onClick,i.onClose)})})});kH.displayName=lye;var cye=N.forwardRef((t,e)=>{const{__scopeToast:r,altText:n,...i}=t;return s.jsx(cn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...i,ref:e})});function uye(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),j3e(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(...uye(n))}}),e}function cL(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?TH(i,o):i.dispatchEvent(o)}var ine=(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 T3e(t=()=>{}){const e=go(t);Ho(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}function j3e(t){return t.nodeType===t.ELEMENT_NODE}function E3e(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 Hz(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}var k3e=Jge,dye=tye,hye=nye,fye=sye,mye=iye,pye=oye,gye=kH;function yye(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,one=Ws,YT=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return one(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:o}=e,c=Object.keys(i).map(m=>{const y=r==null?void 0:r[m],v=o==null?void 0:o[m];if(y===null)return null;const w=ane(y)||ane(v);return i[m][w]}),a=r&&Object.entries(r).reduce((m,y)=>{let[v,w]=y;return w===void 0||(m[v]=w),m},{}),f=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((m,y)=>{let{class:v,className:w,...j}=y;return Object.entries(j).every(A=>{let[C,I]=A;return Array.isArray(I)?I.includes({...o,...a}[C]):{...o,...a}[C]===I})?[...m,v,w]:m},[]);return one(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 A3e=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),xye=(...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 N3e={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 C3e=N.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:c,...a},f)=>N.createElement("svg",{ref:f,...N3e,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:xye("lucide",i),...a},[...c.map(([m,y])=>N.createElement(m,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 dr=(t,e)=>{const r=N.forwardRef(({className:n,...i},o)=>N.createElement(C3e,{ref:o,iconNode:e,className:xye(`lucide-${A3e(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 lne=dr("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 Hx=dr("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 ei=dr("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 I3e=dr("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 ju=dr("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 mS=dr("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 m0=dr("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 vye=dr("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 ZT=dr("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 kC=dr("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 QS=dr("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 qD=dr("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 P3e=dr("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 A8=dr("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 to=dr("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 R3e=dr("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 N8=dr("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 AH=dr("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 NH=dr("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 Hm=dr("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 _ye=dr("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 bo=dr("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 cne=dr("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 XA=dr("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 pa=dr("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 Wo=dr("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 lp=dr("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 Wd=dr("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 bye=dr("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 C8=dr("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 wye=dr("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 Il=dr("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 L3e=dr("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 CH=dr("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 W_=dr("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 I8=dr("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 Wz=dr("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 Hl=dr("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 une=dr("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 GD=dr("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 _g=dr("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 yc=dr("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 M3e=dr("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 D3e=dr("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 mb=dr("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 v3=dr("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 IH=dr("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 O3e=dr("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 F3e=dr("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 Qm=dr("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 dne=dr("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 B3e=dr("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 $3e=dr("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sye=dr("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 z3e=dr("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mf=dr("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 R_=dr("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 QA=dr("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 U3e=dr("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 V3e=dr("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q3e=dr("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 P8=dr("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 Jm=dr("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 ta=dr("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 hne=dr("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 PH=dr("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 RH=dr("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 LH=dr("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 Tye=dr("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 _3=dr("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 G3e=dr("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 jye=dr("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 H3e=dr("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 W3e=dr("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 K3e=dr("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 fne=dr("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 MH=dr("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 Y3e=dr("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 R8=dr("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 zc=dr("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 Wx=dr("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 b3=dr("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rs=dr("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 ii=dr("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 Z3e=dr("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 X3e=dr("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 L_=dr("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 p0=dr("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 Q3e=dr("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 K_=dr("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 Ph=dr("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 J3e=dr("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 eFe=dr("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eye=dr("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 tFe=dr("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 mne=dr("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 w3=dr("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 rFe=dr("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 kye=dr("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 nFe=dr("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 sFe=dr("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 Fn=dr("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 iFe=dr("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 HD=dr("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 Wm=dr("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 aFe=dr("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 oFe=dr("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/** * @license lucide-react v0.462.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=dr("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 L8=dr("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 WD=dr("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 Aye=dr("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 Kz=dr("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 cFe=dr("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AC=dr("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 uFe=dr("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/** * @license lucide-react v0.462.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=dr("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 nd=dr("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 JA=dr("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 DH=dr("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 NC=dr("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 hFe=dr("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 S3=dr("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 eN=dr("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 Nye=dr("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 fFe=dr("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 Yz=dr("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 mFe=dr("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 ki=dr("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 pFe=dr("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 M8=dr("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 OH=dr("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 vc=dr("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 FH=dr("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 gFe=dr("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 CC=dr("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 yFe=dr("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 Cye=dr("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 KD=dr("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 Iye=dr("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 Df=dr("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 XT=dr("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 YD=dr("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 D8=dr("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 O8=dr("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 T3=dr("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 Wl=dr("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 kl=dr("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=dr("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 Pye=dr("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 Rye=dr("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 j3=dr("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 xFe=dr("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 BH=dr("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 Ci=dr("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 Lye=dr("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 JS=dr("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 pne=dr("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"}]]),$H="-",vFe=t=>{const e=bFe(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const a=c.split($H);return a[0]===""&&a.length!==1&&a.shift(),Mye(a,e)||_Fe(c)},getConflictingClassGroupIds:(c,a)=>{const f=r[c]||[];return a&&n[c]?[...f,...n[c]]:f}}},Mye=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?Mye(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const o=t.join($H);return(c=e.validators.find(({validator:a})=>a(o)))==null?void 0:c.classGroupId},gne=/^\[(.+)\]$/,_Fe=t=>{if(gne.test(t)){const e=gne.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},bFe=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return SFe(Object.entries(t.classGroups),r).forEach(([o,c])=>{F8(c,n,o,e)}),n},F8=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const o=i===""?e:yne(e,i);o.classGroupId=r;return}if(typeof i=="function"){if(wFe(i)){F8(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([o,c])=>{F8(c,yne(e,o),r,n)})})},yne=(t,e)=>{let r=t;return e.split($H).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},wFe=t=>t.isThemeGetter,SFe=(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,a])=>[e+c,a])):o);return[r,i]}):t,TFe=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)}}},Dye="!",jFe=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],o=e.length,c=a=>{const f=[];let m=0,y=0,v;for(let I=0;Iy?v-y:void 0;return{modifiers:f,hasImportantModifier:j,baseClassName:A,maybePostfixModifierPosition:C}};return r?a=>r({className:a,parseClassName:c}):c},EFe=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},kFe=t=>({cache:TFe(t.cacheSize),parseClassName:jFe(t),...vFe(t)}),AFe=/\s+/,NFe=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,o=[],c=t.trim().split(AFe);let a="";for(let f=c.length-1;f>=0;f-=1){const m=c[f],{modifiers:y,hasImportantModifier:v,baseClassName:w,maybePostfixModifierPosition:j}=r(m);let A=!!j,C=n(A?w.substring(0,j):w);if(!C){if(!A){a=m+(a.length>0?" "+a:a);continue}if(C=n(w),!C){a=m+(a.length>0?" "+a:a);continue}A=!1}const I=EFe(y).join(":"),M=v?I+Dye:I,D=M+C;if(o.includes(D))continue;o.push(D);const F=i(C,A);for(let z=0;z0?" "+a:a)}return a};function CFe(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;nv(y),t());return r=kFe(m),n=r.cache.get,i=r.cache.set,o=a,a(f)}function a(f){const m=n(f);if(m)return m;const y=NFe(f,r);return i(f,y),y}return function(){return o(CFe.apply(null,arguments))}}const za=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},Fye=/^\[(?:([a-z-]+):)?(.+)\]$/i,PFe=/^\d+\/\d+$/,RFe=new Set(["px","full","screen"]),LFe=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,MFe=/\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$/,DFe=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,OFe=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,FFe=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Kp=t=>pS(t)||RFe.has(t)||PFe.test(t),Oy=t=>QT(t,"length",HFe),pS=t=>!!t&&!Number.isNaN(Number(t)),Zz=t=>QT(t,"number",pS),nk=t=>!!t&&Number.isInteger(Number(t)),BFe=t=>t.endsWith("%")&&pS(t.slice(0,-1)),qs=t=>Fye.test(t),Fy=t=>LFe.test(t),$Fe=new Set(["length","size","percentage"]),zFe=t=>QT(t,$Fe,Bye),UFe=t=>QT(t,"position",Bye),VFe=new Set(["image","url"]),qFe=t=>QT(t,VFe,KFe),GFe=t=>QT(t,"",WFe),sk=()=>!0,QT=(t,e,r)=>{const n=Fye.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},HFe=t=>MFe.test(t)&&!DFe.test(t),Bye=()=>!1,WFe=t=>OFe.test(t),KFe=t=>FFe.test(t),YFe=()=>{const t=za("colors"),e=za("spacing"),r=za("blur"),n=za("brightness"),i=za("borderColor"),o=za("borderRadius"),c=za("borderSpacing"),a=za("borderWidth"),f=za("contrast"),m=za("grayscale"),y=za("hueRotate"),v=za("invert"),w=za("gap"),j=za("gradientColorStops"),A=za("gradientColorStopPositions"),C=za("inset"),I=za("margin"),M=za("opacity"),D=za("padding"),F=za("saturate"),z=za("scale"),q=za("sepia"),H=za("skew"),K=za("space"),J=za("translate"),Q=()=>["auto","contain","none"],ee=()=>["auto","hidden","clip","visible","scroll"],oe=()=>["auto",qs,e],de=()=>[qs,e],ye=()=>["",Kp,Oy],we=()=>["auto",pS,qs],Le=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Se=()=>["solid","dashed","dotted","double","none"],ve=()=>["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"],ke=()=>["","0",qs],Pe=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Ee=()=>[pS,qs];return{cacheSize:500,separator:":",theme:{colors:[sk],spacing:[Kp,Oy],blur:["none","",Fy,qs],brightness:Ee(),borderColor:[t],borderRadius:["none","","full",Fy,qs],borderSpacing:de(),borderWidth:ye(),contrast:Ee(),grayscale:ke(),hueRotate:Ee(),invert:ke(),gap:de(),gradientColorStops:[t],gradientColorStopPositions:[BFe,Oy],inset:oe(),margin:oe(),opacity:Ee(),padding:de(),saturate:Ee(),scale:Ee(),sepia:ke(),skew:Ee(),space:de(),translate:de()},classGroups:{aspect:[{aspect:["auto","square","video",qs]}],container:["container"],columns:[{columns:[Fy]}],"break-after":[{"break-after":Pe()}],"break-before":[{"break-before":Pe()}],"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:[...Le(),qs]}],overflow:[{overflow:ee()}],"overflow-x":[{"overflow-x":ee()}],"overflow-y":[{"overflow-y":ee()}],overscroll:[{overscroll:Q()}],"overscroll-x":[{"overscroll-x":Q()}],"overscroll-y":[{"overscroll-y":Q()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[C]}],"inset-x":[{"inset-x":[C]}],"inset-y":[{"inset-y":[C]}],start:[{start:[C]}],end:[{end:[C]}],top:[{top:[C]}],right:[{right:[C]}],bottom:[{bottom:[C]}],left:[{left:[C]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nk,qs]}],basis:[{basis:oe()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",qs]}],grow:[{grow:ke()}],shrink:[{shrink:ke()}],order:[{order:["first","last","none",nk,qs]}],"grid-cols":[{"grid-cols":[sk]}],"col-start-end":[{col:["auto",{span:["full",nk,qs]},qs]}],"col-start":[{"col-start":we()}],"col-end":[{"col-end":we()}],"grid-rows":[{"grid-rows":[sk]}],"row-start-end":[{row:["auto",{span:[nk,qs]},qs]}],"row-start":[{"row-start":we()}],"row-end":[{"row-end":we()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",qs]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",qs]}],gap:[{gap:[w]}],"gap-x":[{"gap-x":[w]}],"gap-y":[{"gap-y":[w]}],"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:[D]}],px:[{px:[D]}],py:[{py:[D]}],ps:[{ps:[D]}],pe:[{pe:[D]}],pt:[{pt:[D]}],pr:[{pr:[D]}],pb:[{pb:[D]}],pl:[{pl:[D]}],m:[{m:[I]}],mx:[{mx:[I]}],my:[{my:[I]}],ms:[{ms:[I]}],me:[{me:[I]}],mt:[{mt:[I]}],mr:[{mr:[I]}],mb:[{mb:[I]}],ml:[{ml:[I]}],"space-x":[{"space-x":[K]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[K]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",qs,e]}],"min-w":[{"min-w":[qs,e,"min","max","fit"]}],"max-w":[{"max-w":[qs,e,"none","full","min","max","fit","prose",{screen:[Fy]},Fy]}],h:[{h:[qs,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[qs,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[qs,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[qs,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Fy,Oy]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Zz]}],"font-family":[{font:[sk]}],"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",qs]}],"line-clamp":[{"line-clamp":["none",pS,Zz]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Kp,qs]}],"list-image":[{"list-image":["none",qs]}],"list-style-type":[{list:["none","disc","decimal",qs]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[M]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[M]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Se(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Kp,Oy]}],"underline-offset":[{"underline-offset":["auto",Kp,qs]}],"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:de()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",qs]}],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",qs]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[M]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Le(),UFe]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",zFe]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},qFe]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[A]}],"gradient-via-pos":[{via:[A]}],"gradient-to-pos":[{to:[A]}],"gradient-from":[{from:[j]}],"gradient-via":[{via:[j]}],"gradient-to":[{to:[j]}],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:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[M]}],"border-style":[{border:[...Se(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[M]}],"divide-style":[{divide:Se()}],"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:["",...Se()]}],"outline-offset":[{"outline-offset":[Kp,qs]}],"outline-w":[{outline:[Kp,Oy]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:ye()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[M]}],"ring-offset-w":[{"ring-offset":[Kp,Oy]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Fy,GFe]}],"shadow-color":[{shadow:[sk]}],opacity:[{opacity:[M]}],"mix-blend":[{"mix-blend":[...ve(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ve()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[f]}],"drop-shadow":[{"drop-shadow":["","none",Fy,qs]}],grayscale:[{grayscale:[m]}],"hue-rotate":[{"hue-rotate":[y]}],invert:[{invert:[v]}],saturate:[{saturate:[F]}],sepia:[{sepia:[q]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[f]}],"backdrop-grayscale":[{"backdrop-grayscale":[m]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[y]}],"backdrop-invert":[{"backdrop-invert":[v]}],"backdrop-opacity":[{"backdrop-opacity":[M]}],"backdrop-saturate":[{"backdrop-saturate":[F]}],"backdrop-sepia":[{"backdrop-sepia":[q]}],"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",qs]}],duration:[{duration:Ee()}],ease:[{ease:["linear","in","out","in-out",qs]}],delay:[{delay:Ee()}],animate:[{animate:["none","spin","ping","pulse","bounce",qs]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[z]}],"scale-x":[{"scale-x":[z]}],"scale-y":[{"scale-y":[z]}],rotate:[{rotate:[nk,qs]}],"translate-x":[{"translate-x":[J]}],"translate-y":[{"translate-y":[J]}],"skew-x":[{"skew-x":[H]}],"skew-y":[{"skew-y":[H]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",qs]}],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",qs]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":de()}],"scroll-mx":[{"scroll-mx":de()}],"scroll-my":[{"scroll-my":de()}],"scroll-ms":[{"scroll-ms":de()}],"scroll-me":[{"scroll-me":de()}],"scroll-mt":[{"scroll-mt":de()}],"scroll-mr":[{"scroll-mr":de()}],"scroll-mb":[{"scroll-mb":de()}],"scroll-ml":[{"scroll-ml":de()}],"scroll-p":[{"scroll-p":de()}],"scroll-px":[{"scroll-px":de()}],"scroll-py":[{"scroll-py":de()}],"scroll-ps":[{"scroll-ps":de()}],"scroll-pe":[{"scroll-pe":de()}],"scroll-pt":[{"scroll-pt":de()}],"scroll-pr":[{"scroll-pr":de()}],"scroll-pb":[{"scroll-pb":de()}],"scroll-pl":[{"scroll-pl":de()}],"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",qs]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Kp,Oy,Zz]}],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"]}}},ZFe=IFe(YFe);function Xt(...t){return ZFe(Ws(t))}function Ja(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 xne(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}function EJt(t){return t?t.replace(/<[^>]*>/g,""):""}const XFe=k3e,$ye=N.forwardRef(({className:t,...e},r)=>s.jsx(dye,{ref:r,className:Xt("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}));$ye.displayName=dye.displayName;const QFe=YT("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"}}),zye=N.forwardRef(({className:t,variant:e,...r},n)=>s.jsx(hye,{ref:n,className:Xt(QFe({variant:e}),t),...r}));zye.displayName=hye.displayName;const JFe=N.forwardRef(({className:t,...e},r)=>s.jsx(pye,{ref:r,className:Xt("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}));JFe.displayName=pye.displayName;const Uye=N.forwardRef(({className:t,...e},r)=>s.jsx(gye,{ref:r,className:Xt("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...e,children:s.jsx(Ci,{className:"h-4 w-4"})}));Uye.displayName=gye.displayName;const Vye=N.forwardRef(({className:t,...e},r)=>s.jsx(fye,{ref:r,className:Xt("text-sm font-semibold",t),...e}));Vye.displayName=fye.displayName;const qye=N.forwardRef(({className:t,...e},r)=>s.jsx(mye,{ref:r,className:Xt("text-sm opacity-90",t),...e}));qye.displayName=mye.displayName;function e5e(){const{toasts:t}=qge();return s.jsxs(XFe,{children:[t.map(function({id:e,title:r,description:n,action:i,...o}){return s.jsxs(zye,{...o,children:[s.jsxs("div",{className:"grid gap-1",children:[r&&s.jsx(Vye,{children:r}),n&&s.jsx(qye,{children:n})]}),i,s.jsx(Uye,{})]},e)}),s.jsx($ye,{})]})}var vne=["light","dark"],t5e="(prefers-color-scheme: dark)",r5e=N.createContext(void 0),n5e={setTheme:t=>{},themes:[]},s5e=()=>{var t;return(t=N.useContext(r5e))!=null?t:n5e};N.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:c,attrs:a,nonce:f})=>{let m=o==="system",y=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${a.map(A=>`'${A}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,v=i?vne.includes(o)&&o?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${o}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",w=(A,C=!1,I=!0)=>{let M=c?c[A]:A,D=C?A+"|| ''":`'${M}'`,F="";return i&&I&&!C&&vne.includes(A)&&(F+=`d.style.colorScheme = '${A}';`),r==="class"?C||M?F+=`c.add(${D})`:F+="null":M&&(F+=`d[s](n,${D})`),F},j=t?`!function(){${y}${w(t)}}()`:n?`!function(){try{${y}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${m})){var t='${t5e}',m=window.matchMedia(t);if(m.media!==t||m.matches){${w("dark")}}else{${w("light")}}}else if(e){${c?`var x=${JSON.stringify(c)};`:""}${w(c?"x[e]":"e",!0)}}${m?"":"else{"+w(o,!1,!1)+"}"}${v}}catch(e){}}()`:`!function(){try{${y}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${w(c?"x[e]":"e",!0)}}else{${w(o,!1,!1)};}${v}}catch(t){}}();`;return N.createElement("script",{nonce:f,dangerouslySetInnerHTML:{__html:j}})});var i5e=t=>{switch(t){case"success":return l5e;case"info":return u5e;case"warning":return c5e;case"error":return d5e;default:return null}},a5e=Array(12).fill(0),o5e=({visible:t,className:e})=>Qe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Qe.createElement("div",{className:"sonner-spinner"},a5e.map((r,n)=>Qe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),l5e=Qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Qe.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"})),c5e=Qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Qe.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"})),u5e=Qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Qe.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"})),d5e=Qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Qe.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"})),h5e=Qe.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"},Qe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Qe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),f5e=()=>{let[t,e]=Qe.useState(document.hidden);return Qe.useEffect(()=>{let r=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t},B8=1,m5e=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:B8++,o=this.toasts.find(a=>a.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(a=>a.id===i?(this.publish({...a,...t,id:i,title:r}),{...a,...t,id:i,dismissible:c,title:r}):a):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],Qe.isValidElement(f))i=!1,this.create({id:r,type:"default",message:f});else if(g5e(f)&&!f.ok){i=!1;let m=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:m,description:y})}else if(e.success!==void 0){i=!1;let m=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:m,description:y})}}).catch(async f=>{if(o=["reject",f],e.error!==void 0){i=!1;let m=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:m,description:y})}}).finally(()=>{var f;i&&(this.dismiss(r),r=void 0),(f=e.finally)==null||f.call(e)}),a=()=>new Promise((f,m)=>c.then(()=>o[0]==="reject"?m(o[1]):f(o[1])).catch(m));return typeof r!="string"&&typeof r!="number"?{unwrap:a}:Object.assign(r,{unwrap:a})},this.custom=(t,e)=>{let r=(e==null?void 0:e.id)||B8++;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}},Hu=new m5e,p5e=(t,e)=>{let r=(e==null?void 0:e.id)||B8++;return Hu.addToast({title:t,...e,id:r}),r},g5e=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",y5e=p5e,x5e=()=>Hu.toasts,v5e=()=>Hu.getActiveToasts(),$t=Object.assign(y5e,{success:Hu.success,info:Hu.info,warning:Hu.warning,error:Hu.error,custom:Hu.custom,message:Hu.message,promise:Hu.promise,dismiss:Hu.dismiss,loading:Hu.loading},{getHistory:x5e,getToasts:v5e});function _5e(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))}_5e(`: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 uL(t){return t.label!==void 0}var b5e=3,w5e="32px",S5e="16px",_ne=4e3,T5e=356,j5e=14,E5e=20,k5e=200;function af(...t){return t.filter(Boolean).join(" ")}function A5e(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var N5e=t=>{var e,r,n,i,o,c,a,f,m,y,v;let{invert:w,toast:j,unstyled:A,interacting:C,setHeights:I,visibleToasts:M,heights:D,index:F,toasts:z,expanded:q,removeToast:H,defaultRichColors:K,closeButton:J,style:Q,cancelButtonStyle:ee,actionButtonStyle:oe,className:de="",descriptionClassName:ye="",duration:we,position:Le,gap:Se,loadingIcon:ve,expandByDefault:me,classNames:ke,icons:Pe,closeButtonAriaLabel:Ee="Close toast",pauseWhenPageIsHidden:xe}=t,[Ue,Ze]=Qe.useState(null),[lt,wt]=Qe.useState(null),[yt,gt]=Qe.useState(!1),[ft,kt]=Qe.useState(!1),[Vt,xt]=Qe.useState(!1),[or,Tr]=Qe.useState(!1),[rn,Lr]=Qe.useState(!1),[$r,qr]=Qe.useState(0),[Nn,tt]=Qe.useState(0),Tt=Qe.useRef(j.duration||we||_ne),Zt=Qe.useRef(null),ar=Qe.useRef(null),Wt=F===0,Kt=F+1<=M,At=j.type,pr=j.dismissible!==!1,yn=j.className||"",Gn=j.descriptionClassName||"",Bn=Qe.useMemo(()=>D.findIndex(nn=>nn.toastId===j.id)||0,[D,j.id]),Rs=Qe.useMemo(()=>{var nn;return(nn=j.closeButton)!=null?nn:J},[j.closeButton,J]),sa=Qe.useMemo(()=>j.duration||we||_ne,[j.duration,we]),gs=Qe.useRef(0),zi=Qe.useRef(0),Ir=Qe.useRef(0),$n=Qe.useRef(null),[Si,oi]=Le.split("-"),ia=Qe.useMemo(()=>D.reduce((nn,Ln,ri)=>ri>=Bn?nn:nn+Ln.height,0),[D,Bn]),Xr=f5e(),un=j.invert||w,xn=At==="loading";zi.current=Qe.useMemo(()=>Bn*Se+ia,[Bn,ia]),Qe.useEffect(()=>{Tt.current=sa},[sa]),Qe.useEffect(()=>{gt(!0)},[]),Qe.useEffect(()=>{let nn=ar.current;if(nn){let Ln=nn.getBoundingClientRect().height;return tt(Ln),I(ri=>[{toastId:j.id,height:Ln,position:j.position},...ri]),()=>I(ri=>ri.filter(Yo=>Yo.toastId!==j.id))}},[I,j.id]),Qe.useLayoutEffect(()=>{if(!yt)return;let nn=ar.current,Ln=nn.style.height;nn.style.height="auto";let ri=nn.getBoundingClientRect().height;nn.style.height=Ln,tt(ri),I(Yo=>Yo.find(Us=>Us.toastId===j.id)?Yo.map(Us=>Us.toastId===j.id?{...Us,height:ri}:Us):[{toastId:j.id,height:ri,position:j.position},...Yo])},[yt,j.title,j.description,I,j.id]);let Qr=Qe.useCallback(()=>{kt(!0),qr(zi.current),I(nn=>nn.filter(Ln=>Ln.toastId!==j.id)),setTimeout(()=>{H(j)},k5e)},[j,H,I,zi]);Qe.useEffect(()=>{if(j.promise&&At==="loading"||j.duration===1/0||j.type==="loading")return;let nn;return q||C||xe&&Xr?(()=>{if(Ir.current{var Ln;(Ln=j.onAutoClose)==null||Ln.call(j,j),Qr()},Tt.current)),()=>clearTimeout(nn)},[q,C,j,At,xe,Xr,Qr]),Qe.useEffect(()=>{j.delete&&Qr()},[Qr,j.delete]);function cs(){var nn,Ln,ri;return Pe!=null&&Pe.loading?Qe.createElement("div",{className:af(ke==null?void 0:ke.loader,(nn=j==null?void 0:j.classNames)==null?void 0:nn.loader,"sonner-loader"),"data-visible":At==="loading"},Pe.loading):ve?Qe.createElement("div",{className:af(ke==null?void 0:ke.loader,(Ln=j==null?void 0:j.classNames)==null?void 0:Ln.loader,"sonner-loader"),"data-visible":At==="loading"},ve):Qe.createElement(o5e,{className:af(ke==null?void 0:ke.loader,(ri=j==null?void 0:j.classNames)==null?void 0:ri.loader),visible:At==="loading"})}return Qe.createElement("li",{tabIndex:0,ref:ar,className:af(de,yn,ke==null?void 0:ke.toast,(e=j==null?void 0:j.classNames)==null?void 0:e.toast,ke==null?void 0:ke.default,ke==null?void 0:ke[At],(r=j==null?void 0:j.classNames)==null?void 0:r[At]),"data-sonner-toast":"","data-rich-colors":(n=j.richColors)!=null?n:K,"data-styled":!(j.jsx||j.unstyled||A),"data-mounted":yt,"data-promise":!!j.promise,"data-swiped":rn,"data-removed":ft,"data-visible":Kt,"data-y-position":Si,"data-x-position":oi,"data-index":F,"data-front":Wt,"data-swiping":Vt,"data-dismissible":pr,"data-type":At,"data-invert":un,"data-swipe-out":or,"data-swipe-direction":lt,"data-expanded":!!(q||me&&yt),style:{"--index":F,"--toasts-before":F,"--z-index":z.length-F,"--offset":`${ft?$r:zi.current}px`,"--initial-height":me?"auto":`${Nn}px`,...Q,...j.style},onDragEnd:()=>{xt(!1),Ze(null),$n.current=null},onPointerDown:nn=>{xn||!pr||(Zt.current=new Date,qr(zi.current),nn.target.setPointerCapture(nn.pointerId),nn.target.tagName!=="BUTTON"&&(xt(!0),$n.current={x:nn.clientX,y:nn.clientY}))},onPointerUp:()=>{var nn,Ln,ri,Yo;if(or||!pr)return;$n.current=null;let Us=Number(((nn=ar.current)==null?void 0:nn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ft=Number(((Ln=ar.current)==null?void 0:Ln.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),jo=new Date().getTime()-((ri=Zt.current)==null?void 0:ri.getTime()),ws=Ue==="x"?Us:Ft,yi=Math.abs(ws)/jo;if(Math.abs(ws)>=E5e||yi>.11){qr(zi.current),(Yo=j.onDismiss)==null||Yo.call(j,j),wt(Ue==="x"?Us>0?"right":"left":Ft>0?"down":"up"),Qr(),Tr(!0),Lr(!1);return}xt(!1),Ze(null)},onPointerMove:nn=>{var Ln,ri,Yo,Us;if(!$n.current||!pr||((Ln=window.getSelection())==null?void 0:Ln.toString().length)>0)return;let Ft=nn.clientY-$n.current.y,jo=nn.clientX-$n.current.x,ws=(ri=t.swipeDirections)!=null?ri:A5e(Le);!Ue&&(Math.abs(jo)>1||Math.abs(Ft)>1)&&Ze(Math.abs(jo)>Math.abs(Ft)?"x":"y");let yi={x:0,y:0};Ue==="y"?(ws.includes("top")||ws.includes("bottom"))&&(ws.includes("top")&&Ft<0||ws.includes("bottom")&&Ft>0)&&(yi.y=Ft):Ue==="x"&&(ws.includes("left")||ws.includes("right"))&&(ws.includes("left")&&jo<0||ws.includes("right")&&jo>0)&&(yi.x=jo),(Math.abs(yi.x)>0||Math.abs(yi.y)>0)&&Lr(!0),(Yo=ar.current)==null||Yo.style.setProperty("--swipe-amount-x",`${yi.x}px`),(Us=ar.current)==null||Us.style.setProperty("--swipe-amount-y",`${yi.y}px`)}},Rs&&!j.jsx?Qe.createElement("button",{"aria-label":Ee,"data-disabled":xn,"data-close-button":!0,onClick:xn||!pr?()=>{}:()=>{var nn;Qr(),(nn=j.onDismiss)==null||nn.call(j,j)},className:af(ke==null?void 0:ke.closeButton,(i=j==null?void 0:j.classNames)==null?void 0:i.closeButton)},(o=Pe==null?void 0:Pe.close)!=null?o:h5e):null,j.jsx||N.isValidElement(j.title)?j.jsx?j.jsx:typeof j.title=="function"?j.title():j.title:Qe.createElement(Qe.Fragment,null,At||j.icon||j.promise?Qe.createElement("div",{"data-icon":"",className:af(ke==null?void 0:ke.icon,(c=j==null?void 0:j.classNames)==null?void 0:c.icon)},j.promise||j.type==="loading"&&!j.icon?j.icon||cs():null,j.type!=="loading"?j.icon||(Pe==null?void 0:Pe[At])||i5e(At):null):null,Qe.createElement("div",{"data-content":"",className:af(ke==null?void 0:ke.content,(a=j==null?void 0:j.classNames)==null?void 0:a.content)},Qe.createElement("div",{"data-title":"",className:af(ke==null?void 0:ke.title,(f=j==null?void 0:j.classNames)==null?void 0:f.title)},typeof j.title=="function"?j.title():j.title),j.description?Qe.createElement("div",{"data-description":"",className:af(ye,Gn,ke==null?void 0:ke.description,(m=j==null?void 0:j.classNames)==null?void 0:m.description)},typeof j.description=="function"?j.description():j.description):null),N.isValidElement(j.cancel)?j.cancel:j.cancel&&uL(j.cancel)?Qe.createElement("button",{"data-button":!0,"data-cancel":!0,style:j.cancelButtonStyle||ee,onClick:nn=>{var Ln,ri;uL(j.cancel)&&pr&&((ri=(Ln=j.cancel).onClick)==null||ri.call(Ln,nn),Qr())},className:af(ke==null?void 0:ke.cancelButton,(y=j==null?void 0:j.classNames)==null?void 0:y.cancelButton)},j.cancel.label):null,N.isValidElement(j.action)?j.action:j.action&&uL(j.action)?Qe.createElement("button",{"data-button":!0,"data-action":!0,style:j.actionButtonStyle||oe,onClick:nn=>{var Ln,ri;uL(j.action)&&((ri=(Ln=j.action).onClick)==null||ri.call(Ln,nn),!nn.defaultPrevented&&Qr())},className:af(ke==null?void 0:ke.actionButton,(v=j==null?void 0:j.classNames)==null?void 0:v.actionButton)},j.action.label):null))};function bne(){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 C5e(t,e){let r={};return[t,e].forEach((n,i)=>{let o=i===1,c=o?"--mobile-offset":"--offset",a=o?S5e:w5e;function f(m){["top","right","bottom","left"].forEach(y=>{r[`${c}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof n=="number"||typeof n=="string"?f(n):typeof n=="object"?["top","right","bottom","left"].forEach(m=>{n[m]===void 0?r[`${c}-${m}`]=a:r[`${c}-${m}`]=typeof n[m]=="number"?`${n[m]}px`:n[m]}):f(a)}),r}var I5e=N.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:o,closeButton:c,className:a,offset:f,mobileOffset:m,theme:y="light",richColors:v,duration:w,style:j,visibleToasts:A=b5e,toastOptions:C,dir:I=bne(),gap:M=j5e,loadingIcon:D,icons:F,containerAriaLabel:z="Notifications",pauseWhenPageIsHidden:q}=t,[H,K]=Qe.useState([]),J=Qe.useMemo(()=>Array.from(new Set([n].concat(H.filter(xe=>xe.position).map(xe=>xe.position)))),[H,n]),[Q,ee]=Qe.useState([]),[oe,de]=Qe.useState(!1),[ye,we]=Qe.useState(!1),[Le,Se]=Qe.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ve=Qe.useRef(null),me=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),ke=Qe.useRef(null),Pe=Qe.useRef(!1),Ee=Qe.useCallback(xe=>{K(Ue=>{var Ze;return(Ze=Ue.find(lt=>lt.id===xe.id))!=null&&Ze.delete||Hu.dismiss(xe.id),Ue.filter(({id:lt})=>lt!==xe.id)})},[]);return Qe.useEffect(()=>Hu.subscribe(xe=>{if(xe.dismiss){K(Ue=>Ue.map(Ze=>Ze.id===xe.id?{...Ze,delete:!0}:Ze));return}setTimeout(()=>{$ge.flushSync(()=>{K(Ue=>{let Ze=Ue.findIndex(lt=>lt.id===xe.id);return Ze!==-1?[...Ue.slice(0,Ze),{...Ue[Ze],...xe},...Ue.slice(Ze+1)]:[xe,...Ue]})})})}),[]),Qe.useEffect(()=>{if(y!=="system"){Se(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Se("dark"):Se("light")),typeof window>"u")return;let xe=window.matchMedia("(prefers-color-scheme: dark)");try{xe.addEventListener("change",({matches:Ue})=>{Se(Ue?"dark":"light")})}catch{xe.addListener(({matches:Ze})=>{try{Se(Ze?"dark":"light")}catch(lt){console.error(lt)}})}},[y]),Qe.useEffect(()=>{H.length<=1&&de(!1)},[H]),Qe.useEffect(()=>{let xe=Ue=>{var Ze,lt;i.every(wt=>Ue[wt]||Ue.code===wt)&&(de(!0),(Ze=ve.current)==null||Ze.focus()),Ue.code==="Escape"&&(document.activeElement===ve.current||(lt=ve.current)!=null&<.contains(document.activeElement))&&de(!1)};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[i]),Qe.useEffect(()=>{if(ve.current)return()=>{ke.current&&(ke.current.focus({preventScroll:!0}),ke.current=null,Pe.current=!1)}},[ve.current]),Qe.createElement("section",{ref:e,"aria-label":`${z} ${me}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},J.map((xe,Ue)=>{var Ze;let[lt,wt]=xe.split("-");return H.length?Qe.createElement("ol",{key:xe,dir:I==="auto"?bne():I,tabIndex:-1,ref:ve,className:a,"data-sonner-toaster":!0,"data-theme":Le,"data-y-position":lt,"data-lifted":oe&&H.length>1&&!o,"data-x-position":wt,style:{"--front-toast-height":`${((Ze=Q[0])==null?void 0:Ze.height)||0}px`,"--width":`${T5e}px`,"--gap":`${M}px`,...j,...C5e(f,m)},onBlur:yt=>{Pe.current&&!yt.currentTarget.contains(yt.relatedTarget)&&(Pe.current=!1,ke.current&&(ke.current.focus({preventScroll:!0}),ke.current=null))},onFocus:yt=>{yt.target instanceof HTMLElement&&yt.target.dataset.dismissible==="false"||Pe.current||(Pe.current=!0,ke.current=yt.relatedTarget)},onMouseEnter:()=>de(!0),onMouseMove:()=>de(!0),onMouseLeave:()=>{ye||de(!1)},onDragEnd:()=>de(!1),onPointerDown:yt=>{yt.target instanceof HTMLElement&&yt.target.dataset.dismissible==="false"||we(!0)},onPointerUp:()=>we(!1)},H.filter(yt=>!yt.position&&Ue===0||yt.position===xe).map((yt,gt)=>{var ft,kt;return Qe.createElement(N5e,{key:yt.id,icons:F,index:gt,toast:yt,defaultRichColors:v,duration:(ft=C==null?void 0:C.duration)!=null?ft:w,className:C==null?void 0:C.className,descriptionClassName:C==null?void 0:C.descriptionClassName,invert:r,visibleToasts:A,closeButton:(kt=C==null?void 0:C.closeButton)!=null?kt:c,interacting:ye,position:xe,style:C==null?void 0:C.style,unstyled:C==null?void 0:C.unstyled,classNames:C==null?void 0:C.classNames,cancelButtonStyle:C==null?void 0:C.cancelButtonStyle,actionButtonStyle:C==null?void 0:C.actionButtonStyle,removeToast:Ee,toasts:H.filter(Vt=>Vt.position==yt.position),heights:Q.filter(Vt=>Vt.position==yt.position),setHeights:ee,expandByDefault:o,gap:M,loadingIcon:D,expanded:oe,pauseWhenPageIsHidden:q,swipeDirections:t.swipeDirections})})):null}))});const P5e=({...t})=>{const{theme:e="system"}=s5e();return s.jsx(I5e,{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 R5e=R7[" useId ".trim().toString()]||(()=>{}),L5e=0;function ol(t){const[e,r]=N.useState(R5e());return Ho(()=>{r(n=>n??String(L5e++))},[t]),e?`radix-${e}`:""}var Xz="focusScope.autoFocusOnMount",Qz="focusScope.autoFocusOnUnmount",wne={bubbles:!1,cancelable:!0},M5e="FocusScope",IC=N.forwardRef((t,e)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...c}=t,[a,f]=N.useState(null),m=go(i),y=go(o),v=N.useRef(null),w=is(e,C=>f(C)),j=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(n){let C=function(F){if(j.paused||!a)return;const z=F.target;a.contains(z)?v.current=z:Wy(v.current,{select:!0})},I=function(F){if(j.paused||!a)return;const z=F.relatedTarget;z!==null&&(a.contains(z)||Wy(v.current,{select:!0}))},M=function(F){if(document.activeElement===document.body)for(const q of F)q.removedNodes.length>0&&Wy(a)};document.addEventListener("focusin",C),document.addEventListener("focusout",I);const D=new MutationObserver(M);return a&&D.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",C),document.removeEventListener("focusout",I),D.disconnect()}}},[n,a,j.paused]),N.useEffect(()=>{if(a){Tne.add(j);const C=document.activeElement;if(!a.contains(C)){const M=new CustomEvent(Xz,wne);a.addEventListener(Xz,m),a.dispatchEvent(M),M.defaultPrevented||(D5e(z5e(Gye(a)),{select:!0}),document.activeElement===C&&Wy(a))}return()=>{a.removeEventListener(Xz,m),setTimeout(()=>{const M=new CustomEvent(Qz,wne);a.addEventListener(Qz,y),a.dispatchEvent(M),M.defaultPrevented||Wy(C??document.body,{select:!0}),a.removeEventListener(Qz,y),Tne.remove(j)},0)}}},[a,m,y,j]);const A=N.useCallback(C=>{if(!r&&!n||j.paused)return;const I=C.key==="Tab"&&!C.altKey&&!C.ctrlKey&&!C.metaKey,M=document.activeElement;if(I&&M){const D=C.currentTarget,[F,z]=O5e(D);F&&z?!C.shiftKey&&M===z?(C.preventDefault(),r&&Wy(F,{select:!0})):C.shiftKey&&M===F&&(C.preventDefault(),r&&Wy(z,{select:!0})):M===D&&C.preventDefault()}},[r,n,j.paused]);return s.jsx(cn.div,{tabIndex:-1,...c,ref:w,onKeyDown:A})});IC.displayName=M5e;function D5e(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(Wy(n,{select:e}),document.activeElement!==r)return}function O5e(t){const e=Gye(t),r=Sne(e,t),n=Sne(e.reverse(),t);return[r,n]}function Gye(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 Sne(t,e){for(const r of t)if(!F5e(r,{upTo:e}))return r}function F5e(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 B5e(t){return t instanceof HTMLInputElement&&"select"in t}function Wy(t,{select:e=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&B5e(t)&&e&&t.select()}}var Tne=$5e();function $5e(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=jne(t,e),t.unshift(e)},remove(e){var r;t=jne(t,e),(r=t[0])==null||r.resume()}}}function jne(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}function z5e(t){return t.filter(e=>e.tagName!=="A")}var Jz=0;function E3(){N.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??Ene()),document.body.insertAdjacentElement("beforeend",t[1]??Ene()),Jz++,()=>{Jz===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Jz--}},[])}function Ene(){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 Dm=function(){return Dm=Object.assign||function(e){for(var r,n=1,i=arguments.length;n"u")return sBe;var e=iBe(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])}},oBe=Yye(),gS="data-scroll-locked",lBe=function(t,e,r,n){var i=t.left,o=t.top,c=t.right,a=t.gap;return r===void 0&&(r="margin"),` .`.concat(V5e,` { overflow: hidden `).concat(n,`; padding-right: `).concat(a,"px ").concat(n,`; } body[`).concat(gS,`] { 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(a,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(BM,` { right: `).concat(a,"px ").concat(n,`; } .`).concat($M,` { margin-right: `).concat(a,"px ").concat(n,`; } .`).concat(BM," .").concat(BM,` { right: 0 `).concat(n,`; } .`).concat($M," .").concat($M,` { margin-right: 0 `).concat(n,`; } body[`).concat(gS,`] { `).concat(q5e,": ").concat(a,`px; } `)},Ane=function(){var t=parseInt(document.body.getAttribute(gS)||"0",10);return isFinite(t)?t:0},cBe=function(){N.useEffect(function(){return document.body.setAttribute(gS,(Ane()+1).toString()),function(){var t=Ane()-1;t<=0?document.body.removeAttribute(gS):document.body.setAttribute(gS,t.toString())}},[])},uBe=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;cBe();var o=N.useMemo(function(){return aBe(i)},[i]);return N.createElement(oBe,{styles:lBe(o,!e,i,r?"":"!important")})},$8=!1;if(typeof window<"u")try{var dL=Object.defineProperty({},"passive",{get:function(){return $8=!0,!0}});window.addEventListener("test",dL,dL),window.removeEventListener("test",dL,dL)}catch{$8=!1}var r1=$8?{passive:!1}:!1,dBe=function(t){return t.tagName==="TEXTAREA"},Zye=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!dBe(t)&&r[e]==="visible")},hBe=function(t){return Zye(t,"overflowY")},fBe=function(t){return Zye(t,"overflowX")},Nne=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=Xye(t,n);if(i){var o=Qye(t,n),c=o[1],a=o[2];if(c>a)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},mBe=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},pBe=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},Xye=function(t,e){return t==="v"?hBe(e):fBe(e)},Qye=function(t,e){return t==="v"?mBe(e):pBe(e)},gBe=function(t,e){return t==="h"&&e==="rtl"?-1:1},yBe=function(t,e,r,n,i){var o=gBe(t,window.getComputedStyle(e).direction),c=o*n,a=r.target,f=e.contains(a),m=!1,y=c>0,v=0,w=0;do{if(!a)break;var j=Qye(t,a),A=j[0],C=j[1],I=j[2],M=C-I-o*A;(A||M)&&Xye(t,a)&&(v+=M,w+=A);var D=a.parentNode;a=D&&D.nodeType===Node.DOCUMENT_FRAGMENT_NODE?D.host:D}while(!f&&a!==document.body||f&&(e.contains(a)||e===a));return(y&&(Math.abs(v)<1||!i)||!y&&(Math.abs(w)<1||!i))&&(m=!0),m},hL=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Cne=function(t){return[t.deltaX,t.deltaY]},Ine=function(t){return t&&"current"in t?t.current:t},xBe=function(t,e){return t[0]===e[0]&&t[1]===e[1]},vBe=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},_Be=0,n1=[];function bBe(t){var e=N.useRef([]),r=N.useRef([0,0]),n=N.useRef(),i=N.useState(_Be++)[0],o=N.useState(Yye)[0],c=N.useRef(t);N.useEffect(function(){c.current=t},[t]),N.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var C=U5e([t.lockRef.current],(t.shards||[]).map(Ine),!0).filter(Boolean);return C.forEach(function(I){return I.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),C.forEach(function(I){return I.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var a=N.useCallback(function(C,I){if("touches"in C&&C.touches.length===2||C.type==="wheel"&&C.ctrlKey)return!c.current.allowPinchZoom;var M=hL(C),D=r.current,F="deltaX"in C?C.deltaX:D[0]-M[0],z="deltaY"in C?C.deltaY:D[1]-M[1],q,H=C.target,K=Math.abs(F)>Math.abs(z)?"h":"v";if("touches"in C&&K==="h"&&H.type==="range")return!1;var J=Nne(K,H);if(!J)return!0;if(J?q=K:(q=K==="v"?"h":"v",J=Nne(K,H)),!J)return!1;if(!n.current&&"changedTouches"in C&&(F||z)&&(n.current=q),!q)return!0;var Q=n.current||q;return yBe(Q,I,C,Q==="h"?F:z,!0)},[]),f=N.useCallback(function(C){var I=C;if(!(!n1.length||n1[n1.length-1]!==o)){var M="deltaY"in I?Cne(I):hL(I),D=e.current.filter(function(q){return q.name===I.type&&(q.target===I.target||I.target===q.shadowParent)&&xBe(q.delta,M)})[0];if(D&&D.should){I.cancelable&&I.preventDefault();return}if(!D){var F=(c.current.shards||[]).map(Ine).filter(Boolean).filter(function(q){return q.contains(I.target)}),z=F.length>0?a(I,F[0]):!c.current.noIsolation;z&&I.cancelable&&I.preventDefault()}}},[]),m=N.useCallback(function(C,I,M,D){var F={name:C,delta:I,target:M,should:D,shadowParent:wBe(M)};e.current.push(F),setTimeout(function(){e.current=e.current.filter(function(z){return z!==F})},1)},[]),y=N.useCallback(function(C){r.current=hL(C),n.current=void 0},[]),v=N.useCallback(function(C){m(C.type,Cne(C),C.target,a(C,t.lockRef.current))},[]),w=N.useCallback(function(C){m(C.type,hL(C),C.target,a(C,t.lockRef.current))},[]);N.useEffect(function(){return n1.push(o),t.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:w}),document.addEventListener("wheel",f,r1),document.addEventListener("touchmove",f,r1),document.addEventListener("touchstart",y,r1),function(){n1=n1.filter(function(C){return C!==o}),document.removeEventListener("wheel",f,r1),document.removeEventListener("touchmove",f,r1),document.removeEventListener("touchstart",y,r1)}},[]);var j=t.removeScrollBar,A=t.inert;return N.createElement(N.Fragment,null,A?N.createElement(o,{styles:vBe(i)}):null,j?N.createElement(uBe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function wBe(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const SBe=X5e(Kye,bBe);var PC=N.forwardRef(function(t,e){return N.createElement(k3,Dm({},t,{ref:e,sideCar:SBe}))});PC.classNames=k3.classNames;var TBe=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},s1=new WeakMap,fL=new WeakMap,mL={},n6=0,Jye=function(t){return t&&(t.host||Jye(t.parentNode))},jBe=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=Jye(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})},EBe=function(t,e,r,n){var i=jBe(e,Array.isArray(t)?t:[t]);mL[r]||(mL[r]=new WeakMap);var o=mL[r],c=[],a=new Set,f=new Set(i),m=function(v){!v||a.has(v)||(a.add(v),m(v.parentNode))};i.forEach(m);var y=function(v){!v||f.has(v)||Array.prototype.forEach.call(v.children,function(w){if(a.has(w))y(w);else try{var j=w.getAttribute(n),A=j!==null&&j!=="false",C=(s1.get(w)||0)+1,I=(o.get(w)||0)+1;s1.set(w,C),o.set(w,I),c.push(w),C===1&&A&&fL.set(w,!0),I===1&&w.setAttribute(r,"true"),A||w.setAttribute(n,"true")}catch(M){console.error("aria-hidden: cannot operate on ",w,M)}})};return y(e),a.clear(),n6++,function(){c.forEach(function(v){var w=s1.get(v)-1,j=o.get(v)-1;s1.set(v,w),o.set(v,j),w||(fL.has(v)||v.removeAttribute(n),fL.delete(v)),j||v.removeAttribute(r)}),n6--,n6||(s1=new WeakMap,s1=new WeakMap,fL=new WeakMap,mL={})}},A3=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=TBe(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),EBe(n,i,r,"aria-hidden")):function(){return null}},N3="Dialog",[exe,txe]=dl(N3),[kBe,qf]=exe(N3),rxe=t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!0}=t,a=N.useRef(null),f=N.useRef(null),[m,y]=rd({prop:n,defaultProp:i??!1,onChange:o,caller:N3});return s.jsx(kBe,{scope:e,triggerRef:a,contentRef:f,contentId:ol(),titleId:ol(),descriptionId:ol(),open:m,onOpenChange:y,onOpenToggle:N.useCallback(()=>y(v=>!v),[y]),modal:c,children:r})};rxe.displayName=N3;var nxe="DialogTrigger",sxe=N.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=qf(nxe,r),o=is(e,i.triggerRef);return s.jsx(cn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":VH(i.open),...n,ref:o,onClick:Gr(t.onClick,i.onOpenToggle)})});sxe.displayName=nxe;var zH="DialogPortal",[ABe,ixe]=exe(zH,{forceMount:void 0}),axe=t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,o=qf(zH,e);return s.jsx(ABe,{scope:e,forceMount:r,children:N.Children.map(n,c=>s.jsx(Pl,{present:r||o.open,children:s.jsx(KT,{asChild:!0,container:i,children:c})}))})};axe.displayName=zH;var ZD="DialogOverlay",oxe=N.forwardRef((t,e)=>{const r=ixe(ZD,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=qf(ZD,t.__scopeDialog);return o.modal?s.jsx(Pl,{present:n||o.open,children:s.jsx(CBe,{...i,ref:e})}):null});oxe.displayName=ZD;var NBe=Gx("DialogOverlay.RemoveScroll"),CBe=N.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=qf(ZD,r);return s.jsx(PC,{as:NBe,allowPinchZoom:!0,shards:[i.contentRef],children:s.jsx(cn.div,{"data-state":VH(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),Y_="DialogContent",lxe=N.forwardRef((t,e)=>{const r=ixe(Y_,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=qf(Y_,t.__scopeDialog);return s.jsx(Pl,{present:n||o.open,children:o.modal?s.jsx(IBe,{...i,ref:e}):s.jsx(PBe,{...i,ref:e})})});lxe.displayName=Y_;var IBe=N.forwardRef((t,e)=>{const r=qf(Y_,t.__scopeDialog),n=N.useRef(null),i=is(e,r.contentRef,n);return N.useEffect(()=>{const o=n.current;if(o)return A3(o)},[]),s.jsx(cxe,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Gr(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Gr(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,a=c.button===0&&c.ctrlKey===!0;(c.button===2||a)&&o.preventDefault()}),onFocusOutside:Gr(t.onFocusOutside,o=>o.preventDefault())})}),PBe=N.forwardRef((t,e)=>{const r=qf(Y_,t.__scopeDialog),n=N.useRef(!1),i=N.useRef(!1);return s.jsx(cxe,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var c,a;(c=t.onCloseAutoFocus)==null||c.call(t,o),o.defaultPrevented||(n.current||(a=r.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var f,m;(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;((m=r.triggerRef.current)==null?void 0:m.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),cxe=N.forwardRef((t,e)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...c}=t,a=qf(Y_,r),f=N.useRef(null),m=is(e,f);return E3(),s.jsxs(s.Fragment,{children:[s.jsx(IC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(fb,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":VH(a.open),...c,ref:m,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(LBe,{titleId:a.titleId}),s.jsx(DBe,{contentRef:f,descriptionId:a.descriptionId})]})]})}),UH="DialogTitle",uxe=N.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=qf(UH,r);return s.jsx(cn.h2,{id:i.titleId,...n,ref:e})});uxe.displayName=UH;var dxe="DialogDescription",hxe=N.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=qf(dxe,r);return s.jsx(cn.p,{id:i.descriptionId,...n,ref:e})});hxe.displayName=dxe;var fxe="DialogClose",mxe=N.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=qf(fxe,r);return s.jsx(cn.button,{type:"button",...n,ref:e,onClick:Gr(t.onClick,()=>i.onOpenChange(!1))})});mxe.displayName=fxe;function VH(t){return t?"open":"closed"}var pxe="DialogTitleWarning",[RBe,gxe]=B4e(pxe,{contentName:Y_,titleName:UH,docsSlug:"dialog"}),LBe=({titleId:t})=>{const e=gxe(pxe),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 N.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},MBe="DialogDescriptionWarning",DBe=({contentRef:t,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${gxe(MBe).contentName}}.`;return N.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},C3=rxe,qH=sxe,I3=axe,JT=oxe,ej=lxe,RC=uxe,LC=hxe,MC=mxe,yxe="AlertDialog",[OBe,kJt]=dl(yxe,[txe]),Ug=txe(),xxe=t=>{const{__scopeAlertDialog:e,...r}=t,n=Ug(e);return s.jsx(C3,{...n,...r,modal:!0})};xxe.displayName=yxe;var FBe="AlertDialogTrigger",vxe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Ug(r);return s.jsx(qH,{...i,...n,ref:e})});vxe.displayName=FBe;var BBe="AlertDialogPortal",_xe=t=>{const{__scopeAlertDialog:e,...r}=t,n=Ug(e);return s.jsx(I3,{...n,...r})};_xe.displayName=BBe;var $Be="AlertDialogOverlay",bxe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Ug(r);return s.jsx(JT,{...i,...n,ref:e})});bxe.displayName=$Be;var yS="AlertDialogContent",[zBe,UBe]=OBe(yS),VBe=Wge("AlertDialogContent"),wxe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,children:n,...i}=t,o=Ug(r),c=N.useRef(null),a=is(e,c),f=N.useRef(null);return s.jsx(RBe,{contentName:yS,titleName:Sxe,docsSlug:"alert-dialog",children:s.jsx(zBe,{scope:r,cancelRef:f,children:s.jsxs(ej,{role:"alertdialog",...o,...i,ref:a,onOpenAutoFocus:Gr(i.onOpenAutoFocus,m=>{var y;m.preventDefault(),(y=f.current)==null||y.focus({preventScroll:!0})}),onPointerDownOutside:m=>m.preventDefault(),onInteractOutside:m=>m.preventDefault(),children:[s.jsx(VBe,{children:n}),s.jsx(GBe,{contentRef:c})]})})})});wxe.displayName=yS;var Sxe="AlertDialogTitle",Txe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Ug(r);return s.jsx(RC,{...i,...n,ref:e})});Txe.displayName=Sxe;var jxe="AlertDialogDescription",Exe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Ug(r);return s.jsx(LC,{...i,...n,ref:e})});Exe.displayName=jxe;var qBe="AlertDialogAction",kxe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Ug(r);return s.jsx(MC,{...i,...n,ref:e})});kxe.displayName=qBe;var Axe="AlertDialogCancel",Nxe=N.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,{cancelRef:i}=UBe(Axe,r),o=Ug(r),c=is(e,i);return s.jsx(MC,{...o,...n,ref:c})});Nxe.displayName=Axe;var GBe=({contentRef:t})=>{const e=`\`${yS}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${yS}\` by passing a \`${jxe}\` 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 \`${yS}\`. 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 N.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},HBe=xxe,WBe=vxe,KBe=_xe,Cxe=bxe,Ixe=wxe,Pxe=kxe,Rxe=Nxe,Lxe=Txe,Mxe=Exe;const tN=YT("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"}}),Lt=N.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},o)=>{const c=n?Gge:"button";return s.jsx(c,{className:Xt(tN({variant:e,size:r,className:t})),ref:o,...i})});Lt.displayName="Button";const Dxe=HBe,AJt=WBe,YBe=KBe,Oxe=N.forwardRef(({className:t,...e},r)=>s.jsx(Cxe,{className:Xt("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}));Oxe.displayName=Cxe.displayName;const GH=N.forwardRef(({className:t,...e},r)=>s.jsxs(YBe,{children:[s.jsx(Oxe,{}),s.jsx(Ixe,{ref:r,className:Xt("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})]}));GH.displayName=Ixe.displayName;const HH=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col space-y-2 text-center sm:text-left",t),...e});HH.displayName="AlertDialogHeader";const WH=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});WH.displayName="AlertDialogFooter";const KH=N.forwardRef(({className:t,...e},r)=>s.jsx(Lxe,{ref:r,className:Xt("text-lg font-semibold",t),...e}));KH.displayName=Lxe.displayName;const YH=N.forwardRef(({className:t,...e},r)=>s.jsx(Mxe,{ref:r,className:Xt("text-sm text-muted-foreground",t),...e}));YH.displayName=Mxe.displayName;const ZH=N.forwardRef(({className:t,...e},r)=>s.jsx(Pxe,{ref:r,className:Xt(tN(),t),...e}));ZH.displayName=Pxe.displayName;const XH=N.forwardRef(({className:t,...e},r)=>s.jsx(Rxe,{ref:r,className:Xt(tN({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));XH.displayName=Rxe.displayName;let XD=null;const ZBe=["delete","remove","revoke","cannot be undone","permanently"];function NJt(t,e={}){const r=typeof t=="string"?{description:t,...e}:t,n=`${r.title??""} ${r.description??""}`.toLowerCase(),i=r.destructive??ZBe.some(o=>n.includes(o));return new Promise(o=>{if(!XD){o(window.confirm(r.description??r.title??"Are you sure?"));return}XD({...r,destructive:i,resolve:o})})}function XBe(){const[t,e]=N.useState(null);N.useEffect(()=>(XD=i=>e(i),()=>{XD=null}),[]);const r=i=>{t==null||t.resolve(i),e(null)},n=!!(t!=null&&t.destructive);return s.jsx(Dxe,{open:!!t,onOpenChange:i=>!i&&r(!1),children:s.jsxs(GH,{className:"sm:max-w-md",children:[s.jsx(HH,{children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:Xt("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",n?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:s.jsx(XT,{className:"h-5 w-5"})}),s.jsxs("div",{className:"space-y-1.5 text-left",children:[s.jsx(KH,{children:(t==null?void 0:t.title)??(n?"Are you sure?":"Please confirm")}),(t==null?void 0:t.description)&&s.jsx(YH,{className:"leading-relaxed",children:t.description})]})]})}),s.jsxs(WH,{className:"gap-2 sm:gap-2",children:[s.jsx(XH,{onClick:()=>r(!1),children:(t==null?void 0:t.cancelText)??"Cancel"}),s.jsx(ZH,{onClick:()=>r(!0),className:Xt(n&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(t==null?void 0:t.confirmText)??(n?"Delete":"Continue")})]})]})})}const QBe=["top","right","bottom","left"],Kx=Math.min,Nd=Math.max,QD=Math.round,pL=Math.floor,Yx=t=>({x:t,y:t}),JBe={left:"right",right:"left",bottom:"top",top:"bottom"},e$e={start:"end",end:"start"};function z8(t,e,r){return Nd(t,Kx(e,r))}function Ig(t,e){return typeof t=="function"?t(e):t}function Pg(t){return t.split("-")[0]}function tj(t){return t.split("-")[1]}function QH(t){return t==="x"?"y":"x"}function JH(t){return t==="y"?"height":"width"}function Zx(t){return["top","bottom"].includes(Pg(t))?"y":"x"}function eW(t){return QH(Zx(t))}function t$e(t,e,r){r===void 0&&(r=!1);const n=tj(t),i=eW(t),o=JH(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(c=JD(c)),[c,JD(c)]}function r$e(t){const e=JD(t);return[U8(t),e,U8(e)]}function U8(t){return t.replace(/start|end/g,e=>e$e[e])}function n$e(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 s$e(t,e,r,n){const i=tj(t);let o=n$e(Pg(t),r==="start",n);return i&&(o=o.map(c=>c+"-"+i),e&&(o=o.concat(o.map(U8)))),o}function JD(t){return t.replace(/left|right|bottom|top/g,e=>JBe[e])}function i$e(t){return{top:0,right:0,bottom:0,left:0,...t}}function Fxe(t){return typeof t!="number"?i$e(t):{top:t,right:t,bottom:t,left:t}}function eO(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 Pne(t,e,r){let{reference:n,floating:i}=t;const o=Zx(e),c=eW(e),a=JH(c),f=Pg(e),m=o==="y",y=n.x+n.width/2-i.width/2,v=n.y+n.height/2-i.height/2,w=n[a]/2-i[a]/2;let j;switch(f){case"top":j={x:y,y:n.y-i.height};break;case"bottom":j={x:y,y:n.y+n.height};break;case"right":j={x:n.x+n.width,y:v};break;case"left":j={x:n.x-i.width,y:v};break;default:j={x:n.x,y:n.y}}switch(tj(e)){case"start":j[c]-=w*(r&&m?-1:1);break;case"end":j[c]+=w*(r&&m?-1:1);break}return j}const a$e=async(t,e,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:c}=r,a=o.filter(Boolean),f=await(c.isRTL==null?void 0:c.isRTL(e));let m=await c.getElementRects({reference:t,floating:e,strategy:i}),{x:y,y:v}=Pne(m,n,f),w=n,j={},A=0;for(let C=0;C({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:o,platform:c,elements:a,middlewareData:f}=e,{element:m,padding:y=0}=Ig(t,e)||{};if(m==null)return{};const v=Fxe(y),w={x:r,y:n},j=eW(i),A=JH(j),C=await c.getDimensions(m),I=j==="y",M=I?"top":"left",D=I?"bottom":"right",F=I?"clientHeight":"clientWidth",z=o.reference[A]+o.reference[j]-w[j]-o.floating[A],q=w[j]-o.reference[j],H=await(c.getOffsetParent==null?void 0:c.getOffsetParent(m));let K=H?H[F]:0;(!K||!await(c.isElement==null?void 0:c.isElement(H)))&&(K=a.floating[F]||o.floating[A]);const J=z/2-q/2,Q=K/2-C[A]/2-1,ee=Kx(v[M],Q),oe=Kx(v[D],Q),de=ee,ye=K-C[A]-oe,we=K/2-C[A]/2+J,Le=z8(de,we,ye),Se=!f.arrow&&tj(i)!=null&&we!==Le&&o.reference[A]/2-(wewe<=0)){var oe,de;const we=(((oe=o.flip)==null?void 0:oe.index)||0)+1,Le=K[we];if(Le)return{data:{index:we,overflows:ee},reset:{placement:Le}};let Se=(de=ee.filter(ve=>ve.overflows[0]<=0).sort((ve,me)=>ve.overflows[1]-me.overflows[1])[0])==null?void 0:de.placement;if(!Se)switch(j){case"bestFit":{var ye;const ve=(ye=ee.filter(me=>{if(H){const ke=Zx(me.placement);return ke===D||ke==="y"}return!0}).map(me=>[me.placement,me.overflows.filter(ke=>ke>0).reduce((ke,Pe)=>ke+Pe,0)]).sort((me,ke)=>me[1]-ke[1])[0])==null?void 0:ye[0];ve&&(Se=ve);break}case"initialPlacement":Se=a;break}if(i!==Se)return{reset:{placement:Se}}}return{}}}};function Rne(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function Lne(t){return QBe.some(e=>t[e]>=0)}const c$e=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r}=e,{strategy:n="referenceHidden",...i}=Ig(t,e);switch(n){case"referenceHidden":{const o=await rN(e,{...i,elementContext:"reference"}),c=Rne(o,r.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:Lne(c)}}}case"escaped":{const o=await rN(e,{...i,altBoundary:!0}),c=Rne(o,r.floating);return{data:{escapedOffsets:c,escaped:Lne(c)}}}default:return{}}}}};async function u$e(t,e){const{placement:r,platform:n,elements:i}=t,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=Pg(r),a=tj(r),f=Zx(r)==="y",m=["left","top"].includes(c)?-1:1,y=o&&f?-1:1,v=Ig(e,t);let{mainAxis:w,crossAxis:j,alignmentAxis:A}=typeof v=="number"?{mainAxis:v,crossAxis:0,alignmentAxis:null}:{mainAxis:v.mainAxis||0,crossAxis:v.crossAxis||0,alignmentAxis:v.alignmentAxis};return a&&typeof A=="number"&&(j=a==="end"?A*-1:A),f?{x:j*y,y:w*m}:{x:w*m,y:j*y}}const d$e=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:a}=e,f=await u$e(e,t);return c===((r=a.offset)==null?void 0:r.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+f.x,y:o+f.y,data:{...f,placement:c}}}}},h$e=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:a={fn:I=>{let{x:M,y:D}=I;return{x:M,y:D}}},...f}=Ig(t,e),m={x:r,y:n},y=await rN(e,f),v=Zx(Pg(i)),w=QH(v);let j=m[w],A=m[v];if(o){const I=w==="y"?"top":"left",M=w==="y"?"bottom":"right",D=j+y[I],F=j-y[M];j=z8(D,j,F)}if(c){const I=v==="y"?"top":"left",M=v==="y"?"bottom":"right",D=A+y[I],F=A-y[M];A=z8(D,A,F)}const C=a.fn({...e,[w]:j,[v]:A});return{...C,data:{x:C.x-r,y:C.y-n,enabled:{[w]:o,[v]:c}}}}}},f$e=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:r,y:n,placement:i,rects:o,middlewareData:c}=e,{offset:a=0,mainAxis:f=!0,crossAxis:m=!0}=Ig(t,e),y={x:r,y:n},v=Zx(i),w=QH(v);let j=y[w],A=y[v];const C=Ig(a,e),I=typeof C=="number"?{mainAxis:C,crossAxis:0}:{mainAxis:0,crossAxis:0,...C};if(f){const F=w==="y"?"height":"width",z=o.reference[w]-o.floating[F]+I.mainAxis,q=o.reference[w]+o.reference[F]-I.mainAxis;jq&&(j=q)}if(m){var M,D;const F=w==="y"?"width":"height",z=["top","left"].includes(Pg(i)),q=o.reference[v]-o.floating[F]+(z&&((M=c.offset)==null?void 0:M[v])||0)+(z?0:I.crossAxis),H=o.reference[v]+o.reference[F]+(z?0:((D=c.offset)==null?void 0:D[v])||0)-(z?I.crossAxis:0);AH&&(A=H)}return{[w]:j,[v]:A}}}},m$e=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:a}=e,{apply:f=()=>{},...m}=Ig(t,e),y=await rN(e,m),v=Pg(i),w=tj(i),j=Zx(i)==="y",{width:A,height:C}=o.floating;let I,M;v==="top"||v==="bottom"?(I=v,M=w===(await(c.isRTL==null?void 0:c.isRTL(a.floating))?"start":"end")?"left":"right"):(M=v,I=w==="end"?"top":"bottom");const D=C-y.top-y.bottom,F=A-y.left-y.right,z=Kx(C-y[I],D),q=Kx(A-y[M],F),H=!e.middlewareData.shift;let K=z,J=q;if((r=e.middlewareData.shift)!=null&&r.enabled.x&&(J=F),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(K=D),H&&!w){const ee=Nd(y.left,0),oe=Nd(y.right,0),de=Nd(y.top,0),ye=Nd(y.bottom,0);j?J=A-2*(ee!==0||oe!==0?ee+oe:Nd(y.left,y.right)):K=C-2*(de!==0||ye!==0?de+ye:Nd(y.top,y.bottom))}await f({...e,availableWidth:J,availableHeight:K});const Q=await c.getDimensions(a.floating);return A!==Q.width||C!==Q.height?{reset:{rects:!0}}:{}}}};function P3(){return typeof window<"u"}function rj(t){return Bxe(t)?(t.nodeName||"").toLowerCase():"#document"}function Dd(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function cp(t){var e;return(e=(Bxe(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Bxe(t){return P3()?t instanceof Node||t instanceof Dd(t).Node:!1}function zf(t){return P3()?t instanceof Element||t instanceof Dd(t).Element:!1}function ep(t){return P3()?t instanceof HTMLElement||t instanceof Dd(t).HTMLElement:!1}function Mne(t){return!P3()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Dd(t).ShadowRoot}function DC(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=Uf(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&!["inline","contents"].includes(i)}function p$e(t){return["table","td","th"].includes(rj(t))}function R3(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function tW(t){const e=rW(),r=zf(t)?Uf(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 g$e(t){let e=Xx(t);for(;ep(e)&&!eT(e);){if(tW(e))return e;if(R3(e))return null;e=Xx(e)}return null}function rW(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eT(t){return["html","body","#document"].includes(rj(t))}function Uf(t){return Dd(t).getComputedStyle(t)}function L3(t){return zf(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Xx(t){if(rj(t)==="html")return t;const e=t.assignedSlot||t.parentNode||Mne(t)&&t.host||cp(t);return Mne(e)?e.host:e}function $xe(t){const e=Xx(t);return eT(e)?t.ownerDocument?t.ownerDocument.body:t.body:ep(e)&&DC(e)?e:$xe(e)}function nN(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=$xe(t),o=i===((n=t.ownerDocument)==null?void 0:n.body),c=Dd(i);if(o){const a=V8(c);return e.concat(c,c.visualViewport||[],DC(i)?i:[],a&&r?nN(a):[])}return e.concat(i,nN(i,[],r))}function V8(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function zxe(t){const e=Uf(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=ep(t),o=i?t.offsetWidth:r,c=i?t.offsetHeight:n,a=QD(r)!==o||QD(n)!==c;return a&&(r=o,n=c),{width:r,height:n,$:a}}function nW(t){return zf(t)?t:t.contextElement}function xS(t){const e=nW(t);if(!ep(e))return Yx(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:o}=zxe(e);let c=(o?QD(r.width):r.width)/n,a=(o?QD(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!a||!Number.isFinite(a))&&(a=1),{x:c,y:a}}const y$e=Yx(0);function Uxe(t){const e=Dd(t);return!rW()||!e.visualViewport?y$e:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function x$e(t,e,r){return e===void 0&&(e=!1),!r||e&&r!==Dd(t)?!1:e}function Z_(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),o=nW(t);let c=Yx(1);e&&(n?zf(n)&&(c=xS(n)):c=xS(t));const a=x$e(o,r,n)?Uxe(o):Yx(0);let f=(i.left+a.x)/c.x,m=(i.top+a.y)/c.y,y=i.width/c.x,v=i.height/c.y;if(o){const w=Dd(o),j=n&&zf(n)?Dd(n):n;let A=w,C=V8(A);for(;C&&n&&j!==A;){const I=xS(C),M=C.getBoundingClientRect(),D=Uf(C),F=M.left+(C.clientLeft+parseFloat(D.paddingLeft))*I.x,z=M.top+(C.clientTop+parseFloat(D.paddingTop))*I.y;f*=I.x,m*=I.y,y*=I.x,v*=I.y,f+=F,m+=z,A=Dd(C),C=V8(A)}}return eO({width:y,height:v,x:f,y:m})}function v$e(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const o=i==="fixed",c=cp(n),a=e?R3(e.floating):!1;if(n===c||a&&o)return r;let f={scrollLeft:0,scrollTop:0},m=Yx(1);const y=Yx(0),v=ep(n);if((v||!v&&!o)&&((rj(n)!=="body"||DC(c))&&(f=L3(n)),ep(n))){const w=Z_(n);m=xS(n),y.x=w.x+n.clientLeft,y.y=w.y+n.clientTop}return{width:r.width*m.x,height:r.height*m.y,x:r.x*m.x-f.scrollLeft*m.x+y.x,y:r.y*m.y-f.scrollTop*m.y+y.y}}function _$e(t){return Array.from(t.getClientRects())}function q8(t,e){const r=L3(t).scrollLeft;return e?e.left+r:Z_(cp(t)).left+r}function b$e(t){const e=cp(t),r=L3(t),n=t.ownerDocument.body,i=Nd(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=Nd(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let c=-r.scrollLeft+q8(t);const a=-r.scrollTop;return Uf(n).direction==="rtl"&&(c+=Nd(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:c,y:a}}function w$e(t,e){const r=Dd(t),n=cp(t),i=r.visualViewport;let o=n.clientWidth,c=n.clientHeight,a=0,f=0;if(i){o=i.width,c=i.height;const m=rW();(!m||m&&e==="fixed")&&(a=i.offsetLeft,f=i.offsetTop)}return{width:o,height:c,x:a,y:f}}function S$e(t,e){const r=Z_(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,o=ep(t)?xS(t):Yx(1),c=t.clientWidth*o.x,a=t.clientHeight*o.y,f=i*o.x,m=n*o.y;return{width:c,height:a,x:f,y:m}}function Dne(t,e,r){let n;if(e==="viewport")n=w$e(t,r);else if(e==="document")n=b$e(cp(t));else if(zf(e))n=S$e(e,r);else{const i=Uxe(t);n={...e,x:e.x-i.x,y:e.y-i.y}}return eO(n)}function Vxe(t,e){const r=Xx(t);return r===e||!zf(r)||eT(r)?!1:Uf(r).position==="fixed"||Vxe(r,e)}function T$e(t,e){const r=e.get(t);if(r)return r;let n=nN(t,[],!1).filter(a=>zf(a)&&rj(a)!=="body"),i=null;const o=Uf(t).position==="fixed";let c=o?Xx(t):t;for(;zf(c)&&!eT(c);){const a=Uf(c),f=tW(c);!f&&a.position==="fixed"&&(i=null),(o?!f&&!i:!f&&a.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||DC(c)&&!f&&Vxe(t,c))?n=n.filter(y=>y!==c):i=a,c=Xx(c)}return e.set(t,n),n}function j$e(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?R3(e)?[]:T$e(e,this._c):[].concat(r),n],a=c[0],f=c.reduce((m,y)=>{const v=Dne(e,y,i);return m.top=Nd(v.top,m.top),m.right=Kx(v.right,m.right),m.bottom=Kx(v.bottom,m.bottom),m.left=Nd(v.left,m.left),m},Dne(e,a,i));return{width:f.right-f.left,height:f.bottom-f.top,x:f.left,y:f.top}}function E$e(t){const{width:e,height:r}=zxe(t);return{width:e,height:r}}function k$e(t,e,r){const n=ep(e),i=cp(e),o=r==="fixed",c=Z_(t,!0,o,e);let a={scrollLeft:0,scrollTop:0};const f=Yx(0);if(n||!n&&!o)if((rj(e)!=="body"||DC(i))&&(a=L3(e)),n){const j=Z_(e,!0,o,e);f.x=j.x+e.clientLeft,f.y=j.y+e.clientTop}else i&&(f.x=q8(i));let m=0,y=0;if(i&&!n&&!o){const j=i.getBoundingClientRect();y=j.top+a.scrollTop,m=j.left+a.scrollLeft-q8(i,j)}const v=c.left+a.scrollLeft-f.x-m,w=c.top+a.scrollTop-f.y-y;return{x:v,y:w,width:c.width,height:c.height}}function s6(t){return Uf(t).position==="static"}function One(t,e){if(!ep(t)||Uf(t).position==="fixed")return null;if(e)return e(t);let r=t.offsetParent;return cp(t)===r&&(r=r.ownerDocument.body),r}function qxe(t,e){const r=Dd(t);if(R3(t))return r;if(!ep(t)){let i=Xx(t);for(;i&&!eT(i);){if(zf(i)&&!s6(i))return i;i=Xx(i)}return r}let n=One(t,e);for(;n&&p$e(n)&&s6(n);)n=One(n,e);return n&&eT(n)&&s6(n)&&!tW(n)?r:n||g$e(t)||r}const A$e=async function(t){const e=this.getOffsetParent||qxe,r=this.getDimensions,n=await r(t.floating);return{reference:k$e(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function N$e(t){return Uf(t).direction==="rtl"}const C$e={convertOffsetParentRelativeRectToViewportRelativeRect:v$e,getDocumentElement:cp,getClippingRect:j$e,getOffsetParent:qxe,getElementRects:A$e,getClientRects:_$e,getDimensions:E$e,getScale:xS,isElement:zf,isRTL:N$e};function I$e(t,e){let r=null,n;const i=cp(t);function o(){var a;clearTimeout(n),(a=r)==null||a.disconnect(),r=null}function c(a,f){a===void 0&&(a=!1),f===void 0&&(f=1),o();const{left:m,top:y,width:v,height:w}=t.getBoundingClientRect();if(a||e(),!v||!w)return;const j=pL(y),A=pL(i.clientWidth-(m+v)),C=pL(i.clientHeight-(y+w)),I=pL(m),D={rootMargin:-j+"px "+-A+"px "+-C+"px "+-I+"px",threshold:Nd(0,Kx(1,f))||1};let F=!0;function z(q){const H=q[0].intersectionRatio;if(H!==f){if(!F)return c();H?c(!1,H):n=setTimeout(()=>{c(!1,1e-7)},1e3)}F=!1}try{r=new IntersectionObserver(z,{...D,root:i.ownerDocument})}catch{r=new IntersectionObserver(z,D)}r.observe(t)}return c(!0),o}function P$e(t,e,r,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:f=!1}=n,m=nW(t),y=i||o?[...m?nN(m):[],...nN(e)]:[];y.forEach(M=>{i&&M.addEventListener("scroll",r,{passive:!0}),o&&M.addEventListener("resize",r)});const v=m&&a?I$e(m,r):null;let w=-1,j=null;c&&(j=new ResizeObserver(M=>{let[D]=M;D&&D.target===m&&j&&(j.unobserve(e),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var F;(F=j)==null||F.observe(e)})),r()}),m&&!f&&j.observe(m),j.observe(e));let A,C=f?Z_(t):null;f&&I();function I(){const M=Z_(t);C&&(M.x!==C.x||M.y!==C.y||M.width!==C.width||M.height!==C.height)&&r(),C=M,A=requestAnimationFrame(I)}return r(),()=>{var M;y.forEach(D=>{i&&D.removeEventListener("scroll",r),o&&D.removeEventListener("resize",r)}),v==null||v(),(M=j)==null||M.disconnect(),j=null,f&&cancelAnimationFrame(A)}}const R$e=d$e,L$e=h$e,M$e=l$e,D$e=m$e,O$e=c$e,Fne=o$e,F$e=f$e,B$e=(t,e,r)=>{const n=new Map,i={platform:C$e,...r},o={...i.platform,_c:n};return a$e(t,e,{...i,platform:o})};var zM=typeof document<"u"?N.useLayoutEffect:N.useEffect;function tO(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(!tO(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)&&!tO(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function Gxe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Bne(t,e){const r=Gxe(t);return Math.round(e*r)/r}function i6(t){const e=N.useRef(t);return zM(()=>{e.current=t}),e}function $$e(t){t===void 0&&(t={});const{placement:e="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:o,floating:c}={},transform:a=!0,whileElementsMounted:f,open:m}=t,[y,v]=N.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[w,j]=N.useState(n);tO(w,n)||j(n);const[A,C]=N.useState(null),[I,M]=N.useState(null),D=N.useCallback(me=>{me!==H.current&&(H.current=me,C(me))},[]),F=N.useCallback(me=>{me!==K.current&&(K.current=me,M(me))},[]),z=o||A,q=c||I,H=N.useRef(null),K=N.useRef(null),J=N.useRef(y),Q=f!=null,ee=i6(f),oe=i6(i),de=i6(m),ye=N.useCallback(()=>{if(!H.current||!K.current)return;const me={placement:e,strategy:r,middleware:w};oe.current&&(me.platform=oe.current),B$e(H.current,K.current,me).then(ke=>{const Pe={...ke,isPositioned:de.current!==!1};we.current&&!tO(J.current,Pe)&&(J.current=Pe,op.flushSync(()=>{v(Pe)}))})},[w,e,r,oe,de]);zM(()=>{m===!1&&J.current.isPositioned&&(J.current.isPositioned=!1,v(me=>({...me,isPositioned:!1})))},[m]);const we=N.useRef(!1);zM(()=>(we.current=!0,()=>{we.current=!1}),[]),zM(()=>{if(z&&(H.current=z),q&&(K.current=q),z&&q){if(ee.current)return ee.current(z,q,ye);ye()}},[z,q,ye,ee,Q]);const Le=N.useMemo(()=>({reference:H,floating:K,setReference:D,setFloating:F}),[D,F]),Se=N.useMemo(()=>({reference:z,floating:q}),[z,q]),ve=N.useMemo(()=>{const me={position:r,left:0,top:0};if(!Se.floating)return me;const ke=Bne(Se.floating,y.x),Pe=Bne(Se.floating,y.y);return a?{...me,transform:"translate("+ke+"px, "+Pe+"px)",...Gxe(Se.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:ke,top:Pe}},[r,a,Se.floating,y.x,y.y]);return N.useMemo(()=>({...y,update:ye,refs:Le,elements:Se,floatingStyles:ve}),[y,ye,Le,Se,ve])}const z$e=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?Fne({element:n.current,padding:i}).fn(r):{}:n?Fne({element:n,padding:i}).fn(r):{}}}},U$e=(t,e)=>({...R$e(t),options:[t,e]}),V$e=(t,e)=>({...L$e(t),options:[t,e]}),q$e=(t,e)=>({...F$e(t),options:[t,e]}),G$e=(t,e)=>({...M$e(t),options:[t,e]}),H$e=(t,e)=>({...D$e(t),options:[t,e]}),W$e=(t,e)=>({...O$e(t),options:[t,e]}),K$e=(t,e)=>({...z$e(t),options:[t,e]});var Y$e="Arrow",Hxe=N.forwardRef((t,e)=>{const{children:r,width:n=10,height:i=5,...o}=t;return s.jsx(cn.svg,{...o,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});Hxe.displayName=Y$e;var Z$e=Hxe;function OC(t){const[e,r]=N.useState(void 0);return Ho(()=>{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,a;if("borderBoxSize"in o){const f=o.borderBoxSize,m=Array.isArray(f)?f[0]:f;c=m.inlineSize,a=m.blockSize}else c=t.offsetWidth,a=t.offsetHeight;r({width:c,height:a})});return n.observe(t,{box:"border-box"}),()=>n.unobserve(t)}else r(void 0)},[t]),e}var sW="Popper",[Wxe,g0]=dl(sW),[X$e,Kxe]=Wxe(sW),Yxe=t=>{const{__scopePopper:e,children:r}=t,[n,i]=N.useState(null);return s.jsx(X$e,{scope:e,anchor:n,onAnchorChange:i,children:r})};Yxe.displayName=sW;var Zxe="PopperAnchor",Xxe=N.forwardRef((t,e)=>{const{__scopePopper:r,virtualRef:n,...i}=t,o=Kxe(Zxe,r),c=N.useRef(null),a=is(e,c);return N.useEffect(()=>{o.onAnchorChange((n==null?void 0:n.current)||c.current)}),n?null:s.jsx(cn.div,{...i,ref:a})});Xxe.displayName=Zxe;var iW="PopperContent",[Q$e,J$e]=Wxe(iW),Qxe=N.forwardRef((t,e)=>{var yt,gt,ft,kt,Vt,xt;const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:c=0,arrowPadding:a=0,avoidCollisions:f=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:v="partial",hideWhenDetached:w=!1,updatePositionStrategy:j="optimized",onPlaced:A,...C}=t,I=Kxe(iW,r),[M,D]=N.useState(null),F=is(e,or=>D(or)),[z,q]=N.useState(null),H=OC(z),K=(H==null?void 0:H.width)??0,J=(H==null?void 0:H.height)??0,Q=n+(o!=="center"?"-"+o:""),ee=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},oe=Array.isArray(m)?m:[m],de=oe.length>0,ye={padding:ee,boundary:oe.filter(tze),altBoundary:de},{refs:we,floatingStyles:Le,placement:Se,isPositioned:ve,middlewareData:me}=$$e({strategy:"fixed",placement:Q,whileElementsMounted:(...or)=>P$e(...or,{animationFrame:j==="always"}),elements:{reference:I.anchor},middleware:[U$e({mainAxis:i+J,alignmentAxis:c}),f&&V$e({mainAxis:!0,crossAxis:!1,limiter:v==="partial"?q$e():void 0,...ye}),f&&G$e({...ye}),H$e({...ye,apply:({elements:or,rects:Tr,availableWidth:rn,availableHeight:Lr})=>{const{width:$r,height:qr}=Tr.reference,Nn=or.floating.style;Nn.setProperty("--radix-popper-available-width",`${rn}px`),Nn.setProperty("--radix-popper-available-height",`${Lr}px`),Nn.setProperty("--radix-popper-anchor-width",`${$r}px`),Nn.setProperty("--radix-popper-anchor-height",`${qr}px`)}}),z&&K$e({element:z,padding:a}),rze({arrowWidth:K,arrowHeight:J}),w&&W$e({strategy:"referenceHidden",...ye})]}),[ke,Pe]=t0e(Se),Ee=go(A);Ho(()=>{ve&&(Ee==null||Ee())},[ve,Ee]);const xe=(yt=me.arrow)==null?void 0:yt.x,Ue=(gt=me.arrow)==null?void 0:gt.y,Ze=((ft=me.arrow)==null?void 0:ft.centerOffset)!==0,[lt,wt]=N.useState();return Ho(()=>{M&&wt(window.getComputedStyle(M).zIndex)},[M]),s.jsx("div",{ref:we.setFloating,"data-radix-popper-content-wrapper":"",style:{...Le,transform:ve?Le.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:lt,"--radix-popper-transform-origin":[(kt=me.transformOrigin)==null?void 0:kt.x,(Vt=me.transformOrigin)==null?void 0:Vt.y].join(" "),...((xt=me.hide)==null?void 0:xt.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:s.jsx(Q$e,{scope:r,placedSide:ke,onArrowChange:q,arrowX:xe,arrowY:Ue,shouldHideArrow:Ze,children:s.jsx(cn.div,{"data-side":ke,"data-align":Pe,...C,ref:F,style:{...C.style,animation:ve?void 0:"none"}})})})});Qxe.displayName=iW;var Jxe="PopperArrow",eze={top:"bottom",right:"left",bottom:"top",left:"right"},e0e=N.forwardRef(function(e,r){const{__scopePopper:n,...i}=e,o=J$e(Jxe,n),c=eze[o.placedSide];return s.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:s.jsx(Z$e,{...i,ref:r,style:{...i.style,display:"block"}})})});e0e.displayName=Jxe;function tze(t){return t!==null}var rze=t=>({name:"transformOrigin",options:t,fn(e){var I,M,D;const{placement:r,rects:n,middlewareData:i}=e,c=((I=i.arrow)==null?void 0:I.centerOffset)!==0,a=c?0:t.arrowWidth,f=c?0:t.arrowHeight,[m,y]=t0e(r),v={start:"0%",center:"50%",end:"100%"}[y],w=(((M=i.arrow)==null?void 0:M.x)??0)+a/2,j=(((D=i.arrow)==null?void 0:D.y)??0)+f/2;let A="",C="";return m==="bottom"?(A=c?v:`${w}px`,C=`${-f}px`):m==="top"?(A=c?v:`${w}px`,C=`${n.floating.height+f}px`):m==="right"?(A=`${-f}px`,C=c?v:`${j}px`):m==="left"&&(A=`${n.floating.width+f}px`,C=c?v:`${j}px`),{data:{x:A,y:C}}}});function t0e(t){const[e,r="center"]=t.split("-");return[e,r]}var FC=Yxe,BC=Xxe,M3=Qxe,D3=e0e,[O3,CJt]=dl("Tooltip",[g0]),F3=g0(),r0e="TooltipProvider",nze=700,G8="tooltip.open",[sze,aW]=O3(r0e),n0e=t=>{const{__scopeTooltip:e,delayDuration:r=nze,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=t,c=N.useRef(!0),a=N.useRef(!1),f=N.useRef(0);return N.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),s.jsx(sze,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:N.useCallback(()=>{window.clearTimeout(f.current),c.current=!1},[]),onClose:N.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.current=!0,n)},[n]),isPointerInTransitRef:a,onPointerInTransitChange:N.useCallback(m=>{a.current=m},[]),disableHoverableContent:i,children:o})};n0e.displayName=r0e;var sN="Tooltip",[ize,B3]=O3(sN),s0e=t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:o,disableHoverableContent:c,delayDuration:a}=t,f=aW(sN,t.__scopeTooltip),m=F3(e),[y,v]=N.useState(null),w=ol(),j=N.useRef(0),A=c??f.disableHoverableContent,C=a??f.delayDuration,I=N.useRef(!1),[M,D]=rd({prop:n,defaultProp:i??!1,onChange:K=>{K?(f.onOpen(),document.dispatchEvent(new CustomEvent(G8))):f.onClose(),o==null||o(K)},caller:sN}),F=N.useMemo(()=>M?I.current?"delayed-open":"instant-open":"closed",[M]),z=N.useCallback(()=>{window.clearTimeout(j.current),j.current=0,I.current=!1,D(!0)},[D]),q=N.useCallback(()=>{window.clearTimeout(j.current),j.current=0,D(!1)},[D]),H=N.useCallback(()=>{window.clearTimeout(j.current),j.current=window.setTimeout(()=>{I.current=!0,D(!0),j.current=0},C)},[C,D]);return N.useEffect(()=>()=>{j.current&&(window.clearTimeout(j.current),j.current=0)},[]),s.jsx(FC,{...m,children:s.jsx(ize,{scope:e,contentId:w,open:M,stateAttribute:F,trigger:y,onTriggerChange:v,onTriggerEnter:N.useCallback(()=>{f.isOpenDelayedRef.current?H():z()},[f.isOpenDelayedRef,H,z]),onTriggerLeave:N.useCallback(()=>{A?q():(window.clearTimeout(j.current),j.current=0)},[q,A]),onOpen:z,onClose:q,disableHoverableContent:A,children:r})})};s0e.displayName=sN;var H8="TooltipTrigger",i0e=N.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=B3(H8,r),o=aW(H8,r),c=F3(r),a=N.useRef(null),f=is(e,a,i.onTriggerChange),m=N.useRef(!1),y=N.useRef(!1),v=N.useCallback(()=>m.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",v),[v]),s.jsx(BC,{asChild:!0,...c,children:s.jsx(cn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:f,onPointerMove:Gr(t.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Gr(t.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Gr(t.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",v,{once:!0})}),onFocus:Gr(t.onFocus,()=>{m.current||i.onOpen()}),onBlur:Gr(t.onBlur,i.onClose),onClick:Gr(t.onClick,i.onClose)})})});i0e.displayName=H8;var aze="TooltipPortal",[IJt,oze]=O3(aze,{forceMount:void 0}),tT="TooltipContent",a0e=N.forwardRef((t,e)=>{const r=oze(tT,t.__scopeTooltip),{forceMount:n=r.forceMount,side:i="top",...o}=t,c=B3(tT,t.__scopeTooltip);return s.jsx(Pl,{present:n||c.open,children:c.disableHoverableContent?s.jsx(o0e,{side:i,...o,ref:e}):s.jsx(lze,{side:i,...o,ref:e})})}),lze=N.forwardRef((t,e)=>{const r=B3(tT,t.__scopeTooltip),n=aW(tT,t.__scopeTooltip),i=N.useRef(null),o=is(e,i),[c,a]=N.useState(null),{trigger:f,onClose:m}=r,y=i.current,{onPointerInTransitChange:v}=n,w=N.useCallback(()=>{a(null),v(!1)},[v]),j=N.useCallback((A,C)=>{const I=A.currentTarget,M={x:A.clientX,y:A.clientY},D=fze(M,I.getBoundingClientRect()),F=mze(M,D),z=pze(C.getBoundingClientRect()),q=yze([...F,...z]);a(q),v(!0)},[v]);return N.useEffect(()=>()=>w(),[w]),N.useEffect(()=>{if(f&&y){const A=I=>j(I,y),C=I=>j(I,f);return f.addEventListener("pointerleave",A),y.addEventListener("pointerleave",C),()=>{f.removeEventListener("pointerleave",A),y.removeEventListener("pointerleave",C)}}},[f,y,j,w]),N.useEffect(()=>{if(c){const A=C=>{const I=C.target,M={x:C.clientX,y:C.clientY},D=(f==null?void 0:f.contains(I))||(y==null?void 0:y.contains(I)),F=!gze(M,c);D?w():F&&(w(),m())};return document.addEventListener("pointermove",A),()=>document.removeEventListener("pointermove",A)}},[f,y,c,m,w]),s.jsx(o0e,{...t,ref:o})}),[cze,uze]=O3(sN,{isInside:!1}),dze=Wge("TooltipContent"),o0e=N.forwardRef((t,e)=>{const{__scopeTooltip:r,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:c,...a}=t,f=B3(tT,r),m=F3(r),{onClose:y}=f;return N.useEffect(()=>(document.addEventListener(G8,y),()=>document.removeEventListener(G8,y)),[y]),N.useEffect(()=>{if(f.trigger){const v=w=>{const j=w.target;j!=null&&j.contains(f.trigger)&&y()};return window.addEventListener("scroll",v,{capture:!0}),()=>window.removeEventListener("scroll",v,{capture:!0})}},[f.trigger,y]),s.jsx(fb,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:v=>v.preventDefault(),onDismiss:y,children:s.jsxs(M3,{"data-state":f.stateAttribute,...m,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(dze,{children:n}),s.jsx(cze,{scope:r,isInside:!0,children:s.jsx(c3e,{id:f.contentId,role:"tooltip",children:i||n})})]})})});a0e.displayName=tT;var l0e="TooltipArrow",hze=N.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=F3(r);return uze(l0e,r).isInside?null:s.jsx(D3,{...i,...n,ref:e})});hze.displayName=l0e;function fze(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 mze(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 pze(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 gze(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=w>n&&r<(v-m)*(n-y)/(w-y)+m&&(i=!i)}return i}function yze(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),xze(e)}function xze(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 vze=n0e,_ze=s0e,bze=i0e,c0e=a0e;const u0e=vze,wze=_ze,Sze=bze,d0e=N.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(c0e,{ref:n,sideOffset:e,className:Xt("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}));d0e.displayName=c0e.displayName;var nj=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(){}},X_=typeof window>"u"||"Deno"in globalThis;function mu(){}function Tze(t,e){return typeof t=="function"?t(e):t}function W8(t){return typeof t=="number"&&t>=0&&t!==1/0}function h0e(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Dx(t,e){return typeof t=="function"?t(e):t}function xh(t,e){return typeof t=="function"?t(e):t}function $ne(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:o,queryKey:c,stale:a}=t;if(c){if(n){if(e.queryHash!==oW(c,e.options))return!1}else if(!iN(e.queryKey,c))return!1}if(r!=="all"){const f=e.isActive();if(r==="active"&&!f||r==="inactive"&&f)return!1}return!(typeof a=="boolean"&&e.isStale()!==a||i&&i!==e.state.fetchStatus||o&&!o(e))}function zne(t,e){const{exact:r,status:n,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(r){if(Q_(e.options.mutationKey)!==Q_(o))return!1}else if(!iN(e.options.mutationKey,o))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function oW(t,e){return((e==null?void 0:e.queryKeyHashFn)||Q_)(t)}function Q_(t){return JSON.stringify(t,(e,r)=>K8(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function iN(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>iN(t[r],e[r])):!1}function f0e(t,e){if(t===e)return t;const r=Une(t)&&Une(e);if(r||K8(t)&&K8(e)){const n=r?t:Object.keys(t),i=n.length,o=r?e:Object.keys(e),c=o.length,a=r?[]:{},f=new Set(n);let m=0;for(let y=0;y{setTimeout(e,t)})}function Y8(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?f0e(t,e):e}function Eze(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function kze(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}var lW=Symbol();function m0e(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===lW?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function p0e(t,e){return typeof t=="function"?t(...e):!!t}var b_,ux,RS,xme,Aze=(xme=class extends nj{constructor(){super();os(this,b_);os(this,ux);os(this,RS);Sn(this,RS,e=>{if(!X_&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Ct(this,ux)||this.setEventListener(Ct(this,RS))}onUnsubscribe(){var e;this.hasListeners()||((e=Ct(this,ux))==null||e.call(this),Sn(this,ux,void 0))}setEventListener(e){var r;Sn(this,RS,e),(r=Ct(this,ux))==null||r.call(this),Sn(this,ux,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Ct(this,b_)!==e&&(Sn(this,b_,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Ct(this,b_)=="boolean"?Ct(this,b_):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},b_=new WeakMap,ux=new WeakMap,RS=new WeakMap,xme),cW=new Aze,LS,dx,MS,vme,Nze=(vme=class extends nj{constructor(){super();os(this,LS,!0);os(this,dx);os(this,MS);Sn(this,MS,e=>{if(!X_&&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(){Ct(this,dx)||this.setEventListener(Ct(this,MS))}onUnsubscribe(){var e;this.hasListeners()||((e=Ct(this,dx))==null||e.call(this),Sn(this,dx,void 0))}setEventListener(e){var r;Sn(this,MS,e),(r=Ct(this,dx))==null||r.call(this),Sn(this,dx,e(this.setOnline.bind(this)))}setOnline(e){Ct(this,LS)!==e&&(Sn(this,LS,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Ct(this,LS)}},LS=new WeakMap,dx=new WeakMap,MS=new WeakMap,vme),nO=new Nze;function Z8(){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 Cze(t){return Math.min(1e3*2**t,3e4)}function g0e(t){return(t??"online")==="online"?nO.isOnline():!0}var y0e=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function a6(t){return t instanceof y0e}function x0e(t){let e=!1,r=0,n=!1,i;const o=Z8(),c=C=>{var I;n||(w(new y0e(C)),(I=t.abort)==null||I.call(t))},a=()=>{e=!0},f=()=>{e=!1},m=()=>cW.isFocused()&&(t.networkMode==="always"||nO.isOnline())&&t.canRun(),y=()=>g0e(t.networkMode)&&t.canRun(),v=C=>{var I;n||(n=!0,(I=t.onSuccess)==null||I.call(t,C),i==null||i(),o.resolve(C))},w=C=>{var I;n||(n=!0,(I=t.onError)==null||I.call(t,C),i==null||i(),o.reject(C))},j=()=>new Promise(C=>{var I;i=M=>{(n||m())&&C(M)},(I=t.onPause)==null||I.call(t)}).then(()=>{var C;i=void 0,n||(C=t.onContinue)==null||C.call(t)}),A=()=>{if(n)return;let C;const I=r===0?t.initialPromise:void 0;try{C=I??t.fn()}catch(M){C=Promise.reject(M)}Promise.resolve(C).then(v).catch(M=>{var H;if(n)return;const D=t.retry??(X_?0:3),F=t.retryDelay??Cze,z=typeof F=="function"?F(r,M):F,q=D===!0||typeof D=="number"&&rm()?void 0:j()).then(()=>{e?w(M):A()})})};return{promise:o,cancel:c,continue:()=>(i==null||i(),o),cancelRetry:a,continueRetry:f,canStart:y,start:()=>(y()?A():j().then(A),o)}}var Ize=t=>setTimeout(t,0);function Pze(){let t=[],e=0,r=a=>{a()},n=a=>{a()},i=Ize;const o=a=>{e?t.push(a):i(()=>{r(a)})},c=()=>{const a=t;t=[],a.length&&i(()=>{n(()=>{a.forEach(f=>{r(f)})})})};return{batch:a=>{let f;e++;try{f=a()}finally{e--,e||c()}return f},batchCalls:a=>(...f)=>{o(()=>{a(...f)})},schedule:o,setNotifyFunction:a=>{r=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{i=a}}}var El=Pze(),w_,_me,v0e=(_me=class{constructor(){os(this,w_)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),W8(this.gcTime)&&Sn(this,w_,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(X_?1/0:5*60*1e3))}clearGcTimeout(){Ct(this,w_)&&(clearTimeout(Ct(this,w_)),Sn(this,w_,void 0))}},w_=new WeakMap,_me),DS,S_,yh,T_,Rc,gC,j_,pf,tg,bme,Rze=(bme=class extends v0e{constructor(e){super();os(this,pf);os(this,DS);os(this,S_);os(this,yh);os(this,T_);os(this,Rc);os(this,gC);os(this,j_);Sn(this,j_,!1),Sn(this,gC,e.defaultOptions),this.setOptions(e.options),this.observers=[],Sn(this,T_,e.client),Sn(this,yh,Ct(this,T_).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,Sn(this,DS,Lze(this.options)),this.state=e.state??Ct(this,DS),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=Ct(this,Rc))==null?void 0:e.promise}setOptions(e){this.options={...Ct(this,gC),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Ct(this,yh).remove(this)}setData(e,r){const n=Y8(this.state.data,e,this.options);return Zs(this,pf,tg).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e,r){Zs(this,pf,tg).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var n,i;const r=(n=Ct(this,Rc))==null?void 0:n.promise;return(i=Ct(this,Rc))==null||i.cancel(e),r?r.then(mu).catch(mu):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Ct(this,DS))}isActive(){return this.observers.some(e=>xh(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lW||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Dx(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:!h0e(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=Ct(this,Rc))==null||r.continue()}onOnline(){var r;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=Ct(this,Rc))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Ct(this,yh).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(Ct(this,Rc)&&(Ct(this,j_)?Ct(this,Rc).cancel({revert:!0}):Ct(this,Rc).cancelRetry()),this.scheduleGc()),Ct(this,yh).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Zs(this,pf,tg).call(this,{type:"invalidate"})}fetch(e,r){var m,y,v;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Ct(this,Rc))return Ct(this,Rc).continueRetry(),Ct(this,Rc).promise}if(e&&this.setOptions(e),!this.options.queryFn){const w=this.observers.find(j=>j.options.queryFn);w&&this.setOptions(w.options)}const n=new AbortController,i=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(Sn(this,j_,!0),n.signal)})},o=()=>{const w=m0e(this.options,r),A=(()=>{const C={client:Ct(this,T_),queryKey:this.queryKey,meta:this.meta};return i(C),C})();return Sn(this,j_,!1),this.options.persister?this.options.persister(w,A,this):w(A)},a=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Ct(this,T_),state:this.state,fetchFn:o};return i(w),w})();(m=this.options.behavior)==null||m.onFetch(a,this),Sn(this,S_,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((y=a.fetchOptions)==null?void 0:y.meta))&&Zs(this,pf,tg).call(this,{type:"fetch",meta:(v=a.fetchOptions)==null?void 0:v.meta});const f=w=>{var j,A,C,I;a6(w)&&w.silent||Zs(this,pf,tg).call(this,{type:"error",error:w}),a6(w)||((A=(j=Ct(this,yh).config).onError)==null||A.call(j,w,this),(I=(C=Ct(this,yh).config).onSettled)==null||I.call(C,this.state.data,w,this)),this.scheduleGc()};return Sn(this,Rc,x0e({initialPromise:r==null?void 0:r.initialPromise,fn:a.fetchFn,abort:n.abort.bind(n),onSuccess:w=>{var j,A,C,I;if(w===void 0){f(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(w)}catch(M){f(M);return}(A=(j=Ct(this,yh).config).onSuccess)==null||A.call(j,w,this),(I=(C=Ct(this,yh).config).onSettled)==null||I.call(C,w,this.state.error,this),this.scheduleGc()},onError:f,onFail:(w,j)=>{Zs(this,pf,tg).call(this,{type:"failed",failureCount:w,error:j})},onPause:()=>{Zs(this,pf,tg).call(this,{type:"pause"})},onContinue:()=>{Zs(this,pf,tg).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),Ct(this,Rc).start()}},DS=new WeakMap,S_=new WeakMap,yh=new WeakMap,T_=new WeakMap,Rc=new WeakMap,gC=new WeakMap,j_=new WeakMap,pf=new WeakSet,tg=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,..._0e(n.data,this.options),fetchMeta:e.meta??null};case"success":return Sn(this,S_,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 a6(i)&&i.revert&&Ct(this,S_)?{...Ct(this,S_),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),El.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Ct(this,yh).notify({query:this,type:"updated",action:e})})},bme);function _0e(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:g0e(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Lze(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 Nm,wme,Mze=(wme=class extends nj{constructor(e={}){super();os(this,Nm);this.config=e,Sn(this,Nm,new Map)}build(e,r,n){const i=r.queryKey,o=r.queryHash??oW(i,r);let c=this.get(o);return c||(c=new Rze({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Ct(this,Nm).has(e.queryHash)||(Ct(this,Nm).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=Ct(this,Nm).get(e.queryHash);r&&(e.destroy(),r===e&&Ct(this,Nm).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){El.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Ct(this,Nm).get(e)}getAll(){return[...Ct(this,Nm).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>$ne(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>$ne(e,n)):r}notify(e){El.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){El.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){El.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Nm=new WeakMap,wme),Cm,du,E_,Im,Ky,Sme,Dze=(Sme=class extends v0e{constructor(e){super();os(this,Im);os(this,Cm);os(this,du);os(this,E_);this.mutationId=e.mutationId,Sn(this,du,e.mutationCache),Sn(this,Cm,[]),this.state=e.state||b0e(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Ct(this,Cm).includes(e)||(Ct(this,Cm).push(e),this.clearGcTimeout(),Ct(this,du).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){Sn(this,Cm,Ct(this,Cm).filter(r=>r!==e)),this.scheduleGc(),Ct(this,du).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Ct(this,Cm).length||(this.state.status==="pending"?this.scheduleGc():Ct(this,du).remove(this))}continue(){var e;return((e=Ct(this,E_))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var o,c,a,f,m,y,v,w,j,A,C,I,M,D,F,z,q,H,K,J;const r=()=>{Zs(this,Im,Ky).call(this,{type:"continue"})};Sn(this,E_,x0e({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(Q,ee)=>{Zs(this,Im,Ky).call(this,{type:"failed",failureCount:Q,error:ee})},onPause:()=>{Zs(this,Im,Ky).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Ct(this,du).canRun(this)}));const n=this.state.status==="pending",i=!Ct(this,E_).canStart();try{if(n)r();else{Zs(this,Im,Ky).call(this,{type:"pending",variables:e,isPaused:i}),await((c=(o=Ct(this,du).config).onMutate)==null?void 0:c.call(o,e,this));const ee=await((f=(a=this.options).onMutate)==null?void 0:f.call(a,e));ee!==this.state.context&&Zs(this,Im,Ky).call(this,{type:"pending",context:ee,variables:e,isPaused:i})}const Q=await Ct(this,E_).start();return await((y=(m=Ct(this,du).config).onSuccess)==null?void 0:y.call(m,Q,e,this.state.context,this)),await((w=(v=this.options).onSuccess)==null?void 0:w.call(v,Q,e,this.state.context)),await((A=(j=Ct(this,du).config).onSettled)==null?void 0:A.call(j,Q,null,this.state.variables,this.state.context,this)),await((I=(C=this.options).onSettled)==null?void 0:I.call(C,Q,null,e,this.state.context)),Zs(this,Im,Ky).call(this,{type:"success",data:Q}),Q}catch(Q){try{throw await((D=(M=Ct(this,du).config).onError)==null?void 0:D.call(M,Q,e,this.state.context,this)),await((z=(F=this.options).onError)==null?void 0:z.call(F,Q,e,this.state.context)),await((H=(q=Ct(this,du).config).onSettled)==null?void 0:H.call(q,void 0,Q,this.state.variables,this.state.context,this)),await((J=(K=this.options).onSettled)==null?void 0:J.call(K,void 0,Q,e,this.state.context)),Q}finally{Zs(this,Im,Ky).call(this,{type:"error",error:Q})}}finally{Ct(this,du).runNext(this)}}},Cm=new WeakMap,du=new WeakMap,E_=new WeakMap,Im=new WeakSet,Ky=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),El.batch(()=>{Ct(this,Cm).forEach(n=>{n.onMutationUpdate(e)}),Ct(this,du).notify({mutation:this,type:"updated",action:e})})},Sme);function b0e(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ug,gf,yC,Tme,Oze=(Tme=class extends nj{constructor(e={}){super();os(this,ug);os(this,gf);os(this,yC);this.config=e,Sn(this,ug,new Set),Sn(this,gf,new Map),Sn(this,yC,0)}build(e,r,n){const i=new Dze({mutationCache:this,mutationId:++qR(this,yC)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Ct(this,ug).add(e);const r=gL(e);if(typeof r=="string"){const n=Ct(this,gf).get(r);n?n.push(e):Ct(this,gf).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Ct(this,ug).delete(e)){const r=gL(e);if(typeof r=="string"){const n=Ct(this,gf).get(r);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&Ct(this,gf).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=gL(e);if(typeof r=="string"){const n=Ct(this,gf).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=gL(e);if(typeof r=="string"){const i=(n=Ct(this,gf).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(){El.batch(()=>{Ct(this,ug).forEach(e=>{this.notify({type:"removed",mutation:e})}),Ct(this,ug).clear(),Ct(this,gf).clear()})}getAll(){return Array.from(Ct(this,ug))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>zne(r,n))}findAll(e={}){return this.getAll().filter(r=>zne(e,r))}notify(e){El.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return El.batch(()=>Promise.all(e.map(r=>r.continue().catch(mu))))}},ug=new WeakMap,gf=new WeakMap,yC=new WeakMap,Tme);function gL(t){var e;return(e=t.options.scope)==null?void 0:e.id}function qne(t){return{onFetch:(e,r)=>{var y,v,w,j,A;const n=e.options,i=(w=(v=(y=e.fetchOptions)==null?void 0:y.meta)==null?void 0:v.fetchMore)==null?void 0:w.direction,o=((j=e.state.data)==null?void 0:j.pages)||[],c=((A=e.state.data)==null?void 0:A.pageParams)||[];let a={pages:[],pageParams:[]},f=0;const m=async()=>{let C=!1;const I=F=>{Object.defineProperty(F,"signal",{enumerable:!0,get:()=>(e.signal.aborted?C=!0:e.signal.addEventListener("abort",()=>{C=!0}),e.signal)})},M=m0e(e.options,e.fetchOptions),D=async(F,z,q)=>{if(C)return Promise.reject();if(z==null&&F.pages.length)return Promise.resolve(F);const K=(()=>{const oe={client:e.client,queryKey:e.queryKey,pageParam:z,direction:q?"backward":"forward",meta:e.options.meta};return I(oe),oe})(),J=await M(K),{maxPages:Q}=e.options,ee=q?kze:Eze;return{pages:ee(F.pages,J,Q),pageParams:ee(F.pageParams,z,Q)}};if(i&&o.length){const F=i==="backward",z=F?w0e:X8,q={pages:o,pageParams:c},H=z(n,q);a=await D(q,H,F)}else{const F=t??o.length;do{const z=f===0?c[0]??n.initialPageParam:X8(n,a);if(f>0&&z==null)break;a=await D(a,z),f++}while(f{var C,I;return(I=(C=e.options).persister)==null?void 0:I.call(C,m,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=m}}}function X8(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 w0e(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 PJt(t,e){return e?X8(t,e)!=null:!1}function RJt(t,e){return!e||!t.getPreviousPageParam?!1:w0e(t,e)!=null}var No,hx,fx,OS,FS,mx,BS,$S,jme,Fze=(jme=class{constructor(t={}){os(this,No);os(this,hx);os(this,fx);os(this,OS);os(this,FS);os(this,mx);os(this,BS);os(this,$S);Sn(this,No,t.queryCache||new Mze),Sn(this,hx,t.mutationCache||new Oze),Sn(this,fx,t.defaultOptions||{}),Sn(this,OS,new Map),Sn(this,FS,new Map),Sn(this,mx,0)}mount(){qR(this,mx)._++,Ct(this,mx)===1&&(Sn(this,BS,cW.subscribe(async t=>{t&&(await this.resumePausedMutations(),Ct(this,No).onFocus())})),Sn(this,$S,nO.subscribe(async t=>{t&&(await this.resumePausedMutations(),Ct(this,No).onOnline())})))}unmount(){var t,e;qR(this,mx)._--,Ct(this,mx)===0&&((t=Ct(this,BS))==null||t.call(this),Sn(this,BS,void 0),(e=Ct(this,$S))==null||e.call(this),Sn(this,$S,void 0))}isFetching(t){return Ct(this,No).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Ct(this,hx).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Ct(this,No).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Ct(this,No).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Dx(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Ct(this,No).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=Ct(this,No).get(n.queryHash),o=i==null?void 0:i.state.data,c=Tze(e,o);if(c!==void 0)return Ct(this,No).build(this,n).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return El.batch(()=>Ct(this,No).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Ct(this,No).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Ct(this,No);El.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Ct(this,No);return El.batch(()=>(r.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},n=El.batch(()=>Ct(this,No).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(mu).catch(mu)}invalidateQueries(t,e={}){return El.batch(()=>(Ct(this,No).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=El.batch(()=>Ct(this,No).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,r);return r.throwOnError||(o=o.catch(mu)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(n).then(mu)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Ct(this,No).build(this,e);return r.isStaleByTime(Dx(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(mu).catch(mu)}fetchInfiniteQuery(t){return t.behavior=qne(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(mu).catch(mu)}ensureInfiniteQueryData(t){return t.behavior=qne(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return nO.isOnline()?Ct(this,hx).resumePausedMutations():Promise.resolve()}getQueryCache(){return Ct(this,No)}getMutationCache(){return Ct(this,hx)}getDefaultOptions(){return Ct(this,fx)}setDefaultOptions(t){Sn(this,fx,t)}setQueryDefaults(t,e){Ct(this,OS).set(Q_(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Ct(this,OS).values()],r={};return e.forEach(n=>{iN(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Ct(this,FS).set(Q_(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Ct(this,FS).values()],r={};return e.forEach(n=>{iN(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Ct(this,fx).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=oW(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===lW&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Ct(this,fx).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Ct(this,No).clear(),Ct(this,hx).clear()}},No=new WeakMap,hx=new WeakMap,fx=new WeakMap,OS=new WeakMap,FS=new WeakMap,mx=new WeakMap,BS=new WeakMap,$S=new WeakMap,jme),Vu,pi,xC,hu,k_,zS,px,gx,vC,US,VS,A_,N_,yx,qS,Ki,Uk,Q8,J8,eq,tq,rq,nq,sq,S0e,Eme,Bze=(Eme=class extends nj{constructor(e,r){super();os(this,Ki);os(this,Vu);os(this,pi);os(this,xC);os(this,hu);os(this,k_);os(this,zS);os(this,px);os(this,gx);os(this,vC);os(this,US);os(this,VS);os(this,A_);os(this,N_);os(this,yx);os(this,qS,new Set);this.options=r,Sn(this,Vu,e),Sn(this,gx,null),Sn(this,px,Z8()),this.options.experimental_prefetchInRender||Ct(this,px).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&&(Ct(this,pi).addObserver(this),Gne(Ct(this,pi),this.options)?Zs(this,Ki,Uk).call(this):this.updateResult(),Zs(this,Ki,tq).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return iq(Ct(this,pi),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return iq(Ct(this,pi),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Zs(this,Ki,rq).call(this),Zs(this,Ki,nq).call(this),Ct(this,pi).removeObserver(this)}setOptions(e){const r=this.options,n=Ct(this,pi);if(this.options=Ct(this,Vu).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof xh(this.options.enabled,Ct(this,pi))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Zs(this,Ki,sq).call(this),Ct(this,pi).setOptions(this.options),r._defaulted&&!rO(this.options,r)&&Ct(this,Vu).getQueryCache().notify({type:"observerOptionsUpdated",query:Ct(this,pi),observer:this});const i=this.hasListeners();i&&Hne(Ct(this,pi),n,this.options,r)&&Zs(this,Ki,Uk).call(this),this.updateResult(),i&&(Ct(this,pi)!==n||xh(this.options.enabled,Ct(this,pi))!==xh(r.enabled,Ct(this,pi))||Dx(this.options.staleTime,Ct(this,pi))!==Dx(r.staleTime,Ct(this,pi)))&&Zs(this,Ki,Q8).call(this);const o=Zs(this,Ki,J8).call(this);i&&(Ct(this,pi)!==n||xh(this.options.enabled,Ct(this,pi))!==xh(r.enabled,Ct(this,pi))||o!==Ct(this,yx))&&Zs(this,Ki,eq).call(this,o)}getOptimisticResult(e){const r=Ct(this,Vu).getQueryCache().build(Ct(this,Vu),e),n=this.createResult(r,e);return zze(this,n)&&(Sn(this,hu,n),Sn(this,zS,this.options),Sn(this,k_,Ct(this,pi).state)),n}getCurrentResult(){return Ct(this,hu)}trackResult(e,r){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),r==null||r(i),Reflect.get(n,i))})}trackProp(e){Ct(this,qS).add(e)}getCurrentQuery(){return Ct(this,pi)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Ct(this,Vu).defaultQueryOptions(e),n=Ct(this,Vu).getQueryCache().build(Ct(this,Vu),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(e){return Zs(this,Ki,Uk).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Ct(this,hu)))}createResult(e,r){var Q;const n=Ct(this,pi),i=this.options,o=Ct(this,hu),c=Ct(this,k_),a=Ct(this,zS),m=e!==n?e.state:Ct(this,xC),{state:y}=e;let v={...y},w=!1,j;if(r._optimisticResults){const ee=this.hasListeners(),oe=!ee&&Gne(e,r),de=ee&&Hne(e,n,r,i);(oe||de)&&(v={...v,..._0e(y.data,e.options)}),r._optimisticResults==="isRestoring"&&(v.fetchStatus="idle")}let{error:A,errorUpdatedAt:C,status:I}=v;j=v.data;let M=!1;if(r.placeholderData!==void 0&&j===void 0&&I==="pending"){let ee;o!=null&&o.isPlaceholderData&&r.placeholderData===(a==null?void 0:a.placeholderData)?(ee=o.data,M=!0):ee=typeof r.placeholderData=="function"?r.placeholderData((Q=Ct(this,VS))==null?void 0:Q.state.data,Ct(this,VS)):r.placeholderData,ee!==void 0&&(I="success",j=Y8(o==null?void 0:o.data,ee,r),w=!0)}if(r.select&&j!==void 0&&!M)if(o&&j===(c==null?void 0:c.data)&&r.select===Ct(this,vC))j=Ct(this,US);else try{Sn(this,vC,r.select),j=r.select(j),j=Y8(o==null?void 0:o.data,j,r),Sn(this,US,j),Sn(this,gx,null)}catch(ee){Sn(this,gx,ee)}Ct(this,gx)&&(A=Ct(this,gx),j=Ct(this,US),C=Date.now(),I="error");const D=v.fetchStatus==="fetching",F=I==="pending",z=I==="error",q=F&&D,H=j!==void 0,J={status:I,fetchStatus:v.fetchStatus,isPending:F,isSuccess:I==="success",isError:z,isInitialLoading:q,isLoading:q,data:j,dataUpdatedAt:v.dataUpdatedAt,error:A,errorUpdatedAt:C,failureCount:v.fetchFailureCount,failureReason:v.fetchFailureReason,errorUpdateCount:v.errorUpdateCount,isFetched:v.dataUpdateCount>0||v.errorUpdateCount>0,isFetchedAfterMount:v.dataUpdateCount>m.dataUpdateCount||v.errorUpdateCount>m.errorUpdateCount,isFetching:D,isRefetching:D&&!F,isLoadingError:z&&!H,isPaused:v.fetchStatus==="paused",isPlaceholderData:w,isRefetchError:z&&H,isStale:uW(e,r),refetch:this.refetch,promise:Ct(this,px),isEnabled:xh(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const ee=ye=>{J.status==="error"?ye.reject(J.error):J.data!==void 0&&ye.resolve(J.data)},oe=()=>{const ye=Sn(this,px,J.promise=Z8());ee(ye)},de=Ct(this,px);switch(de.status){case"pending":e.queryHash===n.queryHash&&ee(de);break;case"fulfilled":(J.status==="error"||J.data!==de.value)&&oe();break;case"rejected":(J.status!=="error"||J.error!==de.reason)&&oe();break}}return J}updateResult(){const e=Ct(this,hu),r=this.createResult(Ct(this,pi),this.options);if(Sn(this,k_,Ct(this,pi).state),Sn(this,zS,this.options),Ct(this,k_).data!==void 0&&Sn(this,VS,Ct(this,pi)),rO(r,e))return;Sn(this,hu,r);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Ct(this,qS).size)return!0;const c=new Set(o??Ct(this,qS));return this.options.throwOnError&&c.add("error"),Object.keys(Ct(this,hu)).some(a=>{const f=a;return Ct(this,hu)[f]!==e[f]&&c.has(f)})};Zs(this,Ki,S0e).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Zs(this,Ki,tq).call(this)}},Vu=new WeakMap,pi=new WeakMap,xC=new WeakMap,hu=new WeakMap,k_=new WeakMap,zS=new WeakMap,px=new WeakMap,gx=new WeakMap,vC=new WeakMap,US=new WeakMap,VS=new WeakMap,A_=new WeakMap,N_=new WeakMap,yx=new WeakMap,qS=new WeakMap,Ki=new WeakSet,Uk=function(e){Zs(this,Ki,sq).call(this);let r=Ct(this,pi).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(mu)),r},Q8=function(){Zs(this,Ki,rq).call(this);const e=Dx(this.options.staleTime,Ct(this,pi));if(X_||Ct(this,hu).isStale||!W8(e))return;const n=h0e(Ct(this,hu).dataUpdatedAt,e)+1;Sn(this,A_,setTimeout(()=>{Ct(this,hu).isStale||this.updateResult()},n))},J8=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Ct(this,pi)):this.options.refetchInterval)??!1},eq=function(e){Zs(this,Ki,nq).call(this),Sn(this,yx,e),!(X_||xh(this.options.enabled,Ct(this,pi))===!1||!W8(Ct(this,yx))||Ct(this,yx)===0)&&Sn(this,N_,setInterval(()=>{(this.options.refetchIntervalInBackground||cW.isFocused())&&Zs(this,Ki,Uk).call(this)},Ct(this,yx)))},tq=function(){Zs(this,Ki,Q8).call(this),Zs(this,Ki,eq).call(this,Zs(this,Ki,J8).call(this))},rq=function(){Ct(this,A_)&&(clearTimeout(Ct(this,A_)),Sn(this,A_,void 0))},nq=function(){Ct(this,N_)&&(clearInterval(Ct(this,N_)),Sn(this,N_,void 0))},sq=function(){const e=Ct(this,Vu).getQueryCache().build(Ct(this,Vu),this.options);if(e===Ct(this,pi))return;const r=Ct(this,pi);Sn(this,pi,e),Sn(this,xC,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},S0e=function(e){El.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(Ct(this,hu))}),Ct(this,Vu).getQueryCache().notify({query:Ct(this,pi),type:"observerResultsUpdated"})})},Eme);function $ze(t,e){return xh(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Gne(t,e){return $ze(t,e)||t.state.data!==void 0&&iq(t,e,e.refetchOnMount)}function iq(t,e,r){if(xh(e.enabled,t)!==!1&&Dx(e.staleTime,t)!=="static"){const n=typeof r=="function"?r(t):r;return n==="always"||n!==!1&&uW(t,e)}return!1}function Hne(t,e,r,n){return(t!==e||xh(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&uW(t,r)}function uW(t,e){return xh(e.enabled,t)!==!1&&t.isStaleByTime(Dx(e.staleTime,t))}function zze(t,e){return!rO(t.getCurrentResult(),e)}var xx,vx,qu,dg,jg,UM,aq,kme,Uze=(kme=class extends nj{constructor(r,n){super();os(this,jg);os(this,xx);os(this,vx);os(this,qu);os(this,dg);Sn(this,xx,r),this.setOptions(n),this.bindMethods(),Zs(this,jg,UM).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=Ct(this,xx).defaultMutationOptions(r),rO(this.options,n)||Ct(this,xx).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Ct(this,qu),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&Q_(n.mutationKey)!==Q_(this.options.mutationKey)?this.reset():((i=Ct(this,qu))==null?void 0:i.state.status)==="pending"&&Ct(this,qu).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Ct(this,qu))==null||r.removeObserver(this)}onMutationUpdate(r){Zs(this,jg,UM).call(this),Zs(this,jg,aq).call(this,r)}getCurrentResult(){return Ct(this,vx)}reset(){var r;(r=Ct(this,qu))==null||r.removeObserver(this),Sn(this,qu,void 0),Zs(this,jg,UM).call(this),Zs(this,jg,aq).call(this)}mutate(r,n){var i;return Sn(this,dg,n),(i=Ct(this,qu))==null||i.removeObserver(this),Sn(this,qu,Ct(this,xx).getMutationCache().build(Ct(this,xx),this.options)),Ct(this,qu).addObserver(this),Ct(this,qu).execute(r)}},xx=new WeakMap,vx=new WeakMap,qu=new WeakMap,dg=new WeakMap,jg=new WeakSet,UM=function(){var n;const r=((n=Ct(this,qu))==null?void 0:n.state)??b0e();Sn(this,vx,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},aq=function(r){El.batch(()=>{var n,i,o,c,a,f,m,y;if(Ct(this,dg)&&this.hasListeners()){const v=Ct(this,vx).variables,w=Ct(this,vx).context;(r==null?void 0:r.type)==="success"?((i=(n=Ct(this,dg)).onSuccess)==null||i.call(n,r.data,v,w),(c=(o=Ct(this,dg)).onSettled)==null||c.call(o,r.data,null,v,w)):(r==null?void 0:r.type)==="error"&&((f=(a=Ct(this,dg)).onError)==null||f.call(a,r.error,v,w),(y=(m=Ct(this,dg)).onSettled)==null||y.call(m,void 0,r.error,v,w))}this.listeners.forEach(v=>{v(Ct(this,vx))})})},kme),T0e=N.createContext(void 0),kr=t=>{const e=N.useContext(T0e);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Vze=({client:t,children:e})=>(N.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),s.jsx(T0e.Provider,{value:t,children:e})),j0e=N.createContext(!1),qze=()=>N.useContext(j0e);j0e.Provider;function Gze(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Hze=N.createContext(Gze()),Wze=()=>N.useContext(Hze),Kze=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},Yze=t=>{N.useEffect(()=>{t.clearReset()},[t])},Zze=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||p0e(r,[t.error,n])),Xze=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))}},Qze=(t,e)=>t.isLoading&&t.isFetching&&!e,Jze=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Wne=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function e6e(t,e,r){var v,w,j,A,C;const n=qze(),i=Wze(),o=kr(),c=o.defaultQueryOptions(t);(w=(v=o.getDefaultOptions().queries)==null?void 0:v._experimental_beforeQuery)==null||w.call(v,c),c._optimisticResults=n?"isRestoring":"optimistic",Xze(c),Kze(c,i),Yze(i);const a=!o.getQueryCache().get(c.queryHash),[f]=N.useState(()=>new e(o,c)),m=f.getOptimisticResult(c),y=!n&&t.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(I=>{const M=y?f.subscribe(El.batchCalls(I)):mu;return f.updateResult(),M},[f,y]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),N.useEffect(()=>{f.setOptions(c)},[c,f]),Jze(c,m))throw Wne(c,f,i);if(Zze({result:m,errorResetBoundary:i,throwOnError:c.throwOnError,query:o.getQueryCache().get(c.queryHash),suspense:c.suspense}))throw m.error;if((A=(j=o.getDefaultOptions().queries)==null?void 0:j._experimental_afterQuery)==null||A.call(j,c,m),c.experimental_prefetchInRender&&!X_&&Qze(m,n)){const I=a?Wne(c,f,i):(C=o.getQueryCache().get(c.queryHash))==null?void 0:C.promise;I==null||I.catch(mu).finally(()=>{f.updateResult()})}return c.notifyOnChangeProps?m:f.trackResult(m)}function mr(t,e){return e6e(t,Bze)}function Ar(t,e){const r=kr(),[n]=N.useState(()=>new Uze(r,t));N.useEffect(()=>{n.setOptions(t)},[n,t]);const i=N.useSyncExternalStore(N.useCallback(c=>n.subscribe(El.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),o=N.useCallback((c,a)=>{n.mutate(c,a).catch(mu)},[n]);if(i.error&&p0e(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 aN(){return aN=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function E0e(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function r6e(){return Math.random().toString(36).substr(2,8)}function Yne(t,e){return{usr:t.state,key:t.key,idx:e}}function oq(t,e,r,n){return r===void 0&&(r=null),aN({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?sj(e):e,{state:r,key:e&&e.key||n||r6e()})}function sO(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 sj(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 n6e(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,c=i.history,a=wx.Pop,f=null,m=y();m==null&&(m=0,c.replaceState(aN({},c.state,{idx:m}),""));function y(){return(c.state||{idx:null}).idx}function v(){a=wx.Pop;let I=y(),M=I==null?null:I-m;m=I,f&&f({action:a,location:C.location,delta:M})}function w(I,M){a=wx.Push;let D=oq(C.location,I,M);m=y()+1;let F=Yne(D,m),z=C.createHref(D);try{c.pushState(F,"",z)}catch(q){if(q instanceof DOMException&&q.name==="DataCloneError")throw q;i.location.assign(z)}o&&f&&f({action:a,location:C.location,delta:1})}function j(I,M){a=wx.Replace;let D=oq(C.location,I,M);m=y();let F=Yne(D,m),z=C.createHref(D);c.replaceState(F,"",z),o&&f&&f({action:a,location:C.location,delta:0})}function A(I){let M=i.location.origin!=="null"?i.location.origin:i.location.href,D=typeof I=="string"?I:sO(I);return D=D.replace(/ $/,"%20"),vo(M,"No window.location.(origin|href) available to create URL for href: "+D),new URL(D,M)}let C={get action(){return a},get location(){return t(i,c)},listen(I){if(f)throw new Error("A history only accepts one active listener");return i.addEventListener(Kne,v),f=I,()=>{i.removeEventListener(Kne,v),f=null}},createHref(I){return e(i,I)},createURL:A,encodeLocation(I){let M=A(I);return{pathname:M.pathname,search:M.search,hash:M.hash}},push:w,replace:j,go(I){return c.go(I)}};return C}var Zne;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(Zne||(Zne={}));function s6e(t,e,r){return r===void 0&&(r="/"),i6e(t,e,r,!1)}function i6e(t,e,r,n){let i=typeof e=="string"?sj(e):e,o=rT(i.pathname||"/",r);if(o==null)return null;let c=k0e(t);a6e(c);let a=null;for(let f=0;a==null&&f{let f={relativePath:a===void 0?o.path||"":a,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};f.relativePath.startsWith("/")&&(vo(f.relativePath.startsWith(n),'Absolute route path "'+f.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),f.relativePath=f.relativePath.slice(n.length));let m=Ox([n,f.relativePath]),y=r.concat(f);o.children&&o.children.length>0&&(vo(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+m+'".')),k0e(o.children,e,y,m)),!(o.path==null&&!o.index)&&e.push({path:m,score:f6e(m,o.index),routesMeta:y})};return t.forEach((o,c)=>{var a;if(o.path===""||!((a=o.path)!=null&&a.includes("?")))i(o,c);else for(let f of A0e(o.path))i(o,c,f)}),e}function A0e(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=A0e(n.join("/")),a=[];return a.push(...c.map(f=>f===""?o:[o,f].join("/"))),i&&a.push(...c),a.map(f=>t.startsWith("/")&&f===""?"/":f)}function a6e(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:m6e(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const o6e=/^:[\w-]+$/,l6e=3,c6e=2,u6e=1,d6e=10,h6e=-2,Xne=t=>t==="*";function f6e(t,e){let r=t.split("/"),n=r.length;return r.some(Xne)&&(n+=h6e),e&&(n+=c6e),r.filter(i=>!Xne(i)).reduce((i,o)=>i+(o6e.test(o)?l6e:o===""?u6e:d6e),n)}function m6e(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 p6e(t,e,r){let{routesMeta:n}=t,i={},o="/",c=[];for(let a=0;a{let{paramName:w,isOptional:j}=y;if(w==="*"){let C=a[v]||"";c=o.slice(0,o.length-C.length).replace(/(.)\/+$/,"$1")}const A=a[v];return j&&!A?m[w]=void 0:m[w]=(A||"").replace(/%2F/g,"/"),m},{}),pathname:o,pathnameBase:c,pattern:t}}function g6e(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),E0e(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,a,f)=>(n.push({paramName:a,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 y6e(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return E0e(!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 rT(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 x6e(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?sj(t):t;return{pathname:r?r.startsWith("/")?r:v6e(r,e):e,search:w6e(n),hash:S6e(i)}}function v6e(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 o6(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 _6e(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function dW(t,e){let r=_6e(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function hW(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=sj(t):(i=aN({},t),vo(!i.pathname||!i.pathname.includes("?"),o6("?","pathname","search",i)),vo(!i.pathname||!i.pathname.includes("#"),o6("#","pathname","hash",i)),vo(!i.search||!i.search.includes("#"),o6("#","search","hash",i)));let o=t===""||i.pathname==="",c=o?"/":i.pathname,a;if(c==null)a=r;else{let v=e.length-1;if(!n&&c.startsWith("..")){let w=c.split("/");for(;w[0]==="..";)w.shift(),v-=1;i.pathname=w.join("/")}a=v>=0?e[v]:"/"}let f=x6e(i,a),m=c&&c!=="/"&&c.endsWith("/"),y=(o||c===".")&&r.endsWith("/");return!f.pathname.endsWith("/")&&(m||y)&&(f.pathname+="/"),f}const Ox=t=>t.join("/").replace(/\/\/+/g,"/"),b6e=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),w6e=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,S6e=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function T6e(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const N0e=["post","put","patch","delete"];new Set(N0e);const j6e=["get",...N0e];new Set(j6e);/** * 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 oN(){return oN=Object.assign?Object.assign.bind():function(t){for(var e=1;e{a.current=!0}),N.useCallback(function(m,y){if(y===void 0&&(y={}),!a.current)return;if(typeof m=="number"){n.go(m);return}let v=hW(m,JSON.parse(c),o,y.relative==="path");t==null&&e!=="/"&&(v.pathname=v.pathname==="/"?e:Ox([e,v.pathname])),(y.replace?n.replace:n.push)(v,y.state,y)},[e,n,c,o,t])}const A6e=N.createContext(null);function N6e(t){let e=N.useContext(up).outlet;return e&&N.createElement(A6e.Provider,{value:t},e)}function id(){let{matches:t}=N.useContext(up),e=t[t.length-1];return e?e.params:{}}function U3(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=N.useContext(Vg),{matches:i}=N.useContext(up),{pathname:o}=xs(),c=JSON.stringify(dW(i,n.v7_relativeSplatPath));return N.useMemo(()=>hW(t,JSON.parse(c),o,r==="path"),[t,c,o,r])}function C6e(t,e){return I6e(t,e)}function I6e(t,e,r,n){ij()||vo(!1);let{navigator:i}=N.useContext(Vg),{matches:o}=N.useContext(up),c=o[o.length-1],a=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let m=xs(),y;if(e){var v;let I=typeof e=="string"?sj(e):e;f==="/"||(v=I.pathname)!=null&&v.startsWith(f)||vo(!1),y=I}else y=m;let w=y.pathname||"/",j=w;if(f!=="/"){let I=f.replace(/^\//,"").split("/");j="/"+w.replace(/^\//,"").split("/").slice(I.length).join("/")}let A=s6e(t,{pathname:j}),C=D6e(A&&A.map(I=>Object.assign({},I,{params:Object.assign({},a,I.params),pathname:Ox([f,i.encodeLocation?i.encodeLocation(I.pathname).pathname:I.pathname]),pathnameBase:I.pathnameBase==="/"?f:Ox([f,i.encodeLocation?i.encodeLocation(I.pathnameBase).pathname:I.pathnameBase])})),o,r,n);return e&&C?N.createElement(z3.Provider,{value:{location:oN({pathname:"/",search:"",hash:"",state:null,key:"default"},y),navigationType:wx.Pop}},C):C}function P6e(){let t=$6e(),e=T6e(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},e),r?N.createElement("pre",{style:i},r):null,null)}const R6e=N.createElement(P6e,null);class L6e extends N.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,r){return r.location!==e.location||r.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:r.error,location:r.location,revalidation:e.revalidation||r.revalidation}}componentDidCatch(e,r){console.error("React Router caught the following error during render",e,r)}render(){return this.state.error!==void 0?N.createElement(up.Provider,{value:this.props.routeContext},N.createElement(I0e.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function M6e(t){let{routeContext:e,match:r,children:n}=t,i=N.useContext($3);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),N.createElement(up.Provider,{value:e},n)}function D6e(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,a=(i=r)==null?void 0:i.errors;if(a!=null){let y=c.findIndex(v=>v.route.id&&(a==null?void 0:a[v.route.id])!==void 0);y>=0||vo(!1),c=c.slice(0,Math.min(c.length,y+1))}let f=!1,m=-1;if(r&&n&&n.v7_partialHydration)for(let y=0;y=0?c=c.slice(0,m+1):c=[c[0]];break}}}return c.reduceRight((y,v,w)=>{let j,A=!1,C=null,I=null;r&&(j=a&&v.route.id?a[v.route.id]:void 0,C=v.route.errorElement||R6e,f&&(m<0&&w===0?(A=!0,I=null):m===w&&(A=!0,I=v.route.hydrateFallbackElement||null)));let M=e.concat(c.slice(0,w+1)),D=()=>{let F;return j?F=C:A?F=I:v.route.Component?F=N.createElement(v.route.Component,null):v.route.element?F=v.route.element:F=y,N.createElement(M6e,{match:v,routeContext:{outlet:y,matches:M,isDataRoute:r!=null},children:F})};return r&&(v.route.ErrorBoundary||v.route.errorElement||w===0)?N.createElement(L6e,{location:r.location,revalidation:r.revalidation,component:C,error:j,children:D(),routeContext:{outlet:null,matches:M,isDataRoute:!0}}):D()},null)}var R0e=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(R0e||{}),aO=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}(aO||{});function O6e(t){let e=N.useContext($3);return e||vo(!1),e}function F6e(t){let e=N.useContext(C0e);return e||vo(!1),e}function B6e(t){let e=N.useContext(up);return e||vo(!1),e}function L0e(t){let e=B6e(),r=e.matches[e.matches.length-1];return r.route.id||vo(!1),r.route.id}function $6e(){var t;let e=N.useContext(I0e),r=F6e(aO.UseRouteError),n=L0e(aO.UseRouteError);return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function z6e(){let{router:t}=O6e(R0e.UseNavigateStable),e=L0e(aO.UseNavigateStable),r=N.useRef(!1);return P0e(()=>{r.current=!0}),N.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,oN({fromRouteId:e},o)))},[t,e])}function U6e(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function ls(t){let{to:e,replace:r,state:n,relative:i}=t;ij()||vo(!1);let{future:o,static:c}=N.useContext(Vg),{matches:a}=N.useContext(up),{pathname:f}=xs(),m=Bi(),y=hW(e,dW(a,o.v7_relativeSplatPath),f,i==="path"),v=JSON.stringify(y);return N.useEffect(()=>m(JSON.parse(v),{replace:r,state:n,relative:i}),[m,v,i,r,n]),null}function MJt(t){return N6e(t.context)}function ge(t){vo(!1)}function V6e(t){let{basename:e="/",children:r=null,location:n,navigationType:i=wx.Pop,navigator:o,static:c=!1,future:a}=t;ij()&&vo(!1);let f=e.replace(/^\/*/,"/"),m=N.useMemo(()=>({basename:f,navigator:o,static:c,future:oN({v7_relativeSplatPath:!1},a)}),[f,a,o,c]);typeof n=="string"&&(n=sj(n));let{pathname:y="/",search:v="",hash:w="",state:j=null,key:A="default"}=n,C=N.useMemo(()=>{let I=rT(y,f);return I==null?null:{location:{pathname:I,search:v,hash:w,state:j,key:A},navigationType:i}},[f,y,v,w,j,A,i]);return C==null?null:N.createElement(Vg.Provider,{value:m},N.createElement(z3.Provider,{children:r,value:C}))}function Pm(t){let{children:e,location:r}=t;return C6e(lq(e),r)}new Promise(()=>{});function lq(t,e){e===void 0&&(e=[]);let r=[];return N.Children.forEach(t,(n,i)=>{if(!N.isValidElement(n))return;let o=[...e,i];if(n.type===N.Fragment){r.push.apply(r,lq(n.props.children,o));return}n.type!==ge&&vo(!1),!n.props.index||!n.props.children||vo(!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=lq(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 oO(){return oO=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function q6e(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function G6e(t,e){return t.button===0&&(!e||e==="_self")&&!q6e(t)}function cq(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 H6e(t,e){let r=cq(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(o=>{r.append(i,o)})}),r}const W6e=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],K6e=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],Y6e="6";try{window.__reactRouterVersion=Y6e}catch{}const Z6e=N.createContext({isTransitioning:!1}),X6e="startTransition",Qne=R7[X6e];function Q6e(t){let{basename:e,children:r,future:n,window:i}=t,o=N.useRef();o.current==null&&(o.current=t6e({window:i,v5Compat:!0}));let c=o.current,[a,f]=N.useState({action:c.action,location:c.location}),{v7_startTransition:m}=n||{},y=N.useCallback(v=>{m&&Qne?Qne(()=>f(v)):f(v)},[f,m]);return N.useLayoutEffect(()=>c.listen(y),[c,y]),N.useEffect(()=>U6e(n),[n]),N.createElement(V6e,{basename:e,children:r,location:a.location,navigationType:a.action,navigator:c,future:n})}const J6e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",eUe=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,xr=N.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:o,replace:c,state:a,target:f,to:m,preventScrollReset:y,viewTransition:v}=e,w=M0e(e,W6e),{basename:j}=N.useContext(Vg),A,C=!1;if(typeof m=="string"&&eUe.test(m)&&(A=m,J6e))try{let F=new URL(window.location.href),z=m.startsWith("//")?new URL(F.protocol+m):new URL(m),q=rT(z.pathname,j);z.origin===F.origin&&q!=null?m=q+z.search+z.hash:C=!0}catch{}let I=E6e(m,{relative:i}),M=nUe(m,{replace:c,state:a,target:f,preventScrollReset:y,relative:i,viewTransition:v});function D(F){n&&n(F),F.defaultPrevented||M(F)}return N.createElement("a",oO({},w,{href:A||I,onClick:C||o?n:D,ref:r,target:f}))}),tUe=N.forwardRef(function(e,r){let{"aria-current":n="page",caseSensitive:i=!1,className:o="",end:c=!1,style:a,to:f,viewTransition:m,children:y}=e,v=M0e(e,K6e),w=U3(f,{relative:v.relative}),j=xs(),A=N.useContext(C0e),{navigator:C,basename:I}=N.useContext(Vg),M=A!=null&&sUe(w)&&m===!0,D=C.encodeLocation?C.encodeLocation(w).pathname:w.pathname,F=j.pathname,z=A&&A.navigation&&A.navigation.location?A.navigation.location.pathname:null;i||(F=F.toLowerCase(),z=z?z.toLowerCase():null,D=D.toLowerCase()),z&&I&&(z=rT(z,I)||z);const q=D!=="/"&&D.endsWith("/")?D.length-1:D.length;let H=F===D||!c&&F.startsWith(D)&&F.charAt(q)==="/",K=z!=null&&(z===D||!c&&z.startsWith(D)&&z.charAt(D.length)==="/"),J={isActive:H,isPending:K,isTransitioning:M},Q=H?n:void 0,ee;typeof o=="function"?ee=o(J):ee=[o,H?"active":null,K?"pending":null,M?"transitioning":null].filter(Boolean).join(" ");let oe=typeof a=="function"?a(J):a;return N.createElement(xr,oO({},v,{"aria-current":Q,className:ee,ref:r,style:oe,to:f,viewTransition:m}),typeof y=="function"?y(J):y)});var uq;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(uq||(uq={}));var Jne;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Jne||(Jne={}));function rUe(t){let e=N.useContext($3);return e||vo(!1),e}function nUe(t,e){let{target:r,replace:n,state:i,preventScrollReset:o,relative:c,viewTransition:a}=e===void 0?{}:e,f=Bi(),m=xs(),y=U3(t,{relative:c});return N.useCallback(v=>{if(G6e(v,r)){v.preventDefault();let w=n!==void 0?n:sO(m)===sO(y);f(t,{replace:w,state:i,preventScrollReset:o,relative:c,viewTransition:a})}},[m,f,y,n,i,r,t,o,c,a])}function y0(t){let e=N.useRef(cq(t)),r=N.useRef(!1),n=xs(),i=N.useMemo(()=>H6e(n.search,r.current?null:e.current),[n.search]),o=Bi(),c=N.useCallback((a,f)=>{const m=cq(typeof a=="function"?a(i):a);r.current=!0,o("?"+m,f)},[o,i]);return[i,c]}function sUe(t,e){e===void 0&&(e={});let r=N.useContext(Z6e);r==null&&vo(!1);let{basename:n}=rUe(uq.useViewTransitionState),i=U3(t,{relative:e.relative});if(!r.isTransitioning)return!1;let o=rT(r.currentLocation.pathname,n)||r.currentLocation.pathname,c=rT(r.nextLocation.pathname,n)||r.nextLocation.pathname;return iO(i.pathname,c)!=null||iO(i.pathname,o)!=null}var iUe=typeof Element<"u",aUe=typeof Map=="function",oUe=typeof Set=="function",lUe=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function VM(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(!VM(t[n],e[n]))return!1;return!0}var o;if(aUe&&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(!VM(n.value[1],e.get(n.value[0])))return!1;return!0}if(oUe&&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(lUe&&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(iUe&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!VM(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var cUe=function(e,r){try{return VM(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 uUe=wi(cUe);var dUe=function(t,e,r,n,i,o,c,a){if(!t){var f;if(e===void 0)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var m=[r,n,i,o,c,a],y=0;f=new Error(e.replace(/%s/g,function(){return m[y++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}},hUe=dUe;const ese=wi(hUe);var fUe=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),a=Object.keys(r);if(c.length!==a.length)return!1;for(var f=Object.prototype.hasOwnProperty.bind(r),m=0;m(t.BASE="base",t.BODY="body",t.HEAD="head",t.HTML="html",t.LINK="link",t.META="meta",t.NOSCRIPT="noscript",t.SCRIPT="script",t.STYLE="style",t.TITLE="title",t.FRAGMENT="Symbol(react.fragment)",t))(D0e||{}),l6={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"]}},tse=Object.values(D0e),fW={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},pUe=Object.entries(fW).reduce((t,[e,r])=>(t[r]=e,t),{}),Nf="data-rh",vS={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},_S=(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},gUe=t=>{let e=_S(t,"title");const r=_S(t,vS.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=_S(t,vS.DEFAULT_TITLE);return e||n||void 0},yUe=t=>_S(t,vS.ON_CHANGE_CLIENT_STATE)||(()=>{}),c6=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),xUe=(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),ik=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&vUe(`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 m;const y=Object.keys(f);for(let w=0;wi.push(f));const a=Object.keys(c);for(let f=0;f{if(Array.isArray(t)&&t.length){for(let r=0;r({baseTag:xUe(["href"],t),bodyAttributes:c6("bodyAttributes",t),defer:_S(t,vS.DEFER),encode:_S(t,vS.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:c6("htmlAttributes",t),linkTags:ik("link",["rel","href"],t),metaTags:ik("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:ik("noscript",["innerHTML"],t),onChangeClientState:yUe(t),scriptTags:ik("script",["src","innerHTML"],t),styleTags:ik("style",["cssText"],t),title:gUe(t),titleAttributes:c6("titleAttributes",t),prioritizeSeoTags:_Ue(t,vS.PRIORITIZE_SEO_TAGS)}),O0e=t=>Array.isArray(t)?t.join(""):t,wUe=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(wUe(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},rse=(t,e)=>({...t,[e]:void 0}),SUe=["noscript","script","style"],dq=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),F0e=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),TUe=(t,e,r,n)=>{const i=F0e(r),o=O0e(e);return i?`<${t} ${Nf}="true" ${i}>${dq(o,n)}`:`<${t} ${Nf}="true">${dq(o,n)}`},jUe=(t,e,r=!0)=>e.reduce((n,i)=>{const o=i,c=Object.keys(o).filter(m=>!(m==="innerHTML"||m==="cssText")).reduce((m,y)=>{const v=typeof o[y]>"u"?y:`${y}="${dq(o[y],r)}"`;return m?`${m} ${v}`:v},""),a=o.innerHTML||o.cssText||"",f=SUe.indexOf(t)===-1;return`${n}<${t} ${Nf}="true" ${c}${f?"/>":`>${a}`}`},""),B0e=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=fW[n];return r[i||n]=t[n],r},e),EUe=(t,e,r)=>{const n={key:e,[Nf]:!0},i=B0e(r,n);return[Qe.createElement("title",i,e)]},qM=(t,e)=>e.map((r,n)=>{const i={key:n,[Nf]:!0};return Object.keys(r).forEach(o=>{const a=fW[o]||o;if(a==="innerHTML"||a==="cssText"){const f=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:f}}else i[a]=r[o]}),Qe.createElement(t,i)}),gh=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>EUe(t,e.title,e.titleAttributes),toString:()=>TUe(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>B0e(e),toString:()=>F0e(e)};default:return{toComponent:()=>qM(t,e),toString:()=>jUe(t,e,r)}}},kUe=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=u6(t,l6.meta),o=u6(e,l6.link),c=u6(r,l6.script);return{priorityMethods:{toComponent:()=>[...qM("meta",i.priority),...qM("link",o.priority),...qM("script",c.priority)],toString:()=>`${gh("meta",i.priority,n)} ${gh("link",o.priority,n)} ${gh("script",c.priority,n)}`},metaTags:i.default,linkTags:o.default,scriptTags:c.default}},AUe=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:o,styleTags:c,title:a="",titleAttributes:f,prioritizeSeoTags:m}=t;let{linkTags:y,metaTags:v,scriptTags:w}=t,j={toComponent:()=>{},toString:()=>""};return m&&({priorityMethods:j,linkTags:y,metaTags:v,scriptTags:w}=kUe(t)),{priority:j,base:gh("base",e,n),bodyAttributes:gh("bodyAttributes",r,n),htmlAttributes:gh("htmlAttributes",i,n),link:gh("link",y,n),meta:gh("meta",v,n),noscript:gh("noscript",o,n),script:gh("script",w,n),style:gh("style",c,n),title:gh("title",{title:a,titleAttributes:f},n)}},hq=AUe,yL=[],$0e=!!(typeof window<"u"&&window.document&&window.document.createElement),fq=class{constructor(t,e){Vr(this,"instances",[]);Vr(this,"canUseDOM",$0e);Vr(this,"context");Vr(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?yL:this.instances,add:t=>{(this.canUseDOM?yL:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?yL:this.instances).indexOf(t);(this.canUseDOM?yL:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=hq({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},NUe={},z0e=Qe.createContext(NUe),C_,U0e=(C_=class extends N.Component{constructor(r){super(r);Vr(this,"helmetData");this.helmetData=new fq(this.props.context||{},C_.canUseDOM)}render(){return Qe.createElement(z0e.Provider,{value:this.helmetData.value},this.props.children)}},Vr(C_,"canUseDOM",$0e),C_),i1=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${Nf}]`),i=[].slice.call(n),o=[];let c;return e&&e.length&&e.forEach(a=>{const f=document.createElement(t);for(const m in a)if(Object.prototype.hasOwnProperty.call(a,m))if(m==="innerHTML")f.innerHTML=a.innerHTML;else if(m==="cssText")f.styleSheet?f.styleSheet.cssText=a.cssText:f.appendChild(document.createTextNode(a.cssText));else{const y=m,v=typeof a[y]>"u"?"":a[y];f.setAttribute(m,v)}f.setAttribute(Nf,"true"),i.some((m,y)=>(c=y,f.isEqualNode(m)))?i.splice(c,1):o.push(f)}),i.forEach(a=>{var f;return(f=a.parentNode)==null?void 0:f.removeChild(a)}),o.forEach(a=>r.appendChild(a)),{oldTags:i,newTags:o}},mq=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(Nf),i=n?n.split(","):[],o=[...i],c=Object.keys(e);for(const a of c){const f=e[a]||"";r.getAttribute(a)!==f&&r.setAttribute(a,f),i.indexOf(a)===-1&&i.push(a);const m=o.indexOf(a);m!==-1&&o.splice(m,1)}for(let a=o.length-1;a>=0;a-=1)r.removeAttribute(o[a]);i.length===o.length?r.removeAttribute(Nf):r.getAttribute(Nf)!==c.join(",")&&r.setAttribute(Nf,c.join(","))},CUe=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=O0e(t)),mq("title",e)},nse=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:o,metaTags:c,noscriptTags:a,onChangeClientState:f,scriptTags:m,styleTags:y,title:v,titleAttributes:w}=t;mq("body",n),mq("html",i),CUe(v,w);const j={baseTag:i1("base",r),linkTags:i1("link",o),metaTags:i1("meta",c),noscriptTags:i1("noscript",a),scriptTags:i1("script",m),styleTags:i1("style",y)},A={},C={};Object.keys(j).forEach(I=>{const{newTags:M,oldTags:D}=j[I];M.length&&(A[I]=M),D.length&&(C[I]=j[I].oldTags)}),e&&e(),f(t,A,C)},ak=null,IUe=t=>{ak&&cancelAnimationFrame(ak),t.defer?ak=requestAnimationFrame(()=>{nse(t,()=>{ak=null})}):(nse(t),ak=null)},PUe=IUe,sse=class extends N.Component{constructor(){super(...arguments);Vr(this,"rendered",!1)}shouldComponentUpdate(e){return!mUe(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=bUe(e.get().map(o=>{const c={...o.props};return delete c.context,c}));U0e.canUseDOM?PUe(i):hq&&(n=hq(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}},IV,no=(IV=class extends N.Component{shouldComponentUpdate(t){return!uUe(rse(this.props,"helmetData"),rse(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 ese(tse.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 ${tse.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),ese(!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 Qe.Children.forEach(t,n=>{if(!n||!n.props)return;const{children:i,...o}=n.props,c=Object.keys(o).reduce((f,m)=>(f[pUe[m]||m]=o[m],f),{});let{type:a}=n;switch(typeof a=="symbol"?a=a.toString():this.warnOnInvalidChildren(n,i),a){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 fq)){const i=n;n=new fq(i.context,!0),delete r.helmetData}return n?Qe.createElement(sse,{...r,context:n.value}):Qe.createElement(z0e.Consumer,null,i=>Qe.createElement(sse,{...r,context:i}))}},Vr(IV,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),IV);const RUe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Oe(async()=>{const{default:n}=await Promise.resolve().then(()=>aj);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class mW extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class LUe extends mW{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class MUe extends mW{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class DUe extends mW{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var pq;(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"})(pq||(pq={}));var OUe=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};class FUe{constructor(e,{headers:r={},customFetch:n,region:i=pq.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=RUe(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return OUe(this,void 0,void 0,function*(){try{const{headers:i,method:o,body:c}=r;let a={},{region:f}=r;f||(f=this.region),f&&f!=="any"&&(a["x-region"]=f);let m;c&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(a["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(a["Content-Type"]="application/json",m=JSON.stringify(c)));const y=yield this.fetch(`${this.url}/${e}`,{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:m}).catch(A=>{throw new LUe(A)}),v=y.headers.get("x-relay-error");if(v&&v==="true")throw new MUe(y);if(!y.ok)throw new DUe(y);let w=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),j;return w==="application/json"?j=yield y.json():w==="application/octet-stream"?j=yield y.blob():w==="text/event-stream"?j=y:w==="multipart/form-data"?j=yield y.formData():j=yield y.text(),{data:j,error:null}}catch(i){return{data:null,error:i}}})}}var Ku={},pW={},V3={},$C={},q3={},G3={},BUe=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")},nT=BUe();const $Ue=nT.fetch,V0e=nT.fetch.bind(nT),q0e=nT.Headers,zUe=nT.Request,UUe=nT.Response,aj=Object.freeze(Object.defineProperty({__proto__:null,Headers:q0e,Request:zUe,Response:UUe,default:V0e,fetch:$Ue},Symbol.toStringTag,{value:"Module"})),VUe=tDe(aj);var H3={};Object.defineProperty(H3,"__esModule",{value:!0});let qUe=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};H3.default=qUe;var G0e=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(G3,"__esModule",{value:!0});const GUe=G0e(VUe),HUe=G0e(H3);let WUe=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=GUe.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,a,f;let m=null,y=null,v=null,w=o.status,j=o.statusText;if(o.ok){if(this.method!=="HEAD"){const M=await o.text();M===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?y=M:y=JSON.parse(M))}const C=(c=this.headers.Prefer)===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),I=(a=o.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");C&&I&&I.length>1&&(v=parseInt(I[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(y)&&(y.length>1?(m={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,v=null,w=406,j="Not Acceptable"):y.length===1?y=y[0]:y=null)}else{const C=await o.text();try{m=JSON.parse(C),Array.isArray(m)&&o.status===404&&(y=[],m=null,w=200,j="OK")}catch{o.status===404&&C===""?(w=204,j="No Content"):m={message:C}}if(m&&this.isMaybeSingle&&(!((f=m==null?void 0:m.details)===null||f===void 0)&&f.includes("0 rows"))&&(m=null,w=200,j="OK"),m&&this.shouldThrowOnError)throw new HUe.default(m)}return{error:m,data:y,count:v,status:w,statusText:j}});return this.shouldThrowOnError||(i=i.catch(o=>{var c,a,f;return{error:{message:`${(c=o==null?void 0:o.name)!==null&&c!==void 0?c:"FetchError"}: ${o==null?void 0:o.message}`,details:`${(a=o==null?void 0:o.stack)!==null&&a!==void 0?a:""}`,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}};G3.default=WUe;var KUe=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(q3,"__esModule",{value:!0});const YUe=KUe(G3);let ZUe=class extends YUe.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",a=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${a?`${a},`:""}${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 a;const f=[e?"analyze":null,r?"verbose":null,n?"settings":null,i?"buffers":null,o?"wal":null].filter(Boolean).join("|"),m=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${m}"; options=${f};`,c==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};q3.default=ZUe;var XUe=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($C,"__esModule",{value:!0});const QUe=XUe(q3);let JUe=class extends QUe.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}};$C.default=JUe;var eVe=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(V3,"__esModule",{value:!0});const ok=eVe($C);let tVe=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(a=>/\s/.test(a)&&!o?"":(a==='"'&&(o=!o),a)).join("");return this.url.searchParams.set("select",c),n&&(this.headers.Prefer=`count=${n}`),new ok.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((a,f)=>a.concat(Object.keys(f)),[]);if(c.length>0){const a=[...new Set(c)].map(f=>`"${f}"`);this.url.searchParams.set("columns",a.join(","))}}return new ok.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",a=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),o||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){const f=e.reduce((m,y)=>m.concat(Object.keys(y)),[]);if(f.length>0){const m=[...new Set(f)].map(y=>`"${y}"`);this.url.searchParams.set("columns",m.join(","))}}return new ok.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 ok.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 ok.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};V3.default=tVe;var W3={},K3={};Object.defineProperty(K3,"__esModule",{value:!0});K3.version=void 0;K3.version="0.0.0-automated";Object.defineProperty(W3,"__esModule",{value:!0});W3.DEFAULT_HEADERS=void 0;const rVe=K3;W3.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${rVe.version}`};var H0e=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pW,"__esModule",{value:!0});const nVe=H0e(V3),sVe=H0e($C),iVe=W3;let aVe=class W0e{constructor(e,{headers:r={},schema:n,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},iVe.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=i}from(e){const r=new URL(`${this.url}/${e}`);return new nVe.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new W0e(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:i=!1,count:o}={}){let c;const a=new URL(`${this.url}/rpc/${e}`);let f;n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([y,v])=>v!==void 0).map(([y,v])=>[y,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([y,v])=>{a.searchParams.append(y,v)})):(c="POST",f=r);const m=Object.assign({},this.headers);return o&&(m.Prefer=`count=${o}`),new sVe.default({method:c,url:a,headers:m,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}};pW.default=aVe;var oj=fc&&fc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ku,"__esModule",{value:!0});Ku.PostgrestError=Ku.PostgrestBuilder=Ku.PostgrestTransformBuilder=Ku.PostgrestFilterBuilder=Ku.PostgrestQueryBuilder=Ku.PostgrestClient=void 0;const K0e=oj(pW);Ku.PostgrestClient=K0e.default;const Y0e=oj(V3);Ku.PostgrestQueryBuilder=Y0e.default;const Z0e=oj($C);Ku.PostgrestFilterBuilder=Z0e.default;const X0e=oj(q3);Ku.PostgrestTransformBuilder=X0e.default;const Q0e=oj(G3);Ku.PostgrestBuilder=Q0e.default;const J0e=oj(H3);Ku.PostgrestError=J0e.default;var oVe=Ku.default={PostgrestClient:K0e.default,PostgrestQueryBuilder:Y0e.default,PostgrestFilterBuilder:Z0e.default,PostgrestTransformBuilder:X0e.default,PostgrestBuilder:Q0e.default,PostgrestError:J0e.default};const{PostgrestClient:lVe,PostgrestQueryBuilder:zJt,PostgrestFilterBuilder:UJt,PostgrestTransformBuilder:VJt,PostgrestBuilder:qJt,PostgrestError:GJt}=oVe;let gq;typeof window>"u"?gq=require("ws"):gq=window.WebSocket;const cVe=gq,uVe="2.11.10",dVe={"X-Client-Info":`realtime-js/${uVe}`},hVe="1.0.0",eve=1e4,fVe=1e3;var bS;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(bS||(bS={}));var cu;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(cu||(cu={}));var xf;(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"})(xf||(xf={}));var yq;(function(t){t.websocket="websocket"})(yq||(yq={}));var l_;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(l_||(l_={}));class mVe{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 a=n.decode(e.slice(c,c+i));c=c+i;const f=n.decode(e.slice(c,c+o));c=c+o;const m=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:a,event:f,payload:m}}}class tve{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 ja;(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"})(ja||(ja={}));const ise=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((o,c)=>(o[c]=pVe(c,t,e,i),o),{})},pVe=(t,e,r,n)=>{const i=e.find(a=>a.name===t),o=i==null?void 0:i.type,c=r[t];return o&&!n.includes(o)?rve(o,c):xq(c)},rve=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return vVe(e,r)}switch(t){case ja.bool:return gVe(e);case ja.float4:case ja.float8:case ja.int2:case ja.int4:case ja.int8:case ja.numeric:case ja.oid:return yVe(e);case ja.json:case ja.jsonb:return xVe(e);case ja.timestamp:return _Ve(e);case ja.abstime:case ja.date:case ja.daterange:case ja.int4range:case ja.int8range:case ja.money:case ja.reltime:case ja.text:case ja.time:case ja.timestamptz:case ja.timetz:case ja.tsrange:case ja.tstzrange:return xq(e);default:return xq(e)}},xq=t=>t,gVe=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},yVe=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},xVe=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},vVe=(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(a=>rve(e,a))}return t},_Ve=t=>typeof t=="string"?t.replace(" ","T"):t,nve=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class d6{constructor(e,r,n={},i=eve){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 ase;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(ase||(ase={}));class hA{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},i=>{const{onJoin:o,onLeave:c,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=hA.syncState(this.state,i,o,c),this.pendingDiffs.forEach(f=>{this.state=hA.syncDiff(this.state,f,o,c)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},i=>{const{onJoin:o,onLeave:c,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=hA.syncDiff(this.state,i,o,c),a())}),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),a={},f={};return this.map(o,(m,y)=>{c[m]||(f[m]=y)}),this.map(c,(m,y)=>{const v=o[m];if(v){const w=y.map(I=>I.presence_ref),j=v.map(I=>I.presence_ref),A=y.filter(I=>j.indexOf(I.presence_ref)<0),C=v.filter(I=>w.indexOf(I.presence_ref)<0);A.length>0&&(a[m]=A),C.length>0&&(f[m]=C)}else a[m]=y}),this.syncDiff(o,{joins:a,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,(a,f)=>{var m;const y=(m=e[a])!==null&&m!==void 0?m:[];if(e[a]=this.cloneDeep(f),y.length>0){const v=e[a].map(j=>j.presence_ref),w=y.filter(j=>v.indexOf(j.presence_ref)<0);e[a].unshift(...w)}n(a,y,f)}),this.map(c,(a,f)=>{let m=e[a];if(!m)return;const y=f.map(v=>v.presence_ref);m=m.filter(v=>y.indexOf(v.presence_ref)<0),e[a]=m,i(a,m,f),m.length===0&&delete e[a]}),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 ose;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(ose||(ose={}));var lse;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(lse||(lse={}));var ig;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(ig||(ig={}));class gW{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=cu.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 d6(this,xf.join,this.params,this.timeout),this.rejoinTimer=new tve(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=cu.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=cu.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=cu.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=cu.errored,this.rejoinTimer.scheduleTimeout())}),this._on(xf.reply,{},(i,o)=>{this._trigger(this._replyEventName(o),i)}),this.presence=new hA(this),this.broadcastEndpointURL=nve(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:a}}=this.params;this._onError(y=>e==null?void 0:e(ig.CHANNEL_ERROR,y)),this._onClose(()=>e==null?void 0:e(ig.CLOSED));const f={},m={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:a};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:m},f)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:y})=>{var v;if(this.socket.setAuth(),y===void 0){e==null||e(ig.SUBSCRIBED);return}else{const w=this.bindings.postgres_changes,j=(v=w==null?void 0:w.length)!==null&&v!==void 0?v:0,A=[];for(let C=0;C{this.state=cu.errored,e==null||e(ig.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(y).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ig.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 m=await this._fetchWithTimeout(this.broadcastEndpointURL,f,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=m.body)===null||i===void 0?void 0:i.cancel()),m.ok?"ok":"error"}catch(m){return m.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var c,a,f;const m=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((f=(a=(c=this.params)===null||c===void 0?void 0:c.config)===null||a===void 0?void 0:a.broadcast)===null||f===void 0)&&f.ack)&&o("ok"),m.receive("ok",()=>o("ok")),m.receive("error",()=>o("error")),m.receive("timeout",()=>o("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=cu.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(xf.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const i=new d6(this,xf.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 d6(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:a,error:f,leave:m,join:y}=xf;if(n&&[a,f,m,y].indexOf(c)>=0&&n!==this._joinRef())return;let w=this._onMessage(c,r,n);if(r&&!w)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(j=>{var A,C,I;return((A=j.filter)===null||A===void 0?void 0:A.event)==="*"||((I=(C=j.filter)===null||C===void 0?void 0:C.event)===null||I===void 0?void 0:I.toLocaleLowerCase())===c}).map(j=>j.callback(w,n)):(o=this.bindings[c])===null||o===void 0||o.filter(j=>{var A,C,I,M,D,F;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in j){const z=j.id,q=(A=j.filter)===null||A===void 0?void 0:A.event;return z&&((C=r.ids)===null||C===void 0?void 0:C.includes(z))&&(q==="*"||(q==null?void 0:q.toLocaleLowerCase())===((I=r.data)===null||I===void 0?void 0:I.type.toLocaleLowerCase()))}else{const z=(D=(M=j==null?void 0:j.filter)===null||M===void 0?void 0:M.event)===null||D===void 0?void 0:D.toLocaleLowerCase();return z==="*"||z===((F=r==null?void 0:r.event)===null||F===void 0?void 0:F.toLocaleLowerCase())}else return j.type.toLocaleLowerCase()===c}).map(j=>{if(typeof w=="object"&&"ids"in w){const A=w.data,{schema:C,table:I,commit_timestamp:M,type:D,errors:F}=A;w=Object.assign(Object.assign({},{schema:C,table:I,commit_timestamp:M,eventType:D,new:{},old:{},errors:F}),this._getPayloadRecords(A))}j.callback(w,n)})}_isClosed(){return this.state===cu.closed}_isJoined(){return this.state===cu.joined}_isJoining(){return this.state===cu.joining}_isLeaving(){return this.state===cu.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&&gW.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(xf.close,{},e)}_onError(e){this._on(xf.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=cu.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=ise(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=ise(e.columns,e.old_record)),r}}const cse=()=>{},bVe=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class wVe{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=dVe,this.params={},this.timeout=eve,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=cse,this.ref=0,this.logger=cse,this.conn=null,this.sendBuffer=[],this.serializer=new mVe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=o=>{let c;return o?c=o:typeof fetch>"u"?c=(...a)=>Oe(async()=>{const{default:f}=await Promise.resolve().then(()=>aj);return{default:f}},void 0).then(({default:f})=>f(...a)):c=fetch,(...a)=>c(...a)},this.endPoint=`${e}/${yq.websocket}`,this.httpEndpoint=nve(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 tve(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=cVe),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 SVe(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:hVe}))}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 bS.connecting:return l_.Connecting;case bS.open:return l_.Open;case bS.closing:return l_.Closing;default:return l_.Closed}}isConnected(){return this.connectionState()===l_.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(o=>o.topic===n);if(i)return i;{const o=new gW(`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,a=>{var f;(f=this.conn)===null||f===void 0||f.send(a)})};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(xf.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(fVe,"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(a=>a._isMember(n)).forEach(a=>a._trigger(i,o,c)),this.stateChangeCallbacks.message.forEach(a=>a(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(xf.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([bVe],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class SVe{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=bS.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class yW extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function zl(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class TVe extends yW{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class vq extends yW{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var jVe=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};const sve=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Oe(async()=>{const{default:n}=await Promise.resolve().then(()=>aj);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},EVe=()=>jVe(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Oe(()=>Promise.resolve().then(()=>aj),void 0)).Response:Response}),_q=t=>{if(Array.isArray(t))return t.map(r=>_q(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]=_q(n)}),e};var pb=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};const h6=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),kVe=(t,e,r)=>pb(void 0,void 0,void 0,function*(){const n=yield EVe();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{e(new TVe(h6(i),t.status||500))}).catch(i=>{e(new vq(h6(i),i))}):e(new vq(h6(t),t))}),AVe=(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 zC(t,e,r,n,i,o){return pb(this,void 0,void 0,function*(){return new Promise((c,a)=>{t(r,AVe(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=>kVe(f,a,n))})})}function lO(t,e,r,n){return pb(this,void 0,void 0,function*(){return zC(t,"GET",e,r,n)})}function tx(t,e,r,n,i){return pb(this,void 0,void 0,function*(){return zC(t,"POST",e,n,i,r)})}function NVe(t,e,r,n,i){return pb(this,void 0,void 0,function*(){return zC(t,"PUT",e,n,i,r)})}function CVe(t,e,r,n){return pb(this,void 0,void 0,function*(){return zC(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function ive(t,e,r,n,i){return pb(this,void 0,void 0,function*(){return zC(t,"DELETE",e,n,i,r)})}var zu=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};const IVe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},use={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class PVe{constructor(e,r={},n,i){this.url=e,this.headers=r,this.bucketId=n,this.fetch=sve(i)}uploadOrUpdate(e,r,n,i){return zu(this,void 0,void 0,function*(){try{let o;const c=Object.assign(Object.assign({},use),i);let a=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,a["cache-control"]=`max-age=${c.cacheControl}`,a["content-type"]=c.contentType,f&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(f)))),i!=null&&i.headers&&(a=Object.assign(Object.assign({},a),i.headers));const m=this._removeEmptyFolders(r),y=this._getFinalPath(m),v=yield this.fetch(`${this.url}/object/${y}`,Object.assign({method:e,body:o,headers:a},c!=null&&c.duplex?{duplex:c.duplex}:{})),w=yield v.json();return v.ok?{data:{path:m,id:w.Id,fullPath:w.Key},error:null}:{data:null,error:w}}catch(o){if(zl(o))return{data:null,error:o};throw o}})}upload(e,r,n){return zu(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return zu(this,void 0,void 0,function*(){const o=this._removeEmptyFolders(e),c=this._getFinalPath(o),a=new URL(this.url+`/object/upload/sign/${c}`);a.searchParams.set("token",r);try{let f;const m=Object.assign({upsert:use.upsert},i),y=Object.assign(Object.assign({},this.headers),{"x-upsert":String(m.upsert)});typeof Blob<"u"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",m.cacheControl),f.append("",n)):typeof FormData<"u"&&n instanceof FormData?(f=n,f.append("cacheControl",m.cacheControl)):(f=n,y["cache-control"]=`max-age=${m.cacheControl}`,y["content-type"]=m.contentType);const v=yield this.fetch(a.toString(),{method:"PUT",body:f,headers:y}),w=yield v.json();return v.ok?{data:{path:o,fullPath:w.Key},error:null}:{data:null,error:w}}catch(f){if(zl(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,r){return zu(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 tx(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:i}),c=new URL(this.url+o.url),a=c.searchParams.get("token");if(!a)throw new yW("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:a},error:null}}catch(n){if(zl(n))return{data:null,error:n};throw n}})}update(e,r,n){return zu(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return zu(this,void 0,void 0,function*(){try{return{data:yield tx(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(zl(i))return{data:null,error:i};throw i}})}copy(e,r,n){return zu(this,void 0,void 0,function*(){try{return{data:{path:(yield tx(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(zl(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return zu(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),o=yield tx(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(zl(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return zu(this,void 0,void 0,function*(){try{const i=yield tx(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(zl(i))return{data:null,error:i};throw i}})}download(e,r){return zu(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 a=this._getFinalPath(e);return{data:yield(yield lO(this.fetch,`${this.url}/${i}/${a}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(zl(a))return{data:null,error:a};throw a}})}info(e){return zu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield lO(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:_q(n),error:null}}catch(n){if(zl(n))return{data:null,error:n};throw n}})}exists(e){return zu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield CVe(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(zl(n)&&n instanceof vq){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 a=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",f=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});f!==""&&i.push(f);let m=i.join("&");return m!==""&&(m=`?${m}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${m}`)}}}remove(e){return zu(this,void 0,void 0,function*(){try{return{data:yield ive(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(zl(r))return{data:null,error:r};throw r}})}list(e,r,n){return zu(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},IVe),r),{prefix:e||""});return{data:yield tx(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(zl(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 RVe="2.7.1",LVe={"X-Client-Info":`storage-js/${RVe}`};var a1=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};class MVe{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},LVe),r),this.fetch=sve(n)}listBuckets(){return a1(this,void 0,void 0,function*(){try{return{data:yield lO(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(zl(e))return{data:null,error:e};throw e}})}getBucket(e){return a1(this,void 0,void 0,function*(){try{return{data:yield lO(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(zl(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return a1(this,void 0,void 0,function*(){try{return{data:yield tx(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(zl(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return a1(this,void 0,void 0,function*(){try{return{data:yield NVe(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(zl(n))return{data:null,error:n};throw n}})}emptyBucket(e){return a1(this,void 0,void 0,function*(){try{return{data:yield tx(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(zl(r))return{data:null,error:r};throw r}})}deleteBucket(e){return a1(this,void 0,void 0,function*(){try{return{data:yield ive(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(zl(r))return{data:null,error:r};throw r}})}}class DVe extends MVe{constructor(e,r={},n){super(e,r,n)}from(e){return new PVe(this.url,this.headers,e,this.fetch)}}const OVe="2.49.10";let Vk="";typeof Deno<"u"?Vk="deno":typeof document<"u"?Vk="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Vk="react-native":Vk="node";const FVe={"X-Client-Info":`supabase-js-${Vk}/${OVe}`},BVe={headers:FVe},$Ve={schema:"public"},zVe={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},UVe={};var VVe=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};const qVe=t=>{let e;return t?e=t:typeof fetch>"u"?e=V0e:e=fetch,(...r)=>e(...r)},GVe=()=>typeof Headers>"u"?q0e:Headers,HVe=(t,e,r)=>{const n=qVe(r),i=GVe();return(o,c)=>VVe(void 0,void 0,void 0,function*(){var a;const f=(a=yield e())!==null&&a!==void 0?a:t;let m=new i(c==null?void 0:c.headers);return m.has("apikey")||m.set("apikey",t),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),n(o,Object.assign(Object.assign({},c),{headers:m}))})};var WVe=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};function KVe(t){return t.endsWith("/")?t:t+"/"}function YVe(t,e){var r,n;const{db:i,auth:o,realtime:c,global:a}=t,{db:f,auth:m,realtime:y,global:v}=e,w={db:Object.assign(Object.assign({},f),i),auth:Object.assign(Object.assign({},m),o),realtime:Object.assign(Object.assign({},y),c),global:Object.assign(Object.assign(Object.assign({},v),a),{headers:Object.assign(Object.assign({},(r=v==null?void 0:v.headers)!==null&&r!==void 0?r:{}),(n=a==null?void 0:a.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>WVe(this,void 0,void 0,function*(){return""})};return t.accessToken?w.accessToken=t.accessToken:delete w.accessToken,w}const ave="2.69.1",R1=30*1e3,bq=3,f6=bq*R1,ZVe="http://localhost:9999",XVe="supabase.auth.token",QVe={"X-Client-Info":`gotrue-js/${ave}`},wq="X-Supabase-Api-Version",ove={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},JVe=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,e8e=6e5;class xW extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Hs(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class t8e extends xW{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function r8e(t){return Hs(t)&&t.name==="AuthApiError"}class lve extends xW{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class x0 extends xW{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class Yy extends x0{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function n8e(t){return Hs(t)&&t.name==="AuthSessionMissingError"}class m6 extends x0{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class xL extends x0{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class vL extends x0{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 s8e(t){return Hs(t)&&t.name==="AuthImplicitGrantRedirectError"}class dse extends x0{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 Sq extends x0{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function p6(t){return Hs(t)&&t.name==="AuthRetryableFetchError"}class hse extends x0{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class fA extends x0{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const fse="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),mse=` \r=`.split(""),i8e=(()=>{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 pse(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=c=>{l8e(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 o8e(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}a8e(n,e)}}function l8e(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 c8e(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function d8e(t){return Math.round(Date.now()/1e3)+t}function h8e(){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 bm=()=>typeof window<"u"&&typeof document<"u",zv={tested:!1,writable:!1},mA=()=>{if(!bm())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(zv.tested)return zv.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),zv.tested=!0,zv.writable=!0}catch{zv.tested=!0,zv.writable=!1}return zv.writable};function f8e(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 uve=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Oe(async()=>{const{default:n}=await Promise.resolve().then(()=>aj);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},m8e=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",dve=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},_L=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},bL=async(t,e)=>{await t.removeItem(e)};class Y3{constructor(){this.promise=new Y3.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Y3.promiseConstructor=Promise;function g6(t){const e=t.split(".");if(e.length!==3)throw new fA("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function g8e(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 y8e(t){return("0"+t.toString(16)).substr(-2)}function x8e(){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,y8e).join("")}async function v8e(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 _8e(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 v8e(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function o1(t,e,r=!1){const n=x8e();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await dve(t,`${e}-code-verifier`,i);const o=await _8e(n);return[o,n===o?"plain":"s256"]}const b8e=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function w8e(t){const e=t.headers.get(wq);if(!e||!e.match(b8e))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function S8e(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 T8e(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 j8e=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),E8e=[502,503,504];async function gse(t){var e;if(!m8e(t))throw new Sq(e_(t),0);if(E8e.includes(t.status))throw new Sq(e_(t),t.status);let r;try{r=await t.json()}catch(o){throw new lve(e_(o),o)}let n;const i=w8e(t);if(i&&i.getTime()>=ove["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 hse(e_(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Yy}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 hse(e_(r),t.status,r.weak_password.reasons);throw new t8e(e_(r),t.status||500,n)}const k8e=(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 ui(t,e,r,n){var i;const o=Object.assign({},n==null?void 0:n.headers);o[wq]||(o[wq]=ove["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 a=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",f=await A8e(t,e,r+a,{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 A8e(t,e,r,n,i,o){const c=k8e(e,n,i,o);let a;try{a=await t(r,Object.assign({},c))}catch(f){throw console.error(f),new Sq(e_(f),0)}if(a.ok||await gse(a),n!=null&&n.noResolveJson)return a;try{return await a.json()}catch(f){await gse(f)}}function Zy(t){var e;let r=null;P8e(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=d8e(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function yse(t){const e=Zy(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 lx(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function N8e(t){return{data:t,error:null}}function C8e(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o}=t,c=j8e(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o},f=Object.assign({},c);return{data:{properties:a,user:f},error:null}}function I8e(t){return t}function P8e(t){return t.access_token&&t.refresh_token&&t.expires_in}var R8e=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&&(j.forEach(A=>{const C=parseInt(A.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(A.split(";")[1].split("=")[1]);m[`${I}Page`]=C}),m.total=parseInt(w)),{data:Object.assign(Object.assign({},v),m),error:null}}catch(m){if(Hs(m))return{data:{users:[]},error:m};throw m}}async getUserById(e){try{return await ui(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:lx})}catch(r){if(Hs(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){try{return await ui(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:lx})}catch(n){if(Hs(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){try{return await ui(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:lx})}catch(n){if(Hs(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:r,error:n}=await ui(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(Hs(r))return{data:null,error:r};throw r}}async _deleteFactor(e){try{return{data:await ui(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Hs(r))return{data:null,error:r};throw r}}}const M8e={getItem:t=>mA()?globalThis.localStorage.getItem(t):null,setItem:(t,e)=>{mA()&&globalThis.localStorage.setItem(t,e)},removeItem:t=>{mA()&&globalThis.localStorage.removeItem(t)}};function xse(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}function D8e(){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 l1={debug:!!(globalThis&&mA()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class hve extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class O8e extends hve{}async function F8e(t,e,r){l1.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),l1.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){l1.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{l1.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw l1.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new O8e(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(l1.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()}}))}D8e();const B8e={url:ZVe,storageKey:XVe,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:QVe,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function vse(t,e,r){return await r()}class lN{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=lN.nextInstanceID,lN.nextInstanceID+=1,this.instanceID>0&&bm()&&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({},B8e),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 L8e({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=uve(i.fetch),this.lock=i.lock||vse,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:bm()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=F8e:this.lock=vse,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:mA()?this.storage=M8e:(this.memoryStorage={},this.storage=xse(this.memoryStorage)):(this.memoryStorage={},this.storage=xse(this.memoryStorage)),bm()&&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} (${ave}) ${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=f8e(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),bm()&&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),s8e(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:a}=i;return this._debug("#_initialize()","detected session in URL",c,"redirect type",a),await this._saveSession(c),setTimeout(async()=>{a==="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 Hs(r)?{error:r}:{error:new lve("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const o=await ui(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:Zy}),{data:c,error:a}=o;if(a||!c)return{data:{user:null,session:null},error:a};const f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(o){if(Hs(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:v,options:w}=e;let j=null,A=null;this.flowType==="pkce"&&([j,A]=await o1(this.storage,this.storageKey)),o=await ui(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:w==null?void 0:w.emailRedirectTo,body:{email:y,password:v,data:(r=w==null?void 0:w.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:w==null?void 0:w.captchaToken},code_challenge:j,code_challenge_method:A},xform:Zy})}else if("phone"in e){const{phone:y,password:v,options:w}=e;o=await ui(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:y,password:v,data:(n=w==null?void 0:w.data)!==null&&n!==void 0?n:{},channel:(i=w==null?void 0:w.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:w==null?void 0:w.captchaToken}},xform:Zy})}else throw new xL("You must provide either an email or phone number and a password");const{data:c,error:a}=o;if(a||!c)return{data:{user:null,session:null},error:a};const f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(o){if(Hs(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:a}=e;r=await ui(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:c,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:yse})}else if("phone"in e){const{phone:o,password:c,options:a}=e;r=await ui(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:c,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:yse})}else throw new xL("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 m6}:(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(Hs(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 _L(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:o,error:c}=await ui(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Zy});if(await bL(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!o||!o.session||!o.user?{data:{user:null,session:null,redirectType:null},error:new m6}:(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(Hs(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,a=await ui(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:Zy}),{data:f,error:m}=a;return m?{data:{user:null,session:null},error:m}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new m6}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:m})}catch(r){if(Hs(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:a,options:f}=e;let m=null,y=null;this.flowType==="pkce"&&([m,y]=await o1(this.storage,this.storageKey));const{error:v}=await ui(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},create_user:(n=f==null?void 0:f.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:m,code_challenge_method:y},redirectTo:f==null?void 0:f.emailRedirectTo});return{data:{user:null,session:null},error:v}}if("phone"in e){const{phone:a,options:f}=e,{data:m,error:y}=await ui(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,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:m==null?void 0:m.message_id},error:y}}throw new xL("You must provide either an email or phone number.")}catch(a){if(Hs(a))return{data:{user:null,session:null},error:a};throw a}}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:a}=await ui(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:Zy});if(a)throw a;if(!c)throw new Error("An error occurred on token verification.");const f=c.session,m=c.user;return f!=null&&f.access_token&&(await this._saveSession(f),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(i){if(Hs(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 o1(this.storage,this.storageKey)),await ui(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:N8e})}catch(o){if(Hs(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 Yy;const{error:i}=await ui(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(Hs(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 ui(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:a}=await ui(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:a}}throw new xL("You must provide either an email or phone number and a type")}catch(r){if(Hs(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 _L(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()(!c&&m==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),c=!0,this.suppressGetSessionWarning=!0),Reflect.get(f,m,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 ui(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:lx}):await this._useSession(async r=>{var n,i,o;const{data:c,error:a}=r;if(a)throw a;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Yy}:await ui(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:lx})})}catch(r){if(Hs(r))return n8e(r)&&(await this._removeSession(),await bL(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 Yy;const c=i.session;let a=null,f=null;this.flowType==="pkce"&&e.email!=null&&([a,f]=await o1(this.storage,this.storageKey));const{data:m,error:y}=await ui(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:f}),jwt:c.access_token,xform:lx});if(y)throw y;return c.user=m.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(Hs(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 Yy;const r=Date.now()/1e3;let n=r,i=!0,o=null;const{payload:c}=g6(e.access_token);if(c.exp&&(n=c.exp,i=n<=r),i){const{session:a,error:f}=await this._callRefreshToken(e.refresh_token);if(f)return{data:{user:null,session:null},error:f};if(!a)return{data:{user:null,session:null},error:null};o=a}else{const{data:a,error:f}=await this._getUser(e.access_token);if(f)throw f;o={access_token:e.access_token,refresh_token:e.refresh_token,user:a.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(Hs(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:a}=r;if(a)throw a;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Yy;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(Hs(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!bm())throw new vL("No browser detected.");if(e.error||e.error_description||e.error_code)throw new vL(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 dse("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new vL("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 dse("No code detected.");const{data:D,error:F}=await this._exchangeCodeForSession(e.code);if(F)throw F;const z=new URL(window.location.href);return z.searchParams.delete("code"),window.history.replaceState(window.history.state,"",z.toString()),{data:{session:D.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:c,expires_in:a,expires_at:f,token_type:m}=e;if(!o||!a||!c||!m)throw new vL("No session defined in URL");const y=Math.round(Date.now()/1e3),v=parseInt(a);let w=y+v;f&&(w=parseInt(f));const j=w-y;j*1e3<=R1&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${j}s, should have been closer to ${v}s`);const A=w-v;y-A>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",A,w,y):y-A<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",A,w,y);const{data:C,error:I}=await this._getUser(o);if(I)throw I;const M={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:v,expires_at:w,refresh_token:c,token_type:m,user:C.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:M,redirectType:e.type},error:null}}catch(n){if(Hs(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 _L(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:a}=await this.admin.signOut(c,e);if(a&&!(r8e(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await bL(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=h8e(),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 o1(this.storage,this.storageKey,!0));try{return await ui(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(Hs(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(Hs(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,a,f,m,y;const{data:v,error:w}=o;if(w)throw w;const j=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(f=e.options)===null||f===void 0?void 0:f.queryParams,skipBrowserRedirect:!0});return await ui(this.fetch,"GET",j,{headers:this.headers,jwt:(y=(m=v.session)===null||m===void 0?void 0:m.access_token)!==null&&y!==void 0?y:void 0})});if(i)throw i;return bm()&&!(!((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(Hs(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 ui(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(Hs(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 g8e(async i=>(i>0&&await p8e(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await ui(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Zy})),(i,o)=>{const c=200*Math.pow(2,i);return o&&p6(o)&&Date.now()+c-n{try{await a.callback(e,r)}catch(f){o.push(f)}});if(await Promise.all(c),o.length>0){for(let a=0;athis._autoRefreshTokenTick(),R1);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)/R1);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${R1}ms, refresh threshold is ${bq} ticks`),i<=bq&&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 hve)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!bm()||!(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 o1(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(o)}`,code_challenge_method:`${encodeURIComponent(c)}`});i.push(a.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 ui(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(Hs(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 a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:f,error:m}=await ui(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=o==null?void 0:o.session)===null||n===void 0?void 0:n.access_token});return m?{data:null,error:m}:(e.factorType==="totp"&&(!((i=f==null?void 0:f.totp)===null||i===void 0)&&i.qr_code)&&(f.totp.qr_code=`data:image/svg+xml;utf-8,${f.totp.qr_code}`),{data:f,error:null})})}catch(r){if(Hs(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:a}=await ui(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 a?{data:null,error:a}:(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:a})})}catch(r){if(Hs(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 ui(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(Hs(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}=g6(i.access_token);let a=null;c.aal&&(a=c.aal);let f=a;((n=(r=i.user.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(f="aal2");const y=c.amr||[];return{data:{currentLevel:a,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+e8e>Date.now()))return n;const{data:i,error:o}=await ui(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 fA("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),n=i.keys.find(c=>c.kid===e),!n)throw new fA("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:j,error:A}=await this.getSession();if(A||!j.session)return{data:null,error:A};n=j.session.access_token}const{header:i,payload:o,signature:c,raw:{header:a,payload:f}}=g6(n);if(S8e(o.exp),!i.kid||i.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:j}=await this.getUser(n);if(j)throw j;return{data:{claims:o,header:i,signature:c},error:null}}const m=T8e(i.alg),y=await this.fetchJwk(i.kid,r),v=await crypto.subtle.importKey("jwk",y,m,!0,["verify"]);if(!await crypto.subtle.verify(m,v,c,u8e(`${a}.${f}`)))throw new fA("Invalid JWT signature");return{data:{claims:o,header:i,signature:c},error:null}}catch(n){if(Hs(n))return{data:null,error:n};throw n}}}lN.nextInstanceID=0;const $8e=lN;class z8e extends $8e{constructor(e){super(e)}}var U8e=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 a(y){try{m(n.next(y))}catch(v){c(v)}}function f(y){try{m(n.throw(y))}catch(v){c(v)}}function m(y){y.done?o(y.value):i(y.value).then(a,f)}m((n=n.apply(t,e||[])).next())})};class V8e{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 a=KVe(e),f=new URL(a);this.realtimeUrl=new URL("realtime/v1",f),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",f),this.storageUrl=new URL("storage/v1",f),this.functionsUrl=new URL("functions/v1",f);const m=`sb-${f.hostname.split(".")[0]}-auth-token`,y={db:$Ve,realtime:UVe,auth:Object.assign(Object.assign({},zVe),{storageKey:m}),global:BVe},v=YVe(n??{},y);this.storageKey=(i=v.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(o=v.global.headers)!==null&&o!==void 0?o:{},v.accessToken?(this.accessToken=v.accessToken,this.auth=new Proxy({},{get:(w,j)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(j)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=v.auth)!==null&&c!==void 0?c:{},this.headers,v.global.fetch),this.fetch=HVe(r,this._getAccessToken.bind(this),v.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},v.realtime)),this.rest=new lVe(new URL("rest/v1",f).href,{headers:this.headers,schema:v.db.schema,fetch:this.fetch}),v.accessToken||this._listenForAuthEvents()}get functions(){return new FUe(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new DVe(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 U8e(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:a,debug:f},m,y){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new z8e({url:this.authUrl.href,headers:Object.assign(Object.assign({},v),m),storageKey:o,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,flowType:c,lock:a,debug:f,fetch:y,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new wVe(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 q8e=(t,e,r)=>new V8e(t,e,r),G8e="lovable-preview-auth:result";function H8e(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!==G8e||!("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 W8e(){try{const t=localStorage;return t.getItem("__lovable_storage_probe__"),t}catch{return}}function K8e(){var D,F,z;if(typeof window>"u")return;const t=location.hostname,r=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(q=>t===q||t.endsWith("."+q)),n="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",i=r?((D=new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+n+")(?:-dev)?(?=\\.|$)","i").exec(t))==null?void 0:D[1])??((F=new RegExp("^live--("+n+")(?:-thr_[a-z0-9]+)?(?=\\.|$)","i").exec(t))==null?void 0:F[1])??((z=new RegExp("^("+n+")(?=[.-])","i").exec(t))==null?void 0:z[1]):void 0,o=window.parent;if(!i||!(o!==null&&o!==window))return W8e();const a=t.endsWith(".lovableproject-dev.com")||t.endsWith(".gpt-eng.com"),f=a?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,m=location.ancestorOrigins,y=(m==null?void 0:m[0])??(document.referrer?new URL(document.referrer).origin:""),v=y&&f.test(y)?[y]:a?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],w=2e3,j=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),A=(q,H,K)=>new Promise(J=>{const Q=j();let ee=!1;const oe=Le=>{ee||(ee=!0,clearTimeout(ye),window.removeEventListener("message",de),J(Le))},de=Le=>{if(!v.includes(Le.origin))return;const Se=H8e(Le.data,Q);Se&&oe(Se)};window.addEventListener("message",de);const ye=setTimeout(()=>{oe(null)},w),we={type:q,requestId:Q,projectId:i,key:H};K!==void 0&&(we.value=K);for(const Le of v)window.parent.postMessage(we,Le)});let C=!0;const I=250,M=q=>{try{return localStorage.getItem(q)}catch{return}};return{getItem:async q=>{const H=M(q);let K=await A("lovable-preview-auth:get",q,H??void 0);if(!K&&C&&(await new Promise(J=>setTimeout(J,I)),K=await A("lovable-preview-auth:get",q,H??void 0)),C=!1,K!=null&&K.ok&&K.value!==null){if(K.value===""){if(H!==void 0&&M(q)===H)try{localStorage.removeItem(q)}catch{}return null}if(H===null&&M(q)===null)try{localStorage.setItem(q,K.value)}catch{}return K.value}return M(q)??null},setItem:(q,H)=>{try{localStorage.setItem(q,H)}catch{}return A("lovable-preview-auth:set",q,H).then(K=>{if(K!=null&&K.ok&&K.value!==null&&M(q)===H)try{K.value===""?localStorage.removeItem(q):localStorage.setItem(q,K.value)}catch{}})},removeItem:q=>{const H=M(q);try{localStorage.removeItem(q)}catch{}return A("lovable-preview-auth:remove",q,H??void 0).then(()=>{})}}}const Y8e="https://relzejiswnotikjgvjhz.supabase.co",Z8e="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",Ce=q8e(Y8e,Z8e,{auth:{storage:K8e(),persistSession:!0,autoRefreshToken:!0}}),HJt=Object.freeze(Object.defineProperty({__proto__:null,supabase:Ce},Symbol.toStringTag,{value:"Module"})),fve=N.createContext(void 0),X8e=({children:t})=>{const[e,r]=N.useState(null),[n,i]=N.useState(null),[o,c]=N.useState(!0),[a,f]=N.useState(!0),[m,y]=N.useState(!1),[v,w]=N.useState(!1),[j,A]=N.useState(!1),[C,I]=N.useState(null),[M,D]=N.useState([]),[F,z]=N.useState(null),q=N.useRef(null),H=N.useRef(!1),K=N.useRef(!1),J=Bi(),Q=N.useRef(null),ee=Se=>{z(ve=>{const me=typeof Se=="function"?Se(ve):Se,ke=Q.current;if(ke&&me)try{localStorage.setItem(`levelup:selectedBrokerage:${ke}`,me)}catch{}return me})},oe=()=>{y(!1),w(!1),A(!1),I(null),D([]),ee(null),q.current=null,H.current=!1},de=async Se=>{if(Q.current=Se,H.current&&q.current===Se||K.current)return;K.current=!0,f(!0);const ve=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),K.current=!1,f(!1)},8e3);try{console.log("Checking roles via RPC for user:",Se);const[{data:me,error:ke},{data:Pe,error:Ee},{data:xe,error:Ue}]=await Promise.all([Ce.rpc("has_role",{_user_id:Se,_role:"admin"}),Ce.rpc("has_role",{_user_id:Se,_role:"brokerage_manager"}),Ce.rpc("has_role",{_user_id:Se,_role:"coach"})]);if(ke||Ee)console.error("Role RPC errors:",{isAdminError:ke,isBrokerError:Ee,isCoachError:Ue}),y(!1),w(!1),A(!1);else{const wt=!!me,yt=!!Pe,gt=!!xe;console.log("RPC roles result:",{adminValue:wt,brokerValue:yt,coachValue:gt}),y(wt),w(yt),A(gt)}q.current=Se,H.current=!0,window.clearTimeout(ve),f(!1);const{data:Ze,error:lt}=await Ce.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",Se).single();if(!lt&&(Ze!=null&&Ze.is_paused)){const wt=Ze.paused_reason;try{sessionStorage.setItem("accountPausedReason",wt||"")}catch{}await Ce.auth.signOut(),oe(),J("/auth?paused=1",{replace:!0});return}if(I(!lt&&Ze?Ze.brokerage_id:null),Pe){console.log("Fetching managed brokerages for user:",Se);const{data:wt,error:yt}=await Ce.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",Se);if(console.log("Managed brokerage assignments result:",{assignments:wt,assignmentsError:yt}),yt||!wt){console.error("Error fetching managed brokerage assignments:",yt),D([]);return}const gt=Array.from(new Set(wt.map(xt=>xt.brokerage_id).filter(Boolean)));if(gt.length===0){D([]);return}const{data:ft,error:kt}=await Ce.from("brokerages").select("id, name").in("id",gt);if(console.log("Managed brokerages details result:",{brokeragesData:ft,brokeragesError:kt}),kt||!ft){console.error("Error fetching managed brokerages details:",kt),D([]);return}const Vt=ft.map(xt=>({id:xt.id,name:xt.name})).sort((xt,or)=>gt.indexOf(xt.id)-gt.indexOf(or.id));if(console.log("Parsed managed brokerages:",Vt),D(Vt),Vt.length>0){let xt=null;try{xt=localStorage.getItem(`levelup:selectedBrokerage:${Se}`)}catch{}ee(or=>{const Tr=rn=>!!rn&&Vt.some(Lr=>Lr.id===rn);return Tr(or)?or:Tr(xt)?xt:Vt[0].id})}}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),D([]);q.current=Se,H.current=!0}catch(me){console.error("Unexpected error in checkRoles:",me),oe()}finally{window.clearTimeout(ve),K.current=!1,f(!1)}};N.useEffect(()=>{let Se=!0,ve=!1;const me=()=>{!Se||ve||(ve=!0,c(!1))},{data:{subscription:ke}}=Ce.auth.onAuthStateChange((Ee,xe)=>{console.log("Auth event:",Ee),Se&&(i(xe),r(Ue=>{const Ze=(xe==null?void 0:xe.user)??null;return Ue&&Ze&&Ue.id===Ze.id?Ue:Ze}),me(),Ee==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{J("/profile?reset=true")},100)),xe!=null&&xe.user?(!H.current||q.current!==xe.user.id)&&setTimeout(()=>{de(xe.user.id)},0):(oe(),f(!1)))}),Pe=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),me()},8e3);return()=>{Se=!1,window.clearTimeout(Pe),ke.unsubscribe()}},[]);const ye=async(Se,ve)=>{var Ee;const me=(Se||"").trim().toLowerCase(),{data:ke,error:Pe}=await Ce.auth.signInWithPassword({email:me,password:ve});if(Pe)throw $t.error(/invalid login credentials/i.test(Pe.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:Pe.message),Pe;if((Ee=ke.user)!=null&&Ee.id){const{data:xe}=await Ce.from("profiles").select("is_paused, paused_reason").eq("id",ke.user.id).maybeSingle();if(xe!=null&&xe.is_paused){const Ue=xe.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",Ue)}catch{}await Ce.auth.signOut(),oe(),r(null),i(null);const Ze=new Error(Ue?`Your account is paused. ${Ue}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw Ze.name="AccountPaused",$t.error(Ze.message),Ze}}$t.success("Welcome back!")},we=async(Se,ve,me)=>{var Ue;const ke="https://dashboard.relevelup.com/dashboard",Pe=localStorage.getItem("levelup_referral_code")||null,{data:Ee,error:xe}=await Ce.auth.signUp({email:Se,password:ve,options:{emailRedirectTo:ke,data:{name:me,referred_by_code:Pe}}});if(xe)throw $t.error(xe.message),xe;if(Pe&&((Ue=Ee.user)!=null&&Ue.id))try{await Ce.from("profiles").update({referred_by_code:Pe}).eq("id",Ee.user.id),localStorage.removeItem("levelup_referral_code")}catch(Ze){console.warn("Failed to attach referral code to profile",Ze)}$t.success("Account created! Welcome to LevelUp."),J("/dashboard")},Le=async()=>{try{const{data:{session:Se}}=await Ce.auth.getSession();if(Se){const{error:ve}=await Ce.auth.signOut();ve?ve.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",ve.message):(console.error("Sign out error:",ve),$t.error(ve.message)):$t.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),y(!1),w(!1),I(null),D([]),ee(null),J("/auth")}catch(Se){console.error("Unexpected sign out error:",Se),J("/auth")}};return s.jsx(fve.Provider,{value:{user:e,session:n,loading:o,rolesLoading:a,signIn:ye,signUp:we,signOut:Le,isAdmin:m,isBrokerageManager:v,isCoach:j,brokerageId:C,managedBrokerages:M,selectedBrokerageId:F,setSelectedBrokerageId:ee},children:t})},Zn=()=>{const t=N.useContext(fve);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},mve=N.createContext({onlineUsers:[],totalOnline:0}),Q8e=3*60*1e3,J8e=45*1e3,eqe=30*1e3,tqe=({children:t})=>{const{user:e,brokerageId:r,isAdmin:n}=Zn(),[i,o]=N.useState([]),c=N.useRef(new Date().toISOString()),a=N.useCallback(async()=>{e&&await Ce.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=N.useCallback(async()=>{if(!e)return;const y=new Date(Date.now()-Q8e).toISOString(),{data:v}=await Ce.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(!(v!=null&&v.length)){o([]);return}const w=v.map(C=>C.user_id),{data:j}=await Ce.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",w),A=new Map((j||[]).map(C=>[C.id,C]));o(v.map(C=>{var M;const I=A.get(C.user_id);return{id:C.user_id,name:(I==null?void 0:I.name)||((M=I==null?void 0:I.email)==null?void 0:M.split("@")[0])||"Member",avatarUrl:(I==null?void 0:I.avatar_url)||void 0,brokerageId:(I==null?void 0:I.brokerage_id)||void 0,onlineSince:C.online_since||C.last_seen_at}}))},[e==null?void 0:e.id]);N.useEffect(()=>{if(!e){o([]);return}c.current=new Date().toISOString();let y=!1;const v=async()=>{y||(await a(),await f())};v();const w=window.setInterval(()=>{a()},J8e),j=window.setInterval(()=>{f()},eqe),A=()=>{document.visibilityState==="visible"&&v()};return document.addEventListener("visibilitychange",A),()=>{y=!0,window.clearInterval(w),window.clearInterval(j),document.removeEventListener("visibilitychange",A)}},[e==null?void 0:e.id,a,f]);const m=i.filter(y=>!!(y.id===(e==null?void 0:e.id)||n||r&&y.brokerageId===r||!r&&!y.brokerageId));return s.jsx(mve.Provider,{value:{onlineUsers:m,totalOnline:m.length},children:t})},WJt=()=>N.useContext(mve),pve=N.createContext(void 0),Uv="levelup_admin_session",By="levelup_impersonation",y6="levelup_impersonation_return",rqe=({children:t})=>{const[e,r]=N.useState(!1),[n,i]=N.useState(null),[o,c]=N.useState(!1);N.useEffect(()=>{const m=sessionStorage.getItem(By);if(m)try{const y=JSON.parse(m);r(!0),i(y)}catch{sessionStorage.removeItem(By)}},[]);const a=async(m,y)=>{c(!0);try{const{data:{session:v}}=await Ce.auth.getSession();if(!v)return $t.error("No active session found"),!1;const w={access_token:v.access_token,refresh_token:v.refresh_token};sessionStorage.setItem(Uv,JSON.stringify(w)),y&&sessionStorage.setItem(y6,y);const j=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v.access_token}`},body:JSON.stringify({targetUserId:m})}),A=await j.json();if(!j.ok)throw new Error(A.error||"Failed to impersonate user");const C={id:A.targetUser.id,name:A.targetUser.name,email:A.targetUser.email};if(sessionStorage.setItem(By,JSON.stringify(C)),A.method==="session"){const{error:I}=await Ce.auth.setSession({access_token:A.access_token,refresh_token:A.refresh_token});if(I)throw console.error("Set session error:",I),sessionStorage.removeItem(Uv),sessionStorage.removeItem(By),new Error("Failed to establish impersonation session")}else{const I=A.type||"recovery",{error:M}=await Ce.auth.verifyOtp({token_hash:A.token_hash,type:I});if(M)throw console.error("Verify OTP error:",M),sessionStorage.removeItem(Uv),sessionStorage.removeItem(By),new Error("Failed to establish impersonation session")}return r(!0),i(C),$t.success(`Now viewing as ${C.name}`),window.location.href="/dashboard",!0}catch(v){return console.error("Impersonation error:",v),$t.error(v.message||"Failed to impersonate user"),sessionStorage.removeItem(Uv),sessionStorage.removeItem(By),!1}finally{c(!1)}},f=async()=>{c(!0);try{const m=sessionStorage.getItem(Uv);if(!m){await Ce.auth.signOut(),window.location.href="/auth";return}const y=JSON.parse(m);await Ce.auth.signOut();const{error:v}=await Ce.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(sessionStorage.removeItem(Uv),sessionStorage.removeItem(By),v){console.error("Failed to restore admin session:",v),$t.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),i(null),$t.success("Returned to your account");const w=sessionStorage.getItem(y6)||"/admin/members";sessionStorage.removeItem(y6),window.location.href=w}catch(m){console.error("Stop impersonation error:",m),$t.error("Failed to restore admin session"),sessionStorage.removeItem(Uv),sessionStorage.removeItem(By),window.location.href="/auth"}finally{c(!1)}};return s.jsx(pve.Provider,{value:{isImpersonating:e,impersonatedUser:n,startImpersonation:a,stopImpersonation:f,isLoading:o},children:t})},gve=()=>{const t=N.useContext(pve);if(t===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return t},nqe=()=>{const{isImpersonating:t,impersonatedUser:e,stopImpersonation:r,isLoading:n}=gve();return!t||!e?null:s.jsx("div",{className:"fixed top-0 left-0 right-0 z-[100] bg-amber-500 text-amber-950 px-4 py-2 shadow-lg",children:s.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(XT,{className:"h-5 w-5 flex-shrink-0"}),s.jsxs("span",{className:"font-medium text-sm md:text-base",children:[s.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),s.jsx("strong",{children:e.name}),s.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",e.email,")"]})]})]}),s.jsx(Lt,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?s.jsx(zc,{className:"h-4 w-4 animate-spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Ci,{className:"h-4 w-4 mr-1"}),s.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),s.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},yve=N.createContext(void 0),c1="levelup_acting_as",wL="levelup_acting_as_self",sqe=({children:t})=>{const{user:e}=Zn(),[r,n]=N.useState(!1),[i,o]=N.useState([]),[c,a]=N.useState(null),[f,m]=N.useState({}),[y,v]=N.useState(!0),[w,j]=N.useState(()=>sessionStorage.getItem(wL)==="true");N.useEffect(()=>{if(!(e!=null&&e.id)){n(!1),o([]),a(null),m({}),v(!1);return}(async()=>{v(!0);try{const{data:F}=await Ce.rpc("has_role",{_user_id:e.id,_role:"assistant"});if(!F){n(!1),o([]),a(null),m({}),v(!1);return}n(!0);const{data:z,error:q}=await Ce.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",e.id);if(q||!z||z.length===0){o([]),v(!1);return}const H=z.map(Q=>Q.agent_id),{data:K}=await Ce.from("profiles").select("id, name, email, avatar_url").in("id",H),J=(K||[]).map(Q=>({id:Q.id,name:Q.name||Q.email||"Unknown",email:Q.email||"",avatar_url:Q.avatar_url}));if(o(J),sessionStorage.getItem(wL)==="true")j(!0),a(null),m({});else{const Q=sessionStorage.getItem(c1);if(Q){const ee=J.find(oe=>oe.id===Q);if(ee){a(ee);const oe=z.find(de=>de.agent_id===Q);m((oe==null?void 0:oe.permissions)||{})}else if(J.length>0){a(J[0]);const oe=z.find(de=>de.agent_id===J[0].id);m((oe==null?void 0:oe.permissions)||{}),sessionStorage.setItem(c1,J[0].id)}}else if(J.length>0){a(J[0]);const ee=z.find(oe=>oe.agent_id===J[0].id);m((ee==null?void 0:ee.permissions)||{}),sessionStorage.setItem(c1,J[0].id)}}}catch(F){console.error("Error loading assistant data:",F)}finally{v(!1)}})()},[e==null?void 0:e.id]);const A=D=>{a(D),j(!1),sessionStorage.removeItem(wL),D?(sessionStorage.setItem(c1,D.id),Ce.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(e==null?void 0:e.id)||"").eq("agent_id",D.id).single().then(({data:F})=>{m((F==null?void 0:F.permissions)||{})})):(sessionStorage.removeItem(c1),m({}))},C=()=>{j(!0),a(null),m({}),sessionStorage.setItem(wL,"true"),sessionStorage.removeItem(c1)},I=D=>!r||w?!0:f[D]===!0,M=r&&c&&!w?c.id:(e==null?void 0:e.id)||null;return s.jsx(yve.Provider,{value:{isAssistant:r,assignedAgents:i,actingAsAgent:c,setActingAsAgent:A,effectiveUserId:M,permissions:f,hasPermission:I,isLoading:y,isActingAsSelf:w,setActingAsSelf:C},children:t})},Z3=()=>{const t=N.useContext(yve);if(t===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return t},zs=()=>{const{effectiveUserId:t}=Z3();return t};var xve={exports:{}},vve={};/** * @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 sT=N;function iqe(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var aqe=typeof Object.is=="function"?Object.is:iqe,oqe=sT.useState,lqe=sT.useEffect,cqe=sT.useLayoutEffect,uqe=sT.useDebugValue;function dqe(t,e){var r=e(),n=oqe({inst:{value:r,getSnapshot:e}}),i=n[0].inst,o=n[1];return cqe(function(){i.value=r,i.getSnapshot=e,x6(i)&&o({inst:i})},[t,r,e]),lqe(function(){return x6(i)&&o({inst:i}),t(function(){x6(i)&&o({inst:i})})},[t]),uqe(r),r}function x6(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!aqe(t,r)}catch{return!0}}function hqe(t,e){return e()}var fqe=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?hqe:dqe;vve.useSyncExternalStore=sT.useSyncExternalStore!==void 0?sT.useSyncExternalStore:fqe;xve.exports=vve;var mqe=xve.exports;function pqe(){return mqe.useSyncExternalStore(gqe,()=>!0,()=>!1)}function gqe(){return()=>{}}var vW="Avatar",[yqe,KJt]=dl(vW),[xqe,_ve]=yqe(vW),bve=N.forwardRef((t,e)=>{const{__scopeAvatar:r,...n}=t,[i,o]=N.useState("idle");return s.jsx(xqe,{scope:r,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:s.jsx(cn.span,{...n,ref:e})})});bve.displayName=vW;var wve="AvatarImage",Sve=N.forwardRef((t,e)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:i=()=>{},...o}=t,c=_ve(wve,r),a=vqe(n,o),f=go(m=>{i(m),c.onImageLoadingStatusChange(m)});return Ho(()=>{a!=="idle"&&f(a)},[a,f]),a==="loaded"?s.jsx(cn.img,{...o,ref:e,src:n}):null});Sve.displayName=wve;var Tve="AvatarFallback",jve=N.forwardRef((t,e)=>{const{__scopeAvatar:r,delayMs:n,...i}=t,o=_ve(Tve,r),[c,a]=N.useState(n===void 0);return N.useEffect(()=>{if(n!==void 0){const f=window.setTimeout(()=>a(!0),n);return()=>window.clearTimeout(f)}},[n]),c&&o.imageLoadingStatus!=="loaded"?s.jsx(cn.span,{...i,ref:e}):null});jve.displayName=Tve;function _se(t,e){return t?e?(t.src!==e&&(t.src=e),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function vqe(t,{referrerPolicy:e,crossOrigin:r}){const n=pqe(),i=N.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[c,a]=N.useState(()=>_se(o,t));return Ho(()=>{a(_se(o,t))},[o,t]),Ho(()=>{const f=v=>()=>{a(v)};if(!o)return;const m=f("loaded"),y=f("error");return o.addEventListener("load",m),o.addEventListener("error",y),e&&(o.referrerPolicy=e),typeof r=="string"&&(o.crossOrigin=r),()=>{o.removeEventListener("load",m),o.removeEventListener("error",y)}},[o,r,e]),c}var Eve=bve,kve=Sve,Ave=jve;const $d=N.forwardRef(({className:t,...e},r)=>s.jsx(Eve,{ref:r,className:Xt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));$d.displayName=Eve.displayName;const zd=N.forwardRef(({className:t,...e},r)=>s.jsx(kve,{ref:r,className:Xt("aspect-square h-full w-full",t),...e}));zd.displayName=kve.displayName;const Ud=N.forwardRef(({className:t,...e},r)=>s.jsx(Ave,{ref:r,className:Xt("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));Ud.displayName=Ave.displayName;const _qe=YT("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 gi({className:t,variant:e,...r}){return s.jsx("div",{className:Xt(_qe({variant:e}),t),...r})}var bqe=N.createContext(void 0);function gb(t){const e=N.useContext(bqe);return t||e||"ltr"}var v6="rovingFocusGroup.onEntryFocus",wqe={bubbles:!1,cancelable:!0},UC="RovingFocusGroup",[Tq,Nve,Sqe]=jC(UC),[Tqe,lj]=dl(UC,[Sqe]),[jqe,Eqe]=Tqe(UC),Cve=N.forwardRef((t,e)=>s.jsx(Tq.Provider,{scope:t.__scopeRovingFocusGroup,children:s.jsx(Tq.Slot,{scope:t.__scopeRovingFocusGroup,children:s.jsx(kqe,{...t,ref:e})})}));Cve.displayName=UC;var kqe=N.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:i=!1,dir:o,currentTabStopId:c,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:f,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...v}=t,w=N.useRef(null),j=is(e,w),A=gb(o),[C,I]=rd({prop:c,defaultProp:a??null,onChange:f,caller:UC}),[M,D]=N.useState(!1),F=go(m),z=Nve(r),q=N.useRef(!1),[H,K]=N.useState(0);return N.useEffect(()=>{const J=w.current;if(J)return J.addEventListener(v6,F),()=>J.removeEventListener(v6,F)},[F]),s.jsx(jqe,{scope:r,orientation:n,dir:A,loop:i,currentTabStopId:C,onItemFocus:N.useCallback(J=>I(J),[I]),onItemShiftTab:N.useCallback(()=>D(!0),[]),onFocusableItemAdd:N.useCallback(()=>K(J=>J+1),[]),onFocusableItemRemove:N.useCallback(()=>K(J=>J-1),[]),children:s.jsx(cn.div,{tabIndex:M||H===0?-1:0,"data-orientation":n,...v,ref:j,style:{outline:"none",...t.style},onMouseDown:Gr(t.onMouseDown,()=>{q.current=!0}),onFocus:Gr(t.onFocus,J=>{const Q=!q.current;if(J.target===J.currentTarget&&Q&&!M){const ee=new CustomEvent(v6,wqe);if(J.currentTarget.dispatchEvent(ee),!ee.defaultPrevented){const oe=z().filter(Se=>Se.focusable),de=oe.find(Se=>Se.active),ye=oe.find(Se=>Se.id===C),Le=[de,ye,...oe].filter(Boolean).map(Se=>Se.ref.current);Rve(Le,y)}}q.current=!1}),onBlur:Gr(t.onBlur,()=>D(!1))})})}),Ive="RovingFocusGroupItem",Pve=N.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:i=!1,tabStopId:o,children:c,...a}=t,f=ol(),m=o||f,y=Eqe(Ive,r),v=y.currentTabStopId===m,w=Nve(r),{onFocusableItemAdd:j,onFocusableItemRemove:A,currentTabStopId:C}=y;return N.useEffect(()=>{if(n)return j(),()=>A()},[n,j,A]),s.jsx(Tq.ItemSlot,{scope:r,id:m,focusable:n,active:i,children:s.jsx(cn.span,{tabIndex:v?0:-1,"data-orientation":y.orientation,...a,ref:e,onMouseDown:Gr(t.onMouseDown,I=>{n?y.onItemFocus(m):I.preventDefault()}),onFocus:Gr(t.onFocus,()=>y.onItemFocus(m)),onKeyDown:Gr(t.onKeyDown,I=>{if(I.key==="Tab"&&I.shiftKey){y.onItemShiftTab();return}if(I.target!==I.currentTarget)return;const M=Cqe(I,y.orientation,y.dir);if(M!==void 0){if(I.metaKey||I.ctrlKey||I.altKey||I.shiftKey)return;I.preventDefault();let F=w().filter(z=>z.focusable).map(z=>z.ref.current);if(M==="last")F.reverse();else if(M==="prev"||M==="next"){M==="prev"&&F.reverse();const z=F.indexOf(I.currentTarget);F=y.loop?Iqe(F,z+1):F.slice(z+1)}setTimeout(()=>Rve(F))}}),children:typeof c=="function"?c({isCurrentTabStop:v,hasTabStop:C!=null}):c})})});Pve.displayName=Ive;var Aqe={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Nqe(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function Cqe(t,e,r){const n=Nqe(t.key,r);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return Aqe[n]}function Rve(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}function Iqe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var _W=Cve,bW=Pve,jq=["Enter"," "],Pqe=["ArrowDown","PageUp","Home"],Lve=["ArrowUp","PageDown","End"],Rqe=[...Pqe,...Lve],Lqe={ltr:[...jq,"ArrowRight"],rtl:[...jq,"ArrowLeft"]},Mqe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},VC="Menu",[cN,Dqe,Oqe]=jC(VC),[yb,Mve]=dl(VC,[Oqe,g0,lj]),qC=g0(),Dve=lj(),[Ove,v0]=yb(VC),[Fqe,GC]=yb(VC),Fve=t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:o,modal:c=!0}=t,a=qC(e),[f,m]=N.useState(null),y=N.useRef(!1),v=go(o),w=gb(i);return N.useEffect(()=>{const j=()=>{y.current=!0,document.addEventListener("pointerdown",A,{capture:!0,once:!0}),document.addEventListener("pointermove",A,{capture:!0,once:!0})},A=()=>y.current=!1;return document.addEventListener("keydown",j,{capture:!0}),()=>{document.removeEventListener("keydown",j,{capture:!0}),document.removeEventListener("pointerdown",A,{capture:!0}),document.removeEventListener("pointermove",A,{capture:!0})}},[]),s.jsx(FC,{...a,children:s.jsx(Ove,{scope:e,open:r,onOpenChange:v,content:f,onContentChange:m,children:s.jsx(Fqe,{scope:e,onClose:N.useCallback(()=>v(!1),[v]),isUsingKeyboardRef:y,dir:w,modal:c,children:n})})})};Fve.displayName=VC;var Bqe="MenuAnchor",wW=N.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=qC(r);return s.jsx(BC,{...i,...n,ref:e})});wW.displayName=Bqe;var SW="MenuPortal",[$qe,Bve]=yb(SW,{forceMount:void 0}),$ve=t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,o=v0(SW,e);return s.jsx($qe,{scope:e,forceMount:r,children:s.jsx(Pl,{present:r||o.open,children:s.jsx(KT,{asChild:!0,container:i,children:n})})})};$ve.displayName=SW;var Eh="MenuContent",[zqe,TW]=yb(Eh),zve=N.forwardRef((t,e)=>{const r=Bve(Eh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=v0(Eh,t.__scopeMenu),c=GC(Eh,t.__scopeMenu);return s.jsx(cN.Provider,{scope:t.__scopeMenu,children:s.jsx(Pl,{present:n||o.open,children:s.jsx(cN.Slot,{scope:t.__scopeMenu,children:c.modal?s.jsx(Uqe,{...i,ref:e}):s.jsx(Vqe,{...i,ref:e})})})})}),Uqe=N.forwardRef((t,e)=>{const r=v0(Eh,t.__scopeMenu),n=N.useRef(null),i=is(e,n);return N.useEffect(()=>{const o=n.current;if(o)return A3(o)},[]),s.jsx(jW,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Gr(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),Vqe=N.forwardRef((t,e)=>{const r=v0(Eh,t.__scopeMenu);return s.jsx(jW,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),qqe=Gx("MenuContent.ScrollLock"),jW=N.forwardRef((t,e)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:c,disableOutsidePointerEvents:a,onEntryFocus:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:w,onDismiss:j,disableOutsideScroll:A,...C}=t,I=v0(Eh,r),M=GC(Eh,r),D=qC(r),F=Dve(r),z=Dqe(r),[q,H]=N.useState(null),K=N.useRef(null),J=is(e,K,I.onContentChange),Q=N.useRef(0),ee=N.useRef(""),oe=N.useRef(0),de=N.useRef(null),ye=N.useRef("right"),we=N.useRef(0),Le=A?PC:N.Fragment,Se=A?{as:qqe,allowPinchZoom:!0}:void 0,ve=ke=>{var yt,gt;const Pe=ee.current+ke,Ee=z().filter(ft=>!ft.disabled),xe=document.activeElement,Ue=(yt=Ee.find(ft=>ft.ref.current===xe))==null?void 0:yt.textValue,Ze=Ee.map(ft=>ft.textValue),lt=r9e(Ze,Pe,Ue),wt=(gt=Ee.find(ft=>ft.textValue===lt))==null?void 0:gt.ref.current;(function ft(kt){ee.current=kt,window.clearTimeout(Q.current),kt!==""&&(Q.current=window.setTimeout(()=>ft(""),1e3))})(Pe),wt&&setTimeout(()=>wt.focus())};N.useEffect(()=>()=>window.clearTimeout(Q.current),[]),E3();const me=N.useCallback(ke=>{var Ee,xe;return ye.current===((Ee=de.current)==null?void 0:Ee.side)&&s9e(ke,(xe=de.current)==null?void 0:xe.area)},[]);return s.jsx(zqe,{scope:r,searchRef:ee,onItemEnter:N.useCallback(ke=>{me(ke)&&ke.preventDefault()},[me]),onItemLeave:N.useCallback(ke=>{var Pe;me(ke)||((Pe=K.current)==null||Pe.focus(),H(null))},[me]),onTriggerLeave:N.useCallback(ke=>{me(ke)&&ke.preventDefault()},[me]),pointerGraceTimerRef:oe,onPointerGraceIntentChange:N.useCallback(ke=>{de.current=ke},[]),children:s.jsx(Le,{...Se,children:s.jsx(IC,{asChild:!0,trapped:i,onMountAutoFocus:Gr(o,ke=>{var Pe;ke.preventDefault(),(Pe=K.current)==null||Pe.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:s.jsx(fb,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:w,onDismiss:j,children:s.jsx(_W,{asChild:!0,...F,dir:M.dir,orientation:"vertical",loop:n,currentTabStopId:q,onCurrentTabStopIdChange:H,onEntryFocus:Gr(f,ke=>{M.isUsingKeyboardRef.current||ke.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(M3,{role:"menu","aria-orientation":"vertical","data-state":s_e(I.open),"data-radix-menu-content":"",dir:M.dir,...D,...C,ref:J,style:{outline:"none",...C.style},onKeyDown:Gr(C.onKeyDown,ke=>{const Ee=ke.target.closest("[data-radix-menu-content]")===ke.currentTarget,xe=ke.ctrlKey||ke.altKey||ke.metaKey,Ue=ke.key.length===1;Ee&&(ke.key==="Tab"&&ke.preventDefault(),!xe&&Ue&&ve(ke.key));const Ze=K.current;if(ke.target!==Ze||!Rqe.includes(ke.key))return;ke.preventDefault();const wt=z().filter(yt=>!yt.disabled).map(yt=>yt.ref.current);Lve.includes(ke.key)&&wt.reverse(),e9e(wt)}),onBlur:Gr(t.onBlur,ke=>{ke.currentTarget.contains(ke.target)||(window.clearTimeout(Q.current),ee.current="")}),onPointerMove:Gr(t.onPointerMove,uN(ke=>{const Pe=ke.target,Ee=we.current!==ke.clientX;if(ke.currentTarget.contains(Pe)&&Ee){const xe=ke.clientX>we.current?"right":"left";ye.current=xe,we.current=ke.clientX}}))})})})})})})});zve.displayName=Eh;var Gqe="MenuGroup",EW=N.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(cn.div,{role:"group",...n,ref:e})});EW.displayName=Gqe;var Hqe="MenuLabel",Uve=N.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(cn.div,{...n,ref:e})});Uve.displayName=Hqe;var cO="MenuItem",bse="menu.itemSelect",X3=N.forwardRef((t,e)=>{const{disabled:r=!1,onSelect:n,...i}=t,o=N.useRef(null),c=GC(cO,t.__scopeMenu),a=TW(cO,t.__scopeMenu),f=is(e,o),m=N.useRef(!1),y=()=>{const v=o.current;if(!r&&v){const w=new CustomEvent(bse,{bubbles:!0,cancelable:!0});v.addEventListener(bse,j=>n==null?void 0:n(j),{once:!0}),TH(v,w),w.defaultPrevented?m.current=!1:c.onClose()}};return s.jsx(Vve,{...i,ref:f,disabled:r,onClick:Gr(t.onClick,y),onPointerDown:v=>{var w;(w=t.onPointerDown)==null||w.call(t,v),m.current=!0},onPointerUp:Gr(t.onPointerUp,v=>{var w;m.current||(w=v.currentTarget)==null||w.click()}),onKeyDown:Gr(t.onKeyDown,v=>{const w=a.searchRef.current!=="";r||w&&v.key===" "||jq.includes(v.key)&&(v.currentTarget.click(),v.preventDefault())})})});X3.displayName=cO;var Vve=N.forwardRef((t,e)=>{const{__scopeMenu:r,disabled:n=!1,textValue:i,...o}=t,c=TW(cO,r),a=Dve(r),f=N.useRef(null),m=is(e,f),[y,v]=N.useState(!1),[w,j]=N.useState("");return N.useEffect(()=>{const A=f.current;A&&j((A.textContent??"").trim())},[o.children]),s.jsx(cN.ItemSlot,{scope:r,disabled:n,textValue:i??w,children:s.jsx(bW,{asChild:!0,...a,focusable:!n,children:s.jsx(cn.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:m,onPointerMove:Gr(t.onPointerMove,uN(A=>{n?c.onItemLeave(A):(c.onItemEnter(A),A.defaultPrevented||A.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Gr(t.onPointerLeave,uN(A=>c.onItemLeave(A))),onFocus:Gr(t.onFocus,()=>v(!0)),onBlur:Gr(t.onBlur,()=>v(!1))})})})}),Wqe="MenuCheckboxItem",qve=N.forwardRef((t,e)=>{const{checked:r=!1,onCheckedChange:n,...i}=t;return s.jsx(Yve,{scope:t.__scopeMenu,checked:r,children:s.jsx(X3,{role:"menuitemcheckbox","aria-checked":uO(r)?"mixed":r,...i,ref:e,"data-state":NW(r),onSelect:Gr(i.onSelect,()=>n==null?void 0:n(uO(r)?!0:!r),{checkForDefaultPrevented:!1})})})});qve.displayName=Wqe;var Gve="MenuRadioGroup",[Kqe,Yqe]=yb(Gve,{value:void 0,onValueChange:()=>{}}),Hve=N.forwardRef((t,e)=>{const{value:r,onValueChange:n,...i}=t,o=go(n);return s.jsx(Kqe,{scope:t.__scopeMenu,value:r,onValueChange:o,children:s.jsx(EW,{...i,ref:e})})});Hve.displayName=Gve;var Wve="MenuRadioItem",Kve=N.forwardRef((t,e)=>{const{value:r,...n}=t,i=Yqe(Wve,t.__scopeMenu),o=r===i.value;return s.jsx(Yve,{scope:t.__scopeMenu,checked:o,children:s.jsx(X3,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":NW(o),onSelect:Gr(n.onSelect,()=>{var c;return(c=i.onValueChange)==null?void 0:c.call(i,r)},{checkForDefaultPrevented:!1})})})});Kve.displayName=Wve;var kW="MenuItemIndicator",[Yve,Zqe]=yb(kW,{checked:!1}),Zve=N.forwardRef((t,e)=>{const{__scopeMenu:r,forceMount:n,...i}=t,o=Zqe(kW,r);return s.jsx(Pl,{present:n||uO(o.checked)||o.checked===!0,children:s.jsx(cn.span,{...i,ref:e,"data-state":NW(o.checked)})})});Zve.displayName=kW;var Xqe="MenuSeparator",Xve=N.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(cn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});Xve.displayName=Xqe;var Qqe="MenuArrow",Qve=N.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=qC(r);return s.jsx(D3,{...i,...n,ref:e})});Qve.displayName=Qqe;var AW="MenuSub",[Jqe,Jve]=yb(AW),e_e=t=>{const{__scopeMenu:e,children:r,open:n=!1,onOpenChange:i}=t,o=v0(AW,e),c=qC(e),[a,f]=N.useState(null),[m,y]=N.useState(null),v=go(i);return N.useEffect(()=>(o.open===!1&&v(!1),()=>v(!1)),[o.open,v]),s.jsx(FC,{...c,children:s.jsx(Ove,{scope:e,open:n,onOpenChange:v,content:m,onContentChange:y,children:s.jsx(Jqe,{scope:e,contentId:ol(),triggerId:ol(),trigger:a,onTriggerChange:f,children:r})})})};e_e.displayName=AW;var qk="MenuSubTrigger",t_e=N.forwardRef((t,e)=>{const r=v0(qk,t.__scopeMenu),n=GC(qk,t.__scopeMenu),i=Jve(qk,t.__scopeMenu),o=TW(qk,t.__scopeMenu),c=N.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:f}=o,m={__scopeMenu:t.__scopeMenu},y=N.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return N.useEffect(()=>y,[y]),N.useEffect(()=>{const v=a.current;return()=>{window.clearTimeout(v),f(null)}},[a,f]),s.jsx(wW,{asChild:!0,...m,children:s.jsx(Vve,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":s_e(r.open),...t,ref:Cg(e,i.onTriggerChange),onClick:v=>{var w;(w=t.onClick)==null||w.call(t,v),!(t.disabled||v.defaultPrevented)&&(v.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Gr(t.onPointerMove,uN(v=>{o.onItemEnter(v),!v.defaultPrevented&&!t.disabled&&!r.open&&!c.current&&(o.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{r.onOpenChange(!0),y()},100))})),onPointerLeave:Gr(t.onPointerLeave,uN(v=>{var j,A;y();const w=(j=r.content)==null?void 0:j.getBoundingClientRect();if(w){const C=(A=r.content)==null?void 0:A.dataset.side,I=C==="right",M=I?-5:5,D=w[I?"left":"right"],F=w[I?"right":"left"];o.onPointerGraceIntentChange({area:[{x:v.clientX+M,y:v.clientY},{x:D,y:w.top},{x:F,y:w.top},{x:F,y:w.bottom},{x:D,y:w.bottom}],side:C}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(v),v.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Gr(t.onKeyDown,v=>{var j;const w=o.searchRef.current!=="";t.disabled||w&&v.key===" "||Lqe[n.dir].includes(v.key)&&(r.onOpenChange(!0),(j=r.content)==null||j.focus(),v.preventDefault())})})})});t_e.displayName=qk;var r_e="MenuSubContent",n_e=N.forwardRef((t,e)=>{const r=Bve(Eh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=v0(Eh,t.__scopeMenu),c=GC(Eh,t.__scopeMenu),a=Jve(r_e,t.__scopeMenu),f=N.useRef(null),m=is(e,f);return s.jsx(cN.Provider,{scope:t.__scopeMenu,children:s.jsx(Pl,{present:n||o.open,children:s.jsx(cN.Slot,{scope:t.__scopeMenu,children:s.jsx(jW,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:m,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:y=>{var v;c.isUsingKeyboardRef.current&&((v=f.current)==null||v.focus()),y.preventDefault()},onCloseAutoFocus:y=>y.preventDefault(),onFocusOutside:Gr(t.onFocusOutside,y=>{y.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Gr(t.onEscapeKeyDown,y=>{c.onClose(),y.preventDefault()}),onKeyDown:Gr(t.onKeyDown,y=>{var j;const v=y.currentTarget.contains(y.target),w=Mqe[c.dir].includes(y.key);v&&w&&(o.onOpenChange(!1),(j=a.trigger)==null||j.focus(),y.preventDefault())})})})})})});n_e.displayName=r_e;function s_e(t){return t?"open":"closed"}function uO(t){return t==="indeterminate"}function NW(t){return uO(t)?"indeterminate":t?"checked":"unchecked"}function e9e(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}function t9e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}function r9e(t,e,r){const i=e.length>1&&Array.from(e).every(m=>m===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=t9e(t,Math.max(o,0));i.length===1&&(c=c.filter(m=>m!==r));const f=c.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function n9e(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=w>n&&r<(v-m)*(n-y)/(w-y)+m&&(i=!i)}return i}function s9e(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return n9e(r,e)}function uN(t){return e=>e.pointerType==="mouse"?t(e):void 0}var i9e=Fve,a9e=wW,o9e=$ve,l9e=zve,c9e=EW,u9e=Uve,d9e=X3,h9e=qve,f9e=Hve,m9e=Kve,p9e=Zve,g9e=Xve,y9e=Qve,x9e=e_e,v9e=t_e,_9e=n_e,Q3="DropdownMenu",[b9e,YJt]=dl(Q3,[Mve]),Vc=Mve(),[w9e,i_e]=b9e(Q3),a_e=t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:o,onOpenChange:c,modal:a=!0}=t,f=Vc(e),m=N.useRef(null),[y,v]=rd({prop:i,defaultProp:o??!1,onChange:c,caller:Q3});return s.jsx(w9e,{scope:e,triggerId:ol(),triggerRef:m,contentId:ol(),open:y,onOpenChange:v,onOpenToggle:N.useCallback(()=>v(w=>!w),[v]),modal:a,children:s.jsx(i9e,{...f,open:y,onOpenChange:v,dir:n,modal:a,children:r})})};a_e.displayName=Q3;var o_e="DropdownMenuTrigger",l_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...i}=t,o=i_e(o_e,r),c=Vc(r);return s.jsx(a9e,{asChild:!0,...c,children:s.jsx(cn.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:Cg(e,o.triggerRef),onPointerDown:Gr(t.onPointerDown,a=>{!n&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:Gr(t.onKeyDown,a=>{n||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});l_e.displayName=o_e;var S9e="DropdownMenuPortal",c_e=t=>{const{__scopeDropdownMenu:e,...r}=t,n=Vc(e);return s.jsx(o9e,{...n,...r})};c_e.displayName=S9e;var u_e="DropdownMenuContent",d_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=i_e(u_e,r),o=Vc(r),c=N.useRef(!1);return s.jsx(l9e,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...n,ref:e,onCloseAutoFocus:Gr(t.onCloseAutoFocus,a=>{var f;c.current||(f=i.triggerRef.current)==null||f.focus(),c.current=!1,a.preventDefault()}),onInteractOutside:Gr(t.onInteractOutside,a=>{const f=a.detail.originalEvent,m=f.button===0&&f.ctrlKey===!0,y=f.button===2||m;(!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)"}})});d_e.displayName=u_e;var T9e="DropdownMenuGroup",j9e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(c9e,{...i,...n,ref:e})});j9e.displayName=T9e;var E9e="DropdownMenuLabel",h_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(u9e,{...i,...n,ref:e})});h_e.displayName=E9e;var k9e="DropdownMenuItem",f_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(d9e,{...i,...n,ref:e})});f_e.displayName=k9e;var A9e="DropdownMenuCheckboxItem",m_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(h9e,{...i,...n,ref:e})});m_e.displayName=A9e;var N9e="DropdownMenuRadioGroup",C9e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(f9e,{...i,...n,ref:e})});C9e.displayName=N9e;var I9e="DropdownMenuRadioItem",p_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(m9e,{...i,...n,ref:e})});p_e.displayName=I9e;var P9e="DropdownMenuItemIndicator",g_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(p9e,{...i,...n,ref:e})});g_e.displayName=P9e;var R9e="DropdownMenuSeparator",y_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(g9e,{...i,...n,ref:e})});y_e.displayName=R9e;var L9e="DropdownMenuArrow",M9e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(y9e,{...i,...n,ref:e})});M9e.displayName=L9e;var D9e=t=>{const{__scopeDropdownMenu:e,children:r,open:n,onOpenChange:i,defaultOpen:o}=t,c=Vc(e),[a,f]=rd({prop:n,defaultProp:o??!1,onChange:i,caller:"DropdownMenuSub"});return s.jsx(x9e,{...c,open:a,onOpenChange:f,children:r})},O9e="DropdownMenuSubTrigger",x_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(v9e,{...i,...n,ref:e})});x_e.displayName=O9e;var F9e="DropdownMenuSubContent",v_e=N.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Vc(r);return s.jsx(_9e,{...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)"}})});v_e.displayName=F9e;var B9e=a_e,$9e=l_e,z9e=c_e,__e=d_e,b_e=h_e,w_e=f_e,S_e=m_e,T_e=p_e,j_e=g_e,E_e=y_e,U9e=D9e,k_e=x_e,A_e=v_e;const cj=B9e,uj=$9e,ZJt=U9e,V9e=N.forwardRef(({className:t,inset:e,children:r,...n},i)=>s.jsxs(k_e,{ref:i,className:Xt("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",e&&"pl-8",t),...n,children:[r,s.jsx(Wd,{className:"ml-auto h-4 w-4"})]}));V9e.displayName=k_e.displayName;const q9e=N.forwardRef(({className:t,...e},r)=>s.jsx(A_e,{ref:r,className:Xt("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}));q9e.displayName=A_e.displayName;const xb=N.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(z9e,{children:s.jsx(__e,{ref:n,sideOffset:e,className:Xt("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})}));xb.displayName=__e.displayName;const yu=N.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(w_e,{ref:n,className:Xt("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}));yu.displayName=w_e.displayName;const G9e=N.forwardRef(({className:t,children:e,checked:r,...n},i)=>s.jsxs(S_e,{ref:i,className:Xt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),checked:r,...n,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(j_e,{children:s.jsx(pa,{className:"h-4 w-4"})})}),e]}));G9e.displayName=S_e.displayName;const H9e=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(T_e,{ref:n,className:Xt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(j_e,{children:s.jsx(W_,{className:"h-2 w-2 fill-current"})})}),e]}));H9e.displayName=T_e.displayName;const CW=N.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(b_e,{ref:n,className:Xt("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));CW.displayName=b_e.displayName;const iT=N.forwardRef(({className:t,...e},r)=>s.jsx(E_e,{ref:r,className:Xt("-mx-1 my-1 h-px bg-muted",t),...e}));iT.displayName=E_e.displayName;const W9e=()=>{const{isAssistant:t,actingAsAgent:e,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:i,setActingAsSelf:o}=Z3();if(!t)return null;const c=a=>a.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return s.jsx("div",{className:"fixed top-0 left-0 right-0 z-[2147483647] bg-primary text-primary-foreground px-4 py-1.5 shadow-lg",style:{height:"40px"},children:s.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4 h-full",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[i?s.jsxs(s.Fragment,{children:[s.jsx(Wl,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):s.jsxs(s.Fragment,{children:[s.jsx(kl,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),s.jsxs(cj,{children:[s.jsx(uj,{asChild:!0,children:s.jsxs(Lt,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[i?s.jsxs(s.Fragment,{children:[s.jsx(Wl,{className:"h-4 w-4"}),s.jsx("strong",{children:"My Account"})]}):e?s.jsxs(s.Fragment,{children:[s.jsxs($d,{className:"h-5 w-5",children:[s.jsx(zd,{src:e.avatar_url||void 0}),s.jsx(Ud,{className:"text-[10px] bg-primary-foreground/30",children:c(e.name)})]}),s.jsx("strong",{children:e.name})]}):s.jsx("strong",{children:"Select..."}),s.jsx(Wo,{className:"h-3 w-3"})]})}),s.jsxs(xb,{align:"start",className:"z-[2147483647]",children:[s.jsxs(yu,{onClick:o,className:"gap-2",children:[s.jsx(Wl,{className:"h-4 w-4"}),s.jsx("span",{children:"My Account"}),i&&s.jsx(gi,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),s.jsx(iT,{}),r.map(a=>s.jsxs(yu,{onClick:()=>n(a),className:"gap-2",children:[s.jsxs($d,{className:"h-6 w-6",children:[s.jsx(zd,{src:a.avatar_url||void 0}),s.jsx(Ud,{className:"text-[10px]",children:c(a.name)})]}),s.jsx("span",{children:a.name}),!i&&a.id===(e==null?void 0:e.id)&&s.jsx(gi,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},a.id))]})]})]}),s.jsx(gi,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:i?"Personal Mode":"Assistant Mode"})]})})};function N_e(){var f,m;const{user:t,isAdmin:e}=Zn(),{data:r,isLoading:n}=mr({queryKey:["partnership-membership",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:y}=await Ce.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:v},{data:w}]=await Promise.all([Ce.from("partnership_packages").select("*").eq("id",y.package_id).maybeSingle(),Ce.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",y.program_id).maybeSingle()]);return!v||!(w!=null&&w.enabled)?null:{membership:y,pkg:v,program:w}}}),i=N.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),a=y=>{var j,A;const v=((j=r==null?void 0:r.pkg)==null?void 0:j.feature_limits)||{},w=(A=v==null?void 0:v[y])==null?void 0:A.monthly_limit;return typeof w=="number"?w: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:((m=r==null?void 0:r.pkg)==null?void 0:m.name)??null,features:i,hasFeature:c,limitFor:a,isRestricted:o&&!e}}const IW={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"},XJt=Object.keys(IW),K9e={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},wse={"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"},Y9e={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","social-studio":"social","weekly-reels":"weekly_reels"};function Z9e(t){return t.id in wse?wse[t.id]:K9e[t.primaryCategory]??null}function QJt(t){return Y9e[t]??null}const X9e=[["/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 Q9e(t){let e=null;for(const r of X9e){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 Kn=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:Xt("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Kn.displayName="Card";const Rd=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:Xt("flex flex-col space-y-1.5 p-6",t),...e}));Rd.displayName="CardHeader";const Ld=N.forwardRef(({className:t,...e},r)=>s.jsx("h3",{ref:r,className:Xt("text-2xl font-semibold leading-none tracking-tight",t),...e}));Ld.displayName="CardTitle";const dN=N.forwardRef(({className:t,...e},r)=>s.jsx("p",{ref:r,className:Xt("text-sm text-muted-foreground",t),...e}));dN.displayName="CardDescription";const ss=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:Xt("p-6 pt-0",t),...e}));ss.displayName="CardContent";const Eq=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:Xt("flex items-center p-6 pt-0",t),...e}));Eq.displayName="CardFooter";const qc=N.forwardRef(({className:t,...e},r)=>s.jsx("textarea",{className:Xt("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}));qc.displayName="Textarea";const Wa=C3,C_e=qH,J9e=I3,JJt=MC,I_e=N.forwardRef(({className:t,...e},r)=>s.jsx(JT,{ref:r,className:Xt("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}));I_e.displayName=JT.displayName;const La=N.forwardRef(({className:t,children:e,overlayClassName:r,...n},i)=>s.jsxs(J9e,{children:[s.jsx(I_e,{className:r}),s.jsxs(ej,{ref:i,className:Xt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[e,s.jsxs(MC,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ci,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));La.displayName=ej.displayName;const Ko=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});Ko.displayName="DialogHeader";const P_e=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});P_e.displayName="DialogFooter";const Po=N.forwardRef(({className:t,...e},r)=>s.jsx(RC,{ref:r,className:Xt("text-lg font-semibold leading-none tracking-tight",t),...e}));Po.displayName=RC.displayName;const sd=N.forwardRef(({className:t,...e},r)=>s.jsx(LC,{ref:r,className:Xt("text-sm text-muted-foreground",t),...e}));sd.displayName=LC.displayName;function eGe({featureKey:t,open:e,onOpenChange:r}){const{user:n}=Zn(),i=kr(),[o,c]=N.useState(""),{data:a}=mr({queryKey:["partnership-upgrade-requests",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&e,queryFn:async()=>{const{data:v}=await Ce.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",n.id);return v||[]}}),f=!!(a!=null&&a.some(v=>v.feature_key===t&&v.status!=="declined")),m=Ar({mutationFn:async()=>{const{error:v}=await Ce.from("lead_site_upgrade_requests").insert({user_id:n.id,feature_key:t,notes:o||null});if(v)throw v},onSuccess:()=>{i.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),$t.success("Request sent — we'll be in touch shortly."),c(""),r(!1)},onError:v=>$t.error((v==null?void 0:v.message)||"Could not send your request")}),y=IW[t]||t;return s.jsx(Wa,{open:e,onOpenChange:r,children:s.jsxs(La,{className:"sm:max-w-md",children:[s.jsxs(Ko,{children:[s.jsxs(Po,{className:"flex items-center gap-2",children:[s.jsx(ki,{className:"h-5 w-5 text-primary"}),"Request ",y]}),s.jsxs(sd,{children:[y," is included with the Signature package. Send a request and we'll get you set up."]})]}),f?s.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[s.jsx(pa,{className:"h-4 w-4 mt-0.5 text-primary"}),s.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):s.jsx(qc,{placeholder:"Anything we should know? (optional)",value:o,onChange:v=>c(v.target.value),rows:4}),s.jsxs(P_e,{children:[s.jsx(Lt,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!f&&s.jsx(Lt,{onClick:()=>m.mutate(),disabled:m.isPending,children:m.isPending?"Sending…":"Send request"})]})]})})}function tGe({featureKey:t}){const[e,r]=N.useState(!1),n=IW[t]||t;return s.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[s.jsx(Kn,{className:"max-w-lg w-full border-border/60",children:s.jsxs(ss,{className:"p-8 text-center space-y-4",children:[s.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(Wx,{className:"h-6 w-6 text-primary"})}),s.jsxs("h2",{className:"text-2xl font-semibold",children:[n," is a Signature feature"]}),s.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",n,". Request access and our team will upgrade your account."]}),s.jsxs(Lt,{onClick:()=>r(!0),className:"gap-2",children:[s.jsx(ki,{className:"h-4 w-4"})," Request access"]})]})}),s.jsx(eGe,{featureKey:t,open:e,onOpenChange:r})]})}const rGe=t=>{const[e,r]=N.useState(null),[n,i]=N.useState(!0);return N.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:a}=await Ce.storage.from("avatars").list(`${t}`);if(a&&a.length>0){const{data:f}=Ce.storage.from("avatars").getPublicUrl(`${t}/${a[0].name}`);r(`${f.publicUrl}?t=${Date.now()}`)}else r(null)}catch(a){console.error("Error fetching avatar:",a),r(null)}finally{i(!1)}})()},[t]),{avatarUrl:e,loading:n,refreshAvatar:async()=>{if(t)try{const{data:c}=await Ce.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:a}=Ce.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${a.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},eer=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await Ce.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=Ce.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},nGe=t=>{const[e,r]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:o}=await Ce.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(v=>({...v,loading:!1}));return}const c=(i==null?void 0:i.subscription_status)==="trialing",a=!!(i!=null&&i.is_trial),f=!!(i!=null&&i.trial_expires_at)&&new Date(i.trial_expires_at).getTime()>Date.now()&&(i==null?void 0:i.subscription_status)!=="active",m=c&&(i==null?void 0:i.subscription_end_date)||(i==null?void 0:i.trial_expires_at)||(i==null?void 0:i.subscription_end_date)||null;if((c||a||f)&&!!m&&m){const v=new Date().getTime(),w=new Date(m).getTime(),j=Math.ceil((w-v)/(1e3*60*60*24)),A=j<=0;r({isTrial:!0,isExpired:A,expiresAt:m,daysLeft:A?0:j,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},J3=()=>{const{data:t,isLoading:e}=mr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await Ce.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")}},Sse="community_last_seen_post_at";function sGe(){const{user:t}=Zn(),e=xs(),[r,n]=N.useState(0),[i,o]=N.useState(null);N.useEffect(()=>{if(!t)return;const a=localStorage.getItem(`${Sse}_${t.id}`);o(a)},[t]),N.useEffect(()=>{if(!t)return;const a=`community_unread_count_${t.id}`,f=2*60*1e3;(async()=>{try{const j=sessionStorage.getItem(a);if(j){const A=JSON.parse(j);if(A.ts&&Date.now()-A.ts{if(!t)return;const a=Ce.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async f=>{const m=f.new;if(m.user_id===t.id)return;const y=e.pathname==="/community";y||n(C=>C+1);const{data:v}=await Ce.from("profiles").select("name").eq("id",m.user_id).single(),w=(v==null?void 0:v.name)||"Someone",j=m.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),A=j.length>50?j.substring(0,50)+"...":j;y||$t("New Community Post",{description:`${w}: ${A}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{Ce.removeChannel(a)}},[t,e.pathname]);const c=N.useCallback(()=>{if(!t)return;const a=new Date().toISOString();localStorage.setItem(`${Sse}_${t.id}`,a),o(a),n(0)},[t]);return N.useEffect(()=>{e.pathname==="/community"&&r>0&&c()},[e.pathname,r,c]),{unreadCount:r,markAsRead:c}}function iGe(){const{isAdmin:t}=Zn(),{data:e=0}=mr({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await Ce.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 _6=t=>`levelup:activeTeam:${t}`,aGe=()=>{const t=zs();return mr({queryKey:["user-teams",t],queryFn:async()=>{const{data:e,error:r}=await Ce.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 Ce.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,a)=>{var f,m;return c.role!==a.role?c.role==="team_leader"?-1:1:(((f=c.team)==null?void 0:f.name)||"").localeCompare(((m=a.team)==null?void 0:m.name)||"")})},enabled:!!t,staleTime:5*60*1e3})},dj=()=>{const t=zs(),e=aGe(),r=N.useMemo(()=>e.data||[],[e.data]),[n,i]=N.useState(()=>!t||typeof window>"u"?null:window.localStorage.getItem(_6(t)));N.useEffect(()=>{!t||typeof window>"u"||i(window.localStorage.getItem(_6(t)))},[t]);const o=N.useCallback(a=>{i(a),t&&typeof window<"u"&&window.localStorage.setItem(_6(t),a)},[t]),c=N.useMemo(()=>r.length?r.find(a=>a.teamId===n)||r[0]:null,[r,n]);return{...e,data:c,teams:r,activeTeamId:(c==null?void 0:c.teamId)??null,setActiveTeamId:o}},Tse="weekly_reels";function PW(){const{user:t,loading:e,isAdmin:r}=Zn(),{data:n,isLoading:i}=mr({queryKey:["feature-entitlement",Tse,t==null?void 0:t.id],enabled:!!t&&!r,staleTime:5*60*1e3,queryFn:async()=>{const{data:o,error:c}=await Ce.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key",Tse).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 R_e=C3,oGe=qH,lGe=I3,L_e=N.forwardRef(({className:t,...e},r)=>s.jsx(JT,{className:Xt("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}));L_e.displayName=JT.displayName;const cGe=YT("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"}}),RW=N.forwardRef(({side:t="right",className:e,children:r,...n},i)=>s.jsxs(lGe,{children:[s.jsx(L_e,{}),s.jsxs(ej,{ref:i,className:Xt(cGe({side:t}),e),...n,children:[r,s.jsxs(MC,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ci,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));RW.displayName=ej.displayName;const M_e=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col space-y-2 text-center sm:text-left",t),...e});M_e.displayName="SheetHeader";const uGe=({className:t,...e})=>s.jsx("div",{className:Xt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});uGe.displayName="SheetFooter";const D_e=N.forwardRef(({className:t,...e},r)=>s.jsx(RC,{ref:r,className:Xt("text-lg font-semibold text-foreground",t),...e}));D_e.displayName=RC.displayName;const O_e=N.forwardRef(({className:t,...e},r)=>s.jsx(LC,{ref:r,className:Xt("text-sm text-muted-foreground",t),...e}));O_e.displayName=LC.displayName;function hN(t,[e,r]){return Math.min(r,Math.max(e,t))}function dGe(t,e){return N.useReducer((r,n)=>e[r][n]??r,t)}var LW="ScrollArea",[F_e,ter]=dl(LW),[hGe,Dh]=F_e(LW),B_e=N.forwardRef((t,e)=>{const{__scopeScrollArea:r,type:n="hover",dir:i,scrollHideDelay:o=600,...c}=t,[a,f]=N.useState(null),[m,y]=N.useState(null),[v,w]=N.useState(null),[j,A]=N.useState(null),[C,I]=N.useState(null),[M,D]=N.useState(0),[F,z]=N.useState(0),[q,H]=N.useState(!1),[K,J]=N.useState(!1),Q=is(e,oe=>f(oe)),ee=gb(i);return s.jsx(hGe,{scope:r,type:n,dir:ee,scrollHideDelay:o,scrollArea:a,viewport:m,onViewportChange:y,content:v,onContentChange:w,scrollbarX:j,onScrollbarXChange:A,scrollbarXEnabled:q,onScrollbarXEnabledChange:H,scrollbarY:C,onScrollbarYChange:I,scrollbarYEnabled:K,onScrollbarYEnabledChange:J,onCornerWidthChange:D,onCornerHeightChange:z,children:s.jsx(cn.div,{dir:ee,...c,ref:Q,style:{position:"relative","--radix-scroll-area-corner-width":M+"px","--radix-scroll-area-corner-height":F+"px",...t.style}})})});B_e.displayName=LW;var $_e="ScrollAreaViewport",z_e=N.forwardRef((t,e)=>{const{__scopeScrollArea:r,children:n,nonce:i,...o}=t,c=Dh($_e,r),a=N.useRef(null),f=is(e,a,c.onViewportChange);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),s.jsx(cn.div,{"data-radix-scroll-area-viewport":"",...o,ref:f,style:{overflowX:c.scrollbarXEnabled?"scroll":"hidden",overflowY:c.scrollbarYEnabled?"scroll":"hidden",...t.style},children:s.jsx("div",{ref:c.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});z_e.displayName=$_e;var dp="ScrollAreaScrollbar",MW=N.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=Dh(dp,t.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:c}=i,a=t.orientation==="horizontal";return N.useEffect(()=>(a?o(!0):c(!0),()=>{a?o(!1):c(!1)}),[a,o,c]),i.type==="hover"?s.jsx(fGe,{...n,ref:e,forceMount:r}):i.type==="scroll"?s.jsx(mGe,{...n,ref:e,forceMount:r}):i.type==="auto"?s.jsx(U_e,{...n,ref:e,forceMount:r}):i.type==="always"?s.jsx(DW,{...n,ref:e}):null});MW.displayName=dp;var fGe=N.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=Dh(dp,t.__scopeScrollArea),[o,c]=N.useState(!1);return N.useEffect(()=>{const a=i.scrollArea;let f=0;if(a){const m=()=>{window.clearTimeout(f),c(!0)},y=()=>{f=window.setTimeout(()=>c(!1),i.scrollHideDelay)};return a.addEventListener("pointerenter",m),a.addEventListener("pointerleave",y),()=>{window.clearTimeout(f),a.removeEventListener("pointerenter",m),a.removeEventListener("pointerleave",y)}}},[i.scrollArea,i.scrollHideDelay]),s.jsx(Pl,{present:r||o,children:s.jsx(U_e,{"data-state":o?"visible":"hidden",...n,ref:e})})}),mGe=N.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=Dh(dp,t.__scopeScrollArea),o=t.orientation==="horizontal",c=tF(()=>f("SCROLL_END"),100),[a,f]=dGe("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return N.useEffect(()=>{if(a==="idle"){const m=window.setTimeout(()=>f("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(m)}},[a,i.scrollHideDelay,f]),N.useEffect(()=>{const m=i.viewport,y=o?"scrollLeft":"scrollTop";if(m){let v=m[y];const w=()=>{const j=m[y];v!==j&&(f("SCROLL"),c()),v=j};return m.addEventListener("scroll",w),()=>m.removeEventListener("scroll",w)}},[i.viewport,o,f,c]),s.jsx(Pl,{present:r||a!=="hidden",children:s.jsx(DW,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Gr(t.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:Gr(t.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),U_e=N.forwardRef((t,e)=>{const r=Dh(dp,t.__scopeScrollArea),{forceMount:n,...i}=t,[o,c]=N.useState(!1),a=t.orientation==="horizontal",f=tF(()=>{if(r.viewport){const m=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=t,i=Dh(dp,t.__scopeScrollArea),o=N.useRef(null),c=N.useRef(0),[a,f]=N.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),m=W_e(a.viewport,a.content),y={...n,sizes:a,onSizesChange:f,hasThumb:m>0&&m<1,onThumbChange:w=>o.current=w,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:w=>c.current=w};function v(w,j){return _Ge(w,c.current,a,j)}return r==="horizontal"?s.jsx(pGe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const w=i.viewport.scrollLeft,j=jse(w,a,i.dir);o.current.style.transform=`translate3d(${j}px, 0, 0)`}},onWheelScroll:w=>{i.viewport&&(i.viewport.scrollLeft=w)},onDragScroll:w=>{i.viewport&&(i.viewport.scrollLeft=v(w,i.dir))}}):r==="vertical"?s.jsx(gGe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const w=i.viewport.scrollTop,j=jse(w,a);o.current.style.transform=`translate3d(0, ${j}px, 0)`}},onWheelScroll:w=>{i.viewport&&(i.viewport.scrollTop=w)},onDragScroll:w=>{i.viewport&&(i.viewport.scrollTop=v(w))}}):null}),pGe=N.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=Dh(dp,t.__scopeScrollArea),[c,a]=N.useState(),f=N.useRef(null),m=is(e,f,o.onScrollbarXChange);return N.useEffect(()=>{f.current&&a(getComputedStyle(f.current))},[f]),s.jsx(q_e,{"data-orientation":"horizontal",...i,ref:m,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":eF(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.x),onDragScroll:y=>t.onDragScroll(y.x),onWheelScroll:(y,v)=>{if(o.viewport){const w=o.viewport.scrollLeft+y.deltaX;t.onWheelScroll(w),Y_e(w,v)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:hO(c.paddingLeft),paddingEnd:hO(c.paddingRight)}})}})}),gGe=N.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=Dh(dp,t.__scopeScrollArea),[c,a]=N.useState(),f=N.useRef(null),m=is(e,f,o.onScrollbarYChange);return N.useEffect(()=>{f.current&&a(getComputedStyle(f.current))},[f]),s.jsx(q_e,{"data-orientation":"vertical",...i,ref:m,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":eF(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.y),onDragScroll:y=>t.onDragScroll(y.y),onWheelScroll:(y,v)=>{if(o.viewport){const w=o.viewport.scrollTop+y.deltaY;t.onWheelScroll(w),Y_e(w,v)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:hO(c.paddingTop),paddingEnd:hO(c.paddingBottom)}})}})}),[yGe,V_e]=F_e(dp),q_e=N.forwardRef((t,e)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:c,onThumbPointerDown:a,onThumbPositionChange:f,onDragScroll:m,onWheelScroll:y,onResize:v,...w}=t,j=Dh(dp,r),[A,C]=N.useState(null),I=is(e,Q=>C(Q)),M=N.useRef(null),D=N.useRef(""),F=j.viewport,z=n.content-n.viewport,q=go(y),H=go(f),K=tF(v,10);function J(Q){if(M.current){const ee=Q.clientX-M.current.left,oe=Q.clientY-M.current.top;m({x:ee,y:oe})}}return N.useEffect(()=>{const Q=ee=>{const oe=ee.target;(A==null?void 0:A.contains(oe))&&q(ee,z)};return document.addEventListener("wheel",Q,{passive:!1}),()=>document.removeEventListener("wheel",Q,{passive:!1})},[F,A,z,q]),N.useEffect(H,[n,H]),aT(A,K),aT(j.content,K),s.jsx(yGe,{scope:r,scrollbar:A,hasThumb:i,onThumbChange:go(o),onThumbPointerUp:go(c),onThumbPositionChange:H,onThumbPointerDown:go(a),children:s.jsx(cn.div,{...w,ref:I,style:{position:"absolute",...w.style},onPointerDown:Gr(t.onPointerDown,Q=>{Q.button===0&&(Q.target.setPointerCapture(Q.pointerId),M.current=A.getBoundingClientRect(),D.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",j.viewport&&(j.viewport.style.scrollBehavior="auto"),J(Q))}),onPointerMove:Gr(t.onPointerMove,J),onPointerUp:Gr(t.onPointerUp,Q=>{const ee=Q.target;ee.hasPointerCapture(Q.pointerId)&&ee.releasePointerCapture(Q.pointerId),document.body.style.webkitUserSelect=D.current,j.viewport&&(j.viewport.style.scrollBehavior=""),M.current=null})})})}),dO="ScrollAreaThumb",G_e=N.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=V_e(dO,t.__scopeScrollArea);return s.jsx(Pl,{present:r||i.hasThumb,children:s.jsx(xGe,{ref:e,...n})})}),xGe=N.forwardRef((t,e)=>{const{__scopeScrollArea:r,style:n,...i}=t,o=Dh(dO,r),c=V_e(dO,r),{onThumbPositionChange:a}=c,f=is(e,v=>c.onThumbChange(v)),m=N.useRef(void 0),y=tF(()=>{m.current&&(m.current(),m.current=void 0)},100);return N.useEffect(()=>{const v=o.viewport;if(v){const w=()=>{if(y(),!m.current){const j=bGe(v,a);m.current=j,a()}};return a(),v.addEventListener("scroll",w),()=>v.removeEventListener("scroll",w)}},[o.viewport,y,a]),s.jsx(cn.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:Gr(t.onPointerDownCapture,v=>{const j=v.target.getBoundingClientRect(),A=v.clientX-j.left,C=v.clientY-j.top;c.onThumbPointerDown({x:A,y:C})}),onPointerUp:Gr(t.onPointerUp,c.onThumbPointerUp)})});G_e.displayName=dO;var OW="ScrollAreaCorner",H_e=N.forwardRef((t,e)=>{const r=Dh(OW,t.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?s.jsx(vGe,{...t,ref:e}):null});H_e.displayName=OW;var vGe=N.forwardRef((t,e)=>{const{__scopeScrollArea:r,...n}=t,i=Dh(OW,r),[o,c]=N.useState(0),[a,f]=N.useState(0),m=!!(o&&a);return aT(i.scrollbarX,()=>{var v;const y=((v=i.scrollbarX)==null?void 0:v.offsetHeight)||0;i.onCornerHeightChange(y),f(y)}),aT(i.scrollbarY,()=>{var v;const y=((v=i.scrollbarY)==null?void 0:v.offsetWidth)||0;i.onCornerWidthChange(y),c(y)}),m?s.jsx(cn.div,{...n,ref:e,style:{width:o,height:a,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function hO(t){return t?parseInt(t,10):0}function W_e(t,e){const r=t/e;return isNaN(r)?0:r}function eF(t){const e=W_e(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}function _Ge(t,e,r,n="ltr"){const i=eF(r),o=i/2,c=e||o,a=i-c,f=r.scrollbar.paddingStart+c,m=r.scrollbar.size-r.scrollbar.paddingEnd-a,y=r.content-r.viewport,v=n==="ltr"?[0,y]:[y*-1,0];return K_e([f,m],v)(t)}function jse(t,e,r="ltr"){const n=eF(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=e.scrollbar.size-i,c=e.content-e.viewport,a=o-n,f=r==="ltr"?[0,c]:[c*-1,0],m=hN(t,f);return K_e([0,c],[0,a])(m)}function K_e(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 Y_e(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,a=r.top!==o.top;(c||a)&&e(),r=o,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function tF(t,e){const r=go(t),n=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(n.current),[]),N.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}function aT(t,e){const r=go(e);Ho(()=>{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 Z_e=B_e,wGe=z_e,SGe=H_e;const hp=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Z_e,{ref:n,className:Xt("relative overflow-hidden",t),...r,children:[s.jsx(wGe,{className:"h-full w-full rounded-[inherit]",children:e}),s.jsx(X_e,{}),s.jsx(SGe,{})]}));hp.displayName=Z_e.displayName;const X_e=N.forwardRef(({className:t,orientation:e="vertical",...r},n)=>s.jsx(MW,{ref:n,orientation:e,className:Xt("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:s.jsx(G_e,{className:"relative flex-1 rounded-full bg-border"})}));X_e.displayName=MW.displayName;const TGe="/assets/levelup-logo-Eif24dqY.png",jGe="/assets/levelup-logo-icon-C-7iromj.png",EGe="/assets/levelup-logo-mobile-B9skSjUG.png";var HC=t=>t.type==="checkbox",m_=t=>t instanceof Date,pu=t=>t==null;const Q_e=t=>typeof t=="object";var Go=t=>!pu(t)&&!Array.isArray(t)&&Q_e(t)&&!m_(t),J_e=t=>Go(t)&&t.target?HC(t.target)?t.target.checked:t.target.value:t,kGe=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,ebe=(t,e)=>t.has(kGe(e)),AGe=t=>{const e=t.constructor&&t.constructor.prototype;return Go(e)&&e.hasOwnProperty("isPrototypeOf")},FW=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function _l(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(!(FW&&(t instanceof Blob||n))&&(r||Go(t)))if(e=r?[]:{},!r&&!AGe(t))e=t;else for(const i in t)t.hasOwnProperty(i)&&(e[i]=_l(t[i]));else return t;return e}var rF=t=>/^\w*$/.test(t),Bo=t=>t===void 0,BW=t=>Array.isArray(t)?t.filter(Boolean):[],$W=t=>BW(t.replace(/["|']|\]/g,"").split(/\.|\[/)),pn=(t,e,r)=>{if(!e||!Go(t))return r;const n=(rF(e)?[e]:$W(e)).reduce((i,o)=>pu(i)?i:i[o],t);return Bo(n)||n===t?Bo(t[e])?r:t[e]:n},Ad=t=>typeof t=="boolean",Zi=(t,e,r)=>{let n=-1;const i=rF(e)?[e]:$W(e),o=i.length,c=o-1;for(;++nQe.useContext(zW),NGe=t=>{const{children:e,...r}=t;return Qe.createElement(zW.Provider,{value:r},e)};var tbe=(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]!==Tf.all&&(e._proxyFormState[c]=!n||Tf.all),r&&(r[c]=!0),t[c]}});return i};const UW=typeof window<"u"?Qe.useLayoutEffect:Qe.useEffect;function CGe(t){const e=nF(),{control:r=e.control,disabled:n,name:i,exact:o}=t||{},[c,a]=Qe.useState(r._formState),f=Qe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return UW(()=>r._subscribe({name:i,formState:f.current,exact:o,callback:m=>{!n&&a({...r._formState,...m})}}),[i,n,o]),Qe.useEffect(()=>{f.current.isValid&&r._setValid(!0)},[r]),Qe.useMemo(()=>tbe(c,r,f.current,!1),[c,r])}var $m=t=>typeof t=="string",rbe=(t,e,r,n,i)=>$m(t)?(n&&e.watch.add(t),pn(r,t,i)):Array.isArray(t)?t.map(o=>(n&&e.watch.add(o),pn(r,o))):(n&&(e.watchAll=!0),r),kq=t=>pu(t)||!Q_e(t);function hg(t,e,r=new WeakSet){if(kq(t)||kq(e))return t===e;if(m_(t)&&m_(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 a=e[o];if(m_(c)&&m_(a)||Go(c)&&Go(a)||Array.isArray(c)&&Array.isArray(a)?!hg(c,a,r):c!==a)return!1}}return!0}function IGe(t){const e=nF(),{control:r=e.control,name:n,defaultValue:i,disabled:o,exact:c,compute:a}=t||{},f=Qe.useRef(i),m=Qe.useRef(a),y=Qe.useRef(void 0);m.current=a;const v=Qe.useMemo(()=>r._getWatch(n,f.current),[r,n]),[w,j]=Qe.useState(m.current?m.current(v):v);return UW(()=>r._subscribe({name:n,formState:{values:!0},exact:c,callback:A=>{if(!o){const C=rbe(n,r._names,A.values||r._formValues,!1,f.current);if(m.current){const I=m.current(C);hg(I,y.current)||(j(I),y.current=I)}else j(C)}}}),[r,o,n,c]),Qe.useEffect(()=>r._removeUnmounted()),w}function PGe(t){const e=nF(),{name:r,disabled:n,control:i=e.control,shouldUnregister:o,defaultValue:c}=t,a=ebe(i._names.array,r),f=Qe.useMemo(()=>pn(i._formValues,r,pn(i._defaultValues,r,c)),[i,r,c]),m=IGe({control:i,name:r,defaultValue:f,exact:!0}),y=CGe({control:i,name:r,exact:!0}),v=Qe.useRef(t),w=Qe.useRef(i.register(r,{...t.rules,value:m,...Ad(t.disabled)?{disabled:t.disabled}:{}}));v.current=t;const j=Qe.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!pn(y.errors,r)},isDirty:{enumerable:!0,get:()=>!!pn(y.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!pn(y.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!pn(y.validatingFields,r)},error:{enumerable:!0,get:()=>pn(y.errors,r)}}),[y,r]),A=Qe.useCallback(D=>w.current.onChange({target:{value:J_e(D),name:r},type:fO.CHANGE}),[r]),C=Qe.useCallback(()=>w.current.onBlur({target:{value:pn(i._formValues,r),name:r},type:fO.BLUR}),[r,i._formValues]),I=Qe.useCallback(D=>{const F=pn(i._fields,r);F&&D&&(F._f.ref={focus:()=>D.focus&&D.focus(),select:()=>D.select&&D.select(),setCustomValidity:z=>D.setCustomValidity(z),reportValidity:()=>D.reportValidity()})},[i._fields,r]),M=Qe.useMemo(()=>({name:r,value:m,...Ad(n)||y.disabled?{disabled:y.disabled||n}:{},onChange:A,onBlur:C,ref:I}),[r,n,y.disabled,A,C,I,m]);return Qe.useEffect(()=>{const D=i._options.shouldUnregister||o;i.register(r,{...v.current.rules,...Ad(v.current.disabled)?{disabled:v.current.disabled}:{}});const F=(z,q)=>{const H=pn(i._fields,z);H&&H._f&&(H._f.mount=q)};if(F(r,!0),D){const z=_l(pn(i._options.defaultValues,r));Zi(i._defaultValues,r,z),Bo(pn(i._formValues,r))&&Zi(i._formValues,r,z)}return!a&&i.register(r),()=>{(a?D&&!i._state.action:D)?i.unregister(r):F(r,!1)}},[r,i,a,o]),Qe.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),Qe.useMemo(()=>({field:M,formState:y,fieldState:j}),[M,y,j])}const RGe=t=>t.render(PGe(t));var nbe=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},pA=t=>Array.isArray(t)?t:[t],Ese=()=>{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=[]}}},Gu=t=>Go(t)&&!Object.keys(t).length,VW=t=>t.type==="file",jf=t=>typeof t=="function",mO=t=>{if(!FW)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},sbe=t=>t.type==="select-multiple",qW=t=>t.type==="radio",LGe=t=>qW(t)||HC(t),b6=t=>mO(t)&&t.isConnected;function MGe(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if(jf(t[e]))return!0;return!1};function pO(t,e={}){const r=Array.isArray(t);if(Go(t)||r)for(const n in t)Array.isArray(t[n])||Go(t[n])&&!ibe(t[n])?(e[n]=Array.isArray(t[n])?[]:{},pO(t[n],e[n])):pu(t[n])||(e[n]=!0);return e}function abe(t,e,r){const n=Array.isArray(t);if(Go(t)||n)for(const i in t)Array.isArray(t[i])||Go(t[i])&&!ibe(t[i])?Bo(e)||kq(r[i])?r[i]=Array.isArray(t[i])?pO(t[i],[]):{...pO(t[i])}:abe(t[i],pu(e)?{}:e[i],r[i]):r[i]=!hg(t[i],e[i]);return r}var lk=(t,e)=>abe(t,e,pO(e));const kse={value:!1,isValid:!1},Ase={value:!0,isValid:!0};var obe=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&&!Bo(t[0].attributes.value)?Bo(t[0].value)||t[0].value===""?Ase:{value:t[0].value,isValid:!0}:Ase:kse}return kse},lbe=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>Bo(t)?t:e?t===""?NaN:t&&+t:r&&$m(t)?new Date(t):n?n(t):t;const Nse={isValid:!1,value:null};var cbe=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,Nse):Nse;function Cse(t){const e=t.ref;return VW(e)?e.files:qW(e)?cbe(t.refs).value:sbe(e)?[...e.selectedOptions].map(({value:r})=>r):HC(e)?obe(t.refs).value:lbe(Bo(e.value)?t.ref.value:e.value,t)}var OGe=(t,e,r,n)=>{const i={};for(const o of t){const c=pn(e,o);c&&Zi(i,o,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},gO=t=>t instanceof RegExp,ck=t=>Bo(t)?t:gO(t)?t.source:Go(t)?gO(t.value)?t.value.source:t.value:t,Ise=t=>({isOnSubmit:!t||t===Tf.onSubmit,isOnBlur:t===Tf.onBlur,isOnChange:t===Tf.onChange,isOnAll:t===Tf.all,isOnTouch:t===Tf.onTouched});const Pse="AsyncFunction";var FGe=t=>!!t&&!!t.validate&&!!(jf(t.validate)&&t.validate.constructor.name===Pse||Go(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===Pse)),BGe=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),Rse=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const gA=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const o=pn(t,i);if(o){const{_f:c,...a}=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(gA(a,e))break}else if(Go(a)&&gA(a,e))break}}};function Lse(t,e,r){const n=pn(t,r);if(n||rF(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const o=i.join("."),c=pn(e,o),a=pn(t,o);if(c&&!Array.isArray(c)&&r!==o)return{name:r};if(a&&a.type)return{name:o,error:a};if(a&&a.root&&a.root.type)return{name:`${o}.root`,error:a.root};i.pop()}return{name:r}}var $Ge=(t,e,r,n)=>{r(t);const{name:i,...o}=t;return Gu(o)||Object.keys(o).length>=Object.keys(e).length||Object.keys(o).find(c=>e[c]===(!n||Tf.all))},zGe=(t,e,r)=>!t||!e||t===e||pA(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n))),UGe=(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,VGe=(t,e)=>!BW(pn(t,e)).length&&el(t,e),qGe=(t,e,r)=>{const n=pA(pn(t,r));return Zi(n,"root",e[r]),Zi(t,r,n),t},GM=t=>$m(t);function Mse(t,e,r="validate"){if(GM(t)||Array.isArray(t)&&t.every(GM)||Ad(t)&&!t)return{type:r,message:GM(t)?t:"",ref:e}}var u1=t=>Go(t)&&!gO(t)?t:{value:t,message:""},Dse=async(t,e,r,n,i,o)=>{const{ref:c,refs:a,required:f,maxLength:m,minLength:y,min:v,max:w,pattern:j,validate:A,name:C,valueAsNumber:I,mount:M}=t._f,D=pn(r,C);if(!M||e.has(C))return{};const F=a?a[0]:c,z=de=>{i&&F.reportValidity&&(F.setCustomValidity(Ad(de)?"":de||""),F.reportValidity())},q={},H=qW(c),K=HC(c),J=H||K,Q=(I||VW(c))&&Bo(c.value)&&Bo(D)||mO(c)&&c.value===""||D===""||Array.isArray(D)&&!D.length,ee=nbe.bind(null,C,n,q),oe=(de,ye,we,Le=Yp.maxLength,Se=Yp.minLength)=>{const ve=de?ye:we;q[C]={type:de?Le:Se,message:ve,ref:c,...ee(de?Le:Se,ve)}};if(o?!Array.isArray(D)||!D.length:f&&(!J&&(Q||pu(D))||Ad(D)&&!D||K&&!obe(a).isValid||H&&!cbe(a).isValid)){const{value:de,message:ye}=GM(f)?{value:!!f,message:f}:u1(f);if(de&&(q[C]={type:Yp.required,message:ye,ref:F,...ee(Yp.required,ye)},!n))return z(ye),q}if(!Q&&(!pu(v)||!pu(w))){let de,ye;const we=u1(w),Le=u1(v);if(!pu(D)&&!isNaN(D)){const Se=c.valueAsNumber||D&&+D;pu(we.value)||(de=Se>we.value),pu(Le.value)||(ye=Senew Date(new Date().toDateString()+" "+Pe),me=c.type=="time",ke=c.type=="week";$m(we.value)&&D&&(de=me?ve(D)>ve(we.value):ke?D>we.value:Se>new Date(we.value)),$m(Le.value)&&D&&(ye=me?ve(D)+de.value,Le=!pu(ye.value)&&D.length<+ye.value;if((we||Le)&&(oe(we,de.message,ye.message),!n))return z(q[C].message),q}if(j&&!Q&&$m(D)){const{value:de,message:ye}=u1(j);if(gO(de)&&!D.match(de)&&(q[C]={type:Yp.pattern,message:ye,ref:c,...ee(Yp.pattern,ye)},!n))return z(ye),q}if(A){if(jf(A)){const de=await A(D,r),ye=Mse(de,F);if(ye&&(q[C]={...ye,...ee(Yp.validate,ye.message)},!n))return z(ye.message),q}else if(Go(A)){let de={};for(const ye in A){if(!Gu(de)&&!n)break;const we=Mse(await A[ye](D,r),F,ye);we&&(de={...we,...ee(ye,we.message)},z(we.message),n&&(q[C]=de))}if(!Gu(de)&&(q[C]={ref:F,...de},!n))return q}}return z(!0),q};const GGe={mode:Tf.onSubmit,reValidateMode:Tf.onChange,shouldFocusError:!0};function HGe(t={}){let e={...GGe,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:jf(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=Go(e.defaultValues)||Go(e.values)?_l(e.defaultValues||e.values)||{}:{},o=e.shouldUnregister?{}:_l(i),c={action:!1,mount:!1,watch:!1},a={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let v={...y};const w={array:Ese(),state:Ese()},j=e.criteriaMode===Tf.all,A=tt=>Tt=>{clearTimeout(m),m=setTimeout(tt,Tt)},C=async tt=>{if(!e.disabled&&(y.isValid||v.isValid||tt)){const Tt=e.resolver?Gu((await K()).errors):await Q(n,!0);Tt!==r.isValid&&w.state.next({isValid:Tt})}},I=(tt,Tt)=>{!e.disabled&&(y.isValidating||y.validatingFields||v.isValidating||v.validatingFields)&&((tt||Array.from(a.mount)).forEach(Zt=>{Zt&&(Tt?Zi(r.validatingFields,Zt,Tt):el(r.validatingFields,Zt))}),w.state.next({validatingFields:r.validatingFields,isValidating:!Gu(r.validatingFields)}))},M=(tt,Tt=[],Zt,ar,Wt=!0,Kt=!0)=>{if(ar&&Zt&&!e.disabled){if(c.action=!0,Kt&&Array.isArray(pn(n,tt))){const At=Zt(pn(n,tt),ar.argA,ar.argB);Wt&&Zi(n,tt,At)}if(Kt&&Array.isArray(pn(r.errors,tt))){const At=Zt(pn(r.errors,tt),ar.argA,ar.argB);Wt&&Zi(r.errors,tt,At),VGe(r.errors,tt)}if((y.touchedFields||v.touchedFields)&&Kt&&Array.isArray(pn(r.touchedFields,tt))){const At=Zt(pn(r.touchedFields,tt),ar.argA,ar.argB);Wt&&Zi(r.touchedFields,tt,At)}(y.dirtyFields||v.dirtyFields)&&(r.dirtyFields=lk(i,o)),w.state.next({name:tt,isDirty:oe(tt,Tt),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Zi(o,tt,Tt)},D=(tt,Tt)=>{Zi(r.errors,tt,Tt),w.state.next({errors:r.errors})},F=tt=>{r.errors=tt,w.state.next({errors:r.errors,isValid:!1})},z=(tt,Tt,Zt,ar)=>{const Wt=pn(n,tt);if(Wt){const Kt=pn(o,tt,Bo(Zt)?pn(i,tt):Zt);Bo(Kt)||ar&&ar.defaultChecked||Tt?Zi(o,tt,Tt?Kt:Cse(Wt._f)):we(tt,Kt),c.mount&&C()}},q=(tt,Tt,Zt,ar,Wt)=>{let Kt=!1,At=!1;const pr={name:tt};if(!e.disabled){if(!Zt||ar){(y.isDirty||v.isDirty)&&(At=r.isDirty,r.isDirty=pr.isDirty=oe(),Kt=At!==pr.isDirty);const yn=hg(pn(i,tt),Tt);At=!!pn(r.dirtyFields,tt),yn?el(r.dirtyFields,tt):Zi(r.dirtyFields,tt,!0),pr.dirtyFields=r.dirtyFields,Kt=Kt||(y.dirtyFields||v.dirtyFields)&&At!==!yn}if(Zt){const yn=pn(r.touchedFields,tt);yn||(Zi(r.touchedFields,tt,Zt),pr.touchedFields=r.touchedFields,Kt=Kt||(y.touchedFields||v.touchedFields)&&yn!==Zt)}Kt&&Wt&&w.state.next(pr)}return Kt?pr:{}},H=(tt,Tt,Zt,ar)=>{const Wt=pn(r.errors,tt),Kt=(y.isValid||v.isValid)&&Ad(Tt)&&r.isValid!==Tt;if(e.delayError&&Zt?(f=A(()=>D(tt,Zt)),f(e.delayError)):(clearTimeout(m),f=null,Zt?Zi(r.errors,tt,Zt):el(r.errors,tt)),(Zt?!hg(Wt,Zt):Wt)||!Gu(ar)||Kt){const At={...ar,...Kt&&Ad(Tt)?{isValid:Tt}:{},errors:r.errors,name:tt};r={...r,...At},w.state.next(At)}},K=async tt=>{I(tt,!0);const Tt=await e.resolver(o,e.context,OGe(tt||a.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return I(tt),Tt},J=async tt=>{const{errors:Tt}=await K(tt);if(tt)for(const Zt of tt){const ar=pn(Tt,Zt);ar?Zi(r.errors,Zt,ar):el(r.errors,Zt)}else r.errors=Tt;return Tt},Q=async(tt,Tt,Zt={valid:!0})=>{for(const ar in tt){const Wt=tt[ar];if(Wt){const{_f:Kt,...At}=Wt;if(Kt){const pr=a.array.has(Kt.name),yn=Wt._f&&FGe(Wt._f);yn&&y.validatingFields&&I([ar],!0);const Gn=await Dse(Wt,a.disabled,o,j,e.shouldUseNativeValidation&&!Tt,pr);if(yn&&y.validatingFields&&I([ar]),Gn[Kt.name]&&(Zt.valid=!1,Tt))break;!Tt&&(pn(Gn,Kt.name)?pr?qGe(r.errors,Gn,Kt.name):Zi(r.errors,Kt.name,Gn[Kt.name]):el(r.errors,Kt.name))}!Gu(At)&&await Q(At,Tt,Zt)}}return Zt.valid},ee=()=>{for(const tt of a.unMount){const Tt=pn(n,tt);Tt&&(Tt._f.refs?Tt._f.refs.every(Zt=>!b6(Zt)):!b6(Tt._f.ref))&&yt(tt)}a.unMount=new Set},oe=(tt,Tt)=>!e.disabled&&(tt&&Tt&&Zi(o,tt,Tt),!hg(Pe(),i)),de=(tt,Tt,Zt)=>rbe(tt,a,{...c.mount?o:Bo(Tt)?i:$m(tt)?{[tt]:Tt}:Tt},Zt,Tt),ye=tt=>BW(pn(c.mount?o:i,tt,e.shouldUnregister?pn(i,tt,[]):[])),we=(tt,Tt,Zt={})=>{const ar=pn(n,tt);let Wt=Tt;if(ar){const Kt=ar._f;Kt&&(!Kt.disabled&&Zi(o,tt,lbe(Tt,Kt)),Wt=mO(Kt.ref)&&pu(Tt)?"":Tt,sbe(Kt.ref)?[...Kt.ref.options].forEach(At=>At.selected=Wt.includes(At.value)):Kt.refs?HC(Kt.ref)?Kt.refs.forEach(At=>{(!At.defaultChecked||!At.disabled)&&(Array.isArray(Wt)?At.checked=!!Wt.find(pr=>pr===At.value):At.checked=Wt===At.value||!!Wt)}):Kt.refs.forEach(At=>At.checked=At.value===Wt):VW(Kt.ref)?Kt.ref.value="":(Kt.ref.value=Wt,Kt.ref.type||w.state.next({name:tt,values:_l(o)})))}(Zt.shouldDirty||Zt.shouldTouch)&&q(tt,Wt,Zt.shouldTouch,Zt.shouldDirty,!0),Zt.shouldValidate&&ke(tt)},Le=(tt,Tt,Zt)=>{for(const ar in Tt){if(!Tt.hasOwnProperty(ar))return;const Wt=Tt[ar],Kt=tt+"."+ar,At=pn(n,Kt);(a.array.has(tt)||Go(Wt)||At&&!At._f)&&!m_(Wt)?Le(Kt,Wt,Zt):we(Kt,Wt,Zt)}},Se=(tt,Tt,Zt={})=>{const ar=pn(n,tt),Wt=a.array.has(tt),Kt=_l(Tt);Zi(o,tt,Kt),Wt?(w.array.next({name:tt,values:_l(o)}),(y.isDirty||y.dirtyFields||v.isDirty||v.dirtyFields)&&Zt.shouldDirty&&w.state.next({name:tt,dirtyFields:lk(i,o),isDirty:oe(tt,Kt)})):ar&&!ar._f&&!pu(Kt)?Le(tt,Kt,Zt):we(tt,Kt,Zt),Rse(tt,a)&&w.state.next({...r,name:tt}),w.state.next({name:c.mount?tt:void 0,values:_l(o)})},ve=async tt=>{c.mount=!0;const Tt=tt.target;let Zt=Tt.name,ar=!0;const Wt=pn(n,Zt),Kt=yn=>{ar=Number.isNaN(yn)||m_(yn)&&isNaN(yn.getTime())||hg(yn,pn(o,Zt,yn))},At=Ise(e.mode),pr=Ise(e.reValidateMode);if(Wt){let yn,Gn;const Bn=Tt.type?Cse(Wt._f):J_e(tt),Rs=tt.type===fO.BLUR||tt.type===fO.FOCUS_OUT,sa=!BGe(Wt._f)&&!e.resolver&&!pn(r.errors,Zt)&&!Wt._f.deps||UGe(Rs,pn(r.touchedFields,Zt),r.isSubmitted,pr,At),gs=Rse(Zt,a,Rs);Zi(o,Zt,Bn),Rs?(Wt._f.onBlur&&Wt._f.onBlur(tt),f&&f(0)):Wt._f.onChange&&Wt._f.onChange(tt);const zi=q(Zt,Bn,Rs),Ir=!Gu(zi)||gs;if(!Rs&&w.state.next({name:Zt,type:tt.type,values:_l(o)}),sa)return(y.isValid||v.isValid)&&(e.mode==="onBlur"?Rs&&C():Rs||C()),Ir&&w.state.next({name:Zt,...gs?{}:zi});if(!Rs&&gs&&w.state.next({...r}),e.resolver){const{errors:$n}=await K([Zt]);if(Kt(Bn),ar){const Si=Lse(r.errors,n,Zt),oi=Lse($n,n,Si.name||Zt);yn=oi.error,Zt=oi.name,Gn=Gu($n)}}else I([Zt],!0),yn=(await Dse(Wt,a.disabled,o,j,e.shouldUseNativeValidation))[Zt],I([Zt]),Kt(Bn),ar&&(yn?Gn=!1:(y.isValid||v.isValid)&&(Gn=await Q(n,!0)));ar&&(Wt._f.deps&&ke(Wt._f.deps),H(Zt,Gn,yn,zi))}},me=(tt,Tt)=>{if(pn(r.errors,Tt)&&tt.focus)return tt.focus(),1},ke=async(tt,Tt={})=>{let Zt,ar;const Wt=pA(tt);if(e.resolver){const Kt=await J(Bo(tt)?tt:Wt);Zt=Gu(Kt),ar=tt?!Wt.some(At=>pn(Kt,At)):Zt}else tt?(ar=(await Promise.all(Wt.map(async Kt=>{const At=pn(n,Kt);return await Q(At&&At._f?{[Kt]:At}:At)}))).every(Boolean),!(!ar&&!r.isValid)&&C()):ar=Zt=await Q(n);return w.state.next({...!$m(tt)||(y.isValid||v.isValid)&&Zt!==r.isValid?{}:{name:tt},...e.resolver||!tt?{isValid:Zt}:{},errors:r.errors}),Tt.shouldFocus&&!ar&&gA(n,me,tt?Wt:a.mount),ar},Pe=tt=>{const Tt={...c.mount?o:i};return Bo(tt)?Tt:$m(tt)?pn(Tt,tt):tt.map(Zt=>pn(Tt,Zt))},Ee=(tt,Tt)=>({invalid:!!pn((Tt||r).errors,tt),isDirty:!!pn((Tt||r).dirtyFields,tt),error:pn((Tt||r).errors,tt),isValidating:!!pn(r.validatingFields,tt),isTouched:!!pn((Tt||r).touchedFields,tt)}),xe=tt=>{tt&&pA(tt).forEach(Tt=>el(r.errors,Tt)),w.state.next({errors:tt?r.errors:{}})},Ue=(tt,Tt,Zt)=>{const ar=(pn(n,tt,{_f:{}})._f||{}).ref,Wt=pn(r.errors,tt)||{},{ref:Kt,message:At,type:pr,...yn}=Wt;Zi(r.errors,tt,{...yn,...Tt,ref:ar}),w.state.next({name:tt,errors:r.errors,isValid:!1}),Zt&&Zt.shouldFocus&&ar&&ar.focus&&ar.focus()},Ze=(tt,Tt)=>jf(tt)?w.state.subscribe({next:Zt=>"values"in Zt&&tt(de(void 0,Tt),Zt)}):de(tt,Tt,!0),lt=tt=>w.state.subscribe({next:Tt=>{zGe(tt.name,Tt.name,tt.exact)&&$Ge(Tt,tt.formState||y,$r,tt.reRenderRoot)&&tt.callback({values:{...o},...r,...Tt,defaultValues:i})}}).unsubscribe,wt=tt=>(c.mount=!0,v={...v,...tt.formState},lt({...tt,formState:v})),yt=(tt,Tt={})=>{for(const Zt of tt?pA(tt):a.mount)a.mount.delete(Zt),a.array.delete(Zt),Tt.keepValue||(el(n,Zt),el(o,Zt)),!Tt.keepError&&el(r.errors,Zt),!Tt.keepDirty&&el(r.dirtyFields,Zt),!Tt.keepTouched&&el(r.touchedFields,Zt),!Tt.keepIsValidating&&el(r.validatingFields,Zt),!e.shouldUnregister&&!Tt.keepDefaultValue&&el(i,Zt);w.state.next({values:_l(o)}),w.state.next({...r,...Tt.keepDirty?{isDirty:oe()}:{}}),!Tt.keepIsValid&&C()},gt=({disabled:tt,name:Tt})=>{(Ad(tt)&&c.mount||tt||a.disabled.has(Tt))&&(tt?a.disabled.add(Tt):a.disabled.delete(Tt))},ft=(tt,Tt={})=>{let Zt=pn(n,tt);const ar=Ad(Tt.disabled)||Ad(e.disabled);return Zi(n,tt,{...Zt||{},_f:{...Zt&&Zt._f?Zt._f:{ref:{name:tt}},name:tt,mount:!0,...Tt}}),a.mount.add(tt),Zt?gt({disabled:Ad(Tt.disabled)?Tt.disabled:e.disabled,name:tt}):z(tt,!0,Tt.value),{...ar?{disabled:Tt.disabled||e.disabled}:{},...e.progressive?{required:!!Tt.required,min:ck(Tt.min),max:ck(Tt.max),minLength:ck(Tt.minLength),maxLength:ck(Tt.maxLength),pattern:ck(Tt.pattern)}:{},name:tt,onChange:ve,onBlur:ve,ref:Wt=>{if(Wt){ft(tt,Tt),Zt=pn(n,tt);const Kt=Bo(Wt.value)&&Wt.querySelectorAll&&Wt.querySelectorAll("input,select,textarea")[0]||Wt,At=LGe(Kt),pr=Zt._f.refs||[];if(At?pr.find(yn=>yn===Kt):Kt===Zt._f.ref)return;Zi(n,tt,{_f:{...Zt._f,...At?{refs:[...pr.filter(b6),Kt,...Array.isArray(pn(i,tt))?[{}]:[]],ref:{type:Kt.type,name:tt}}:{ref:Kt}}}),z(tt,!1,void 0,Kt)}else Zt=pn(n,tt,{}),Zt._f&&(Zt._f.mount=!1),(e.shouldUnregister||Tt.shouldUnregister)&&!(ebe(a.array,tt)&&c.action)&&a.unMount.add(tt)}}},kt=()=>e.shouldFocusError&&gA(n,me,a.mount),Vt=tt=>{Ad(tt)&&(w.state.next({disabled:tt}),gA(n,(Tt,Zt)=>{const ar=pn(n,Zt);ar&&(Tt.disabled=ar._f.disabled||tt,Array.isArray(ar._f.refs)&&ar._f.refs.forEach(Wt=>{Wt.disabled=ar._f.disabled||tt}))},0,!1))},xt=(tt,Tt)=>async Zt=>{let ar;Zt&&(Zt.preventDefault&&Zt.preventDefault(),Zt.persist&&Zt.persist());let Wt=_l(o);if(w.state.next({isSubmitting:!0}),e.resolver){const{errors:Kt,values:At}=await K();r.errors=Kt,Wt=_l(At)}else await Q(n);if(a.disabled.size)for(const Kt of a.disabled)el(Wt,Kt);if(el(r.errors,"root"),Gu(r.errors)){w.state.next({errors:{}});try{await tt(Wt,Zt)}catch(Kt){ar=Kt}}else Tt&&await Tt({...r.errors},Zt),kt(),setTimeout(kt);if(w.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Gu(r.errors)&&!ar,submitCount:r.submitCount+1,errors:r.errors}),ar)throw ar},or=(tt,Tt={})=>{pn(n,tt)&&(Bo(Tt.defaultValue)?Se(tt,_l(pn(i,tt))):(Se(tt,Tt.defaultValue),Zi(i,tt,_l(Tt.defaultValue))),Tt.keepTouched||el(r.touchedFields,tt),Tt.keepDirty||(el(r.dirtyFields,tt),r.isDirty=Tt.defaultValue?oe(tt,_l(pn(i,tt))):oe()),Tt.keepError||(el(r.errors,tt),y.isValid&&C()),w.state.next({...r}))},Tr=(tt,Tt={})=>{const Zt=tt?_l(tt):i,ar=_l(Zt),Wt=Gu(tt),Kt=Wt?i:ar;if(Tt.keepDefaultValues||(i=Zt),!Tt.keepValues){if(Tt.keepDirtyValues){const At=new Set([...a.mount,...Object.keys(lk(i,o))]);for(const pr of Array.from(At))pn(r.dirtyFields,pr)?Zi(Kt,pr,pn(o,pr)):Se(pr,pn(Kt,pr))}else{if(FW&&Bo(tt))for(const At of a.mount){const pr=pn(n,At);if(pr&&pr._f){const yn=Array.isArray(pr._f.refs)?pr._f.refs[0]:pr._f.ref;if(mO(yn)){const Gn=yn.closest("form");if(Gn){Gn.reset();break}}}}if(Tt.keepFieldsRef)for(const At of a.mount)Se(At,pn(Kt,At));else n={}}o=e.shouldUnregister?Tt.keepDefaultValues?_l(i):{}:_l(Kt),w.array.next({values:{...Kt}}),w.state.next({values:{...Kt}})}a={mount:Tt.keepDirtyValues?a.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!y.isValid||!!Tt.keepIsValid||!!Tt.keepDirtyValues,c.watch=!!e.shouldUnregister,w.state.next({submitCount:Tt.keepSubmitCount?r.submitCount:0,isDirty:Wt?!1:Tt.keepDirty?r.isDirty:!!(Tt.keepDefaultValues&&!hg(tt,i)),isSubmitted:Tt.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Wt?{}:Tt.keepDirtyValues?Tt.keepDefaultValues&&o?lk(i,o):r.dirtyFields:Tt.keepDefaultValues&&tt?lk(i,tt):Tt.keepDirty?r.dirtyFields:{},touchedFields:Tt.keepTouched?r.touchedFields:{},errors:Tt.keepErrors?r.errors:{},isSubmitSuccessful:Tt.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},rn=(tt,Tt)=>Tr(jf(tt)?tt(o):tt,Tt),Lr=(tt,Tt={})=>{const Zt=pn(n,tt),ar=Zt&&Zt._f;if(ar){const Wt=ar.refs?ar.refs[0]:ar.ref;Wt.focus&&(Wt.focus(),Tt.shouldSelect&&jf(Wt.select)&&Wt.select())}},$r=tt=>{r={...r,...tt}},Nn={control:{register:ft,unregister:yt,getFieldState:Ee,handleSubmit:xt,setError:Ue,_subscribe:lt,_runSchema:K,_focusError:kt,_getWatch:de,_getDirty:oe,_setValid:C,_setFieldArray:M,_setDisabledField:gt,_setErrors:F,_getFieldArray:ye,_reset:Tr,_resetDefaultValues:()=>jf(e.defaultValues)&&e.defaultValues().then(tt=>{rn(tt,e.resetOptions),w.state.next({isLoading:!1})}),_removeUnmounted:ee,_disableForm:Vt,_subjects:w,_proxyFormState:y,get _fields(){return n},get _formValues(){return o},get _state(){return c},set _state(tt){c=tt},get _defaultValues(){return i},get _names(){return a},set _names(tt){a=tt},get _formState(){return r},get _options(){return e},set _options(tt){e={...e,...tt}}},subscribe:wt,trigger:ke,register:ft,handleSubmit:xt,watch:Ze,setValue:Se,getValues:Pe,reset:rn,resetField:or,clearErrors:xe,unregister:yt,setError:Ue,setFocus:Lr,getFieldState:Ee};return{...Nn,formControl:Nn}}function GW(t={}){const e=Qe.useRef(void 0),r=Qe.useRef(void 0),[n,i]=Qe.useState({isDirty:!1,isValidating:!1,isLoading:jf(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:jf(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!jf(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:c,...a}=HGe(t);e.current={...a,formState:n}}const o=e.current.control;return o._options=t,UW(()=>{const c=o._subscribe({formState:o._proxyFormState,callback:()=>i({...o._formState}),reRenderRoot:!0});return i(a=>({...a,isReady:!0})),o._formState.isReady=!0,c},[o]),Qe.useEffect(()=>o._disableForm(t.disabled),[o,t.disabled]),Qe.useEffect(()=>{t.mode&&(o._options.mode=t.mode),t.reValidateMode&&(o._options.reValidateMode=t.reValidateMode)},[o,t.mode,t.reValidateMode]),Qe.useEffect(()=>{t.errors&&(o._setErrors(t.errors),o._focusError())},[o,t.errors]),Qe.useEffect(()=>{t.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,t.shouldUnregister]),Qe.useEffect(()=>{if(o._proxyFormState.isDirty){const c=o._getDirty();c!==n.isDirty&&o._subjects.state.next({isDirty:c})}},[o,n.isDirty]),Qe.useEffect(()=>{t.values&&!hg(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]),Qe.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=tbe(n,o),e.current}const Ose=(t,e,r)=>{if(t&&"reportValidity"in t){const n=pn(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},ube=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?Ose(n.ref,r,t):n.refs&&n.refs.forEach(i=>Ose(i,r,t))}},WGe=(t,e)=>{e.shouldUseNativeValidation&&ube(t,e);const r={};for(const n in t){const i=pn(e.fields,n),o=Object.assign(t[n]||{},{ref:i&&i.ref});if(KGe(e.names||Object.keys(t),n)){const c=Object.assign({},pn(r,n));Zi(c,"root",o),Zi(r,n,c)}else Zi(r,n,o)}return r},KGe=(t,e)=>t.some(r=>r.startsWith(e+"."));var YGe=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 a=n.unionErrors[0].errors[0];r[c]={message:a.message,type:a.code}}else r[c]={message:o,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(y){return y.errors.forEach(function(v){return t.push(v)})}),e){var f=r[c].types,m=f&&f[n.code];r[c]=nbe(c,e,r,i,m?[].concat(m,n.message):n.message)}t.shift()}return r},HW=function(t,e,r){return r===void 0&&(r={}),function(n,i,o){try{return Promise.resolve(function(c,a){try{var f=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(m){return o.shouldUseNativeValidation&&ube({},o),{errors:{},values:r.raw?n:m}})}catch(m){return a(m)}return f&&f.then?f.then(void 0,a):f}(0,function(c){if(function(a){return Array.isArray(a==null?void 0:a.errors)}(c))return{values:{},errors:WGe(YGe(c.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw c}))}catch(c){return Promise.reject(c)}}},Fse;function Cr(t,e,r){function n(a,f){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:f,constr:c,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,f);const m=c.prototype,y=Object.keys(m);for(let v=0;v{var f,m;return r!=null&&r.Parent&&a instanceof r.Parent?!0:(m=(f=a==null?void 0:a._zod)==null?void 0:f.traits)==null?void 0:m.has(t)}}),Object.defineProperty(c,"name",{value:t}),c}class wS extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class dbe extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Fse=globalThis).__zod_globalConfig??(Fse.__zod_globalConfig={});const WW=globalThis.__zod_globalConfig;function Rg(t){return WW}function hbe(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 Aq(t,e){return typeof e=="bigint"?e.toString():e}function KW(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function YW(t){return t==null}function ZW(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ZGe(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 yO(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const QGe=KW(()=>{var t;if(WW.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 oT(t){if(yO(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const r=e.prototype;return!(yO(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function mbe(t){return oT(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const JGe=new Set(["string","number","symbol"]);function lT(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b0(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 Yn(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 e7e(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const t7e={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 r7e(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=_0(t._zod.def,{get shape(){const c={};for(const a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(c[a]=r.shape[a])}return vb(this,"shape",c),c},checks:[]});return b0(t,o)}function n7e(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=_0(t._zod.def,{get shape(){const c={...t._zod.def.shape};for(const a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete c[a]}return vb(this,"shape",c),c},checks:[]});return b0(t,o)}function s7e(t,e){if(!oT(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=_0(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return vb(this,"shape",o),o}});return b0(t,i)}function i7e(t,e){if(!oT(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=_0(t._zod.def,{get shape(){const n={...t._zod.def.shape,...e};return vb(this,"shape",n),n}});return b0(t,r)}function a7e(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=_0(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return vb(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return b0(t,r)}function o7e(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=_0(e._zod.def,{get shape(){const a=e._zod.def.shape,f={...a};if(r)for(const m in r){if(!(m in a))throw new Error(`Unrecognized key: "${m}"`);r[m]&&(f[m]=t?new t({type:"optional",innerType:a[m]}):a[m])}else for(const m in a)f[m]=t?new t({type:"optional",innerType:a[m]}):a[m];return vb(this,"shape",f),f},checks:[]});return b0(e,c)}function l7e(t,e,r){const n=_0(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 vb(this,"shape",o),o}});return b0(e,n)}function X1(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 SL(t){return typeof t=="string"?t:t==null?void 0:t.message}function Lg(t,e,r){var f,m,y,v,w,j;const n=t.message?t.message:SL((y=(m=(f=t.inst)==null?void 0:f._zod.def)==null?void 0:m.error)==null?void 0:y.call(m,t))??SL((v=e==null?void 0:e.error)==null?void 0:v.call(e,t))??SL((w=r.customError)==null?void 0:w.call(r,t))??SL((j=r.localeError)==null?void 0:j.call(r,t))??"Invalid input",{inst:i,continue:o,input:c,...a}=t;return a.path??(a.path=[]),a.message=n,e!=null&&e.reportInput&&(a.input=c),a}function XW(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function fN(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const pbe=(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,Aq,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gbe=Cr("$ZodError",pbe),ybe=Cr("$ZodError",pbe,{Parent:Error});function u7e(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 d7e(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(a=>n({issues:a},[...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 a=[...o,...c.path];if(a.length===0)r._errors.push(e(c));else{let f=r,m=0;for(;m(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 wS;if(c.issues.length){const a=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Lg(f,o,Rg())));throw fbe(a,i==null?void 0:i.callee),a}return c.value},JW=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 a=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Lg(f,o,Rg())));throw fbe(a,i==null?void 0:i.callee),a}return c.value},sF=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 wS;return o.issues.length?{success:!1,error:new(t??gbe)(o.issues.map(c=>Lg(c,i,Rg())))}:{success:!0,data:o.value}},h7e=sF(ybe),iF=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=>Lg(c,i,Rg())))}:{success:!0,data:o.value}},f7e=iF(ybe),m7e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return QW(t)(e,r,i)},p7e=t=>(e,r,n)=>QW(t)(e,r,n),g7e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return JW(t)(e,r,i)},y7e=t=>async(e,r,n)=>JW(t)(e,r,n),x7e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return sF(t)(e,r,i)},v7e=t=>(e,r,n)=>sF(t)(e,r,n),_7e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return iF(t)(e,r,i)},b7e=t=>async(e,r,n)=>iF(t)(e,r,n),w7e=/^[cC][0-9a-z]{6,}$/,S7e=/^[0-9a-z]+$/,T7e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,j7e=/^[0-9a-vA-V]{20}$/,E7e=/^[A-Za-z0-9]{27}$/,k7e=/^[a-zA-Z0-9_-]{21}$/,A7e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,N7e=/^([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})$/,zse=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)$/,C7e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,I7e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function P7e(){return new RegExp(I7e,"u")}const R7e=/^(?:(?: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])$/,L7e=/^(([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}|:))$/,M7e=/^((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])$/,D7e=/^(([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])$/,O7e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xbe=/^[A-Za-z0-9_-]*$/,F7e=/^https?$/,B7e=/^\+[1-9]\d{6,14}$/,vbe="(?:(?:\\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])))",$7e=new RegExp(`^${vbe}$`);function _be(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 z7e(t){return new RegExp(`^${_be(t)}$`)}function U7e(t){const e=_be({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(`^${vbe}T(?:${n})$`)}const V7e=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}$`)},q7e=/^-?\d+$/,bbe=/^-?\d+(?:\.\d+)?$/,G7e=/^(?:true|false)$/i,H7e=/^[^A-Z]*$/,W7e=/^[^a-z]*$/,ad=Cr("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),wbe={number:"number",bigint:"bigint",object:"date"},Sbe=Cr("$ZodCheckLessThan",(t,e)=>{ad.init(t,e);const r=wbe[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{ad.init(t,e);const r=wbe[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})}}),K7e=Cr("$ZodCheckMultipleOf",(t,e)=>{ad.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):ZGe(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})}}),Y7e=Cr("$ZodCheckNumberFormat",(t,e)=>{var c;ad.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]=t7e[e.format];t._zod.onattach.push(a=>{const f=a._zod.bag;f.format=e.format,f.minimum=i,f.maximum=o,r&&(f.pattern=q7e)}),t._zod.check=a=>{const f=a.value;if(r){if(!Number.isInteger(f)){a.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:f,inst:t});return}if(!Number.isSafeInteger(f)){f>0?a.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}):a.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&&a.issues.push({origin:"number",input:f,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}}),Z7e=Cr("$ZodCheckMaxLength",(t,e)=>{var r;ad.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!YW(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=XW(i);n.issues.push({origin:c,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),X7e=Cr("$ZodCheckMinLength",(t,e)=>{var r;ad.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!YW(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=XW(i);n.issues.push({origin:c,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),Q7e=Cr("$ZodCheckLengthEquals",(t,e)=>{var r;ad.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!YW(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=XW(i),a=o>e.length;n.issues.push({origin:c,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),aF=Cr("$ZodCheckStringFormat",(t,e)=>{var r,n;ad.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=()=>{})}),J7e=Cr("$ZodCheckRegex",(t,e)=>{aF.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})}}),eHe=Cr("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=H7e),aF.init(t,e)}),tHe=Cr("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=W7e),aF.init(t,e)}),rHe=Cr("$ZodCheckIncludes",(t,e)=>{ad.init(t,e);const r=lT(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})}}),nHe=Cr("$ZodCheckStartsWith",(t,e)=>{ad.init(t,e);const r=new RegExp(`^${lT(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})}}),sHe=Cr("$ZodCheckEndsWith",(t,e)=>{ad.init(t,e);const r=new RegExp(`.*${lT(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})}}),iHe=Cr("$ZodCheckOverwrite",(t,e)=>{ad.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class aHe{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 oHe={major:4,minor:4,patch:3},wo=Cr("$ZodType",(t,e)=>{var i;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=oHe;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=(a,f,m)=>{let y=X1(a),v;for(const w of f){if(w._zod.def.when){if(c7e(a)||!w._zod.def.when(a))continue}else if(y)continue;const j=a.issues.length,A=w._zod.check(a);if(A instanceof Promise&&(m==null?void 0:m.async)===!1)throw new wS;if(v||A instanceof Promise)v=(v??Promise.resolve()).then(async()=>{await A,a.issues.length!==j&&(y||(y=X1(a,j)))});else{if(a.issues.length===j)continue;y||(y=X1(a,j))}}return v?v.then(()=>a):a},c=(a,f,m)=>{if(X1(a))return a.aborted=!0,a;const y=o(f,n,m);if(y instanceof Promise){if(m.async===!1)throw new wS;return y.then(v=>t._zod.parse(v,m))}return t._zod.parse(y,m)};t._zod.run=(a,f)=>{if(f.skipChecks)return t._zod.parse(a,f);if(f.direction==="backward"){const y=t._zod.parse({value:a.value,issues:[]},{...f,skipChecks:!0});return y instanceof Promise?y.then(v=>c(v,a,f)):c(y,a,f)}const m=t._zod.parse(a,f);if(m instanceof Promise){if(f.async===!1)throw new wS;return m.then(y=>o(y,n,f))}return o(m,n,f)}}ca(t,"~standard",()=>({validate:o=>{var c;try{const a=h7e(t,o);return a.success?{value:a.data}:{issues:(c=a.error)==null?void 0:c.issues}}catch{return f7e(t,o).then(f=>{var m;return f.success?{value:f.data}:{issues:(m=f.error)==null?void 0:m.issues}})}},vendor:"zod",version:1}))}),eK=Cr("$ZodString",(t,e)=>{var r;wo.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??V7e(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}}),so=Cr("$ZodStringFormat",(t,e)=>{aF.init(t,e),eK.init(t,e)}),lHe=Cr("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=N7e),so.init(t,e)}),cHe=Cr("$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=zse(n))}else e.pattern??(e.pattern=zse());so.init(t,e)}),uHe=Cr("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=C7e),so.init(t,e)}),dHe=Cr("$ZodURL",(t,e)=>{so.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)===F7e.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})}}}),hHe=Cr("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=P7e()),so.init(t,e)}),fHe=Cr("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=k7e),so.init(t,e)}),mHe=Cr("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=w7e),so.init(t,e)}),pHe=Cr("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=S7e),so.init(t,e)}),gHe=Cr("$ZodULID",(t,e)=>{e.pattern??(e.pattern=T7e),so.init(t,e)}),yHe=Cr("$ZodXID",(t,e)=>{e.pattern??(e.pattern=j7e),so.init(t,e)}),xHe=Cr("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=E7e),so.init(t,e)}),vHe=Cr("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=U7e(e)),so.init(t,e)}),_He=Cr("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=$7e),so.init(t,e)}),bHe=Cr("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=z7e(e)),so.init(t,e)}),wHe=Cr("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=A7e),so.init(t,e)}),SHe=Cr("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=R7e),so.init(t,e),t._zod.bag.format="ipv4"}),THe=Cr("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=L7e),so.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})}}}),jHe=Cr("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=M7e),so.init(t,e)}),EHe=Cr("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=D7e),so.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 jbe(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const kHe=Cr("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=O7e),so.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{jbe(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function AHe(t){if(!xbe.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return jbe(r)}const NHe=Cr("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xbe),so.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{AHe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),CHe=Cr("$ZodE164",(t,e)=>{e.pattern??(e.pattern=B7e),so.init(t,e)});function IHe(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 PHe=Cr("$ZodJWT",(t,e)=>{so.init(t,e),t._zod.check=r=>{IHe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ebe=Cr("$ZodNumber",(t,e)=>{wo.init(t,e),t._zod.pattern=t._zod.bag.pattern??bbe,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}}),RHe=Cr("$ZodNumberFormat",(t,e)=>{Y7e.init(t,e),Ebe.init(t,e)}),LHe=Cr("$ZodBoolean",(t,e)=>{wo.init(t,e),t._zod.pattern=G7e,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}}),MHe=Cr("$ZodUnknown",(t,e)=>{wo.init(t,e),t._zod.parse=r=>r}),DHe=Cr("$ZodNever",(t,e)=>{wo.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Use(t,e,r){t.issues.length&&e.issues.push(...Q1(r,t.issues)),e.value[r]=t.value}const OHe=Cr("$ZodArray",(t,e)=>{wo.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;cUse(m,r,c))):Use(f,r,c)}return o.length?Promise.all(o).then(()=>r):r}});function xO(t,e,r,n,i,o){const c=r in n;if(t.issues.length){if(i&&o&&!c)return;e.issues.push(...Q1(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 kbe(t){var n,i,o,c;const e=Object.keys(t.shape);for(const a of e)if(!((c=(o=(i=(n=t.shape)==null?void 0:n[a])==null?void 0:i._zod)==null?void 0:o.traits)!=null&&c.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const r=e7e(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Abe(t,e,r,n,i,o){const c=[],a=i.keySet,f=i.catchall._zod,m=f.def.type,y=f.optin==="optional",v=f.optout==="optional";for(const w in e){if(w==="__proto__"||a.has(w))continue;if(m==="never"){c.push(w);continue}const j=f.run({value:e[w],issues:[]},n);j instanceof Promise?t.push(j.then(A=>xO(A,r,w,e,y,v))):xO(j,r,w,e,y,v)}return c.length&&r.issues.push({code:"unrecognized_keys",keys:c,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}const FHe=Cr("$ZodObject",(t,e)=>{wo.init(t,e);const r=Object.getOwnPropertyDescriptor(e,"shape");if(!(r!=null&&r.get)){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const f={...a};return Object.defineProperty(e,"shape",{value:f}),f}})}const n=KW(()=>kbe(e));ca(t._zod,"propValues",()=>{const a=e.shape,f={};for(const m in a){const y=a[m]._zod;if(y.values){f[m]??(f[m]=new Set);for(const v of y.values)f[m].add(v)}}return f});const i=yO,o=e.catchall;let c;t._zod.parse=(a,f)=>{c??(c=n.value);const m=a.value;if(!i(m))return a.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),a;a.value={};const y=[],v=c.shape;for(const w of c.keys){const j=v[w],A=j._zod.optin==="optional",C=j._zod.optout==="optional",I=j._zod.run({value:m[w],issues:[]},f);I instanceof Promise?y.push(I.then(M=>xO(M,a,w,m,A,C))):xO(I,a,w,m,A,C)}return o?Abe(y,m,a,f,n.value,t):y.length?Promise.all(y).then(()=>a):a}}),BHe=Cr("$ZodObjectJIT",(t,e)=>{FHe.init(t,e);const r=t._zod.parse,n=KW(()=>kbe(e)),i=w=>{var F,z;const j=new aHe(["shape","payload","ctx"]),A=n.value,C=q=>{const H=$se(q);return`shape[${H}]._zod.run({ value: input[${H}], issues: [] }, ctx)`};j.write("const input = payload.value;");const I=Object.create(null);let M=0;for(const q of A.keys)I[q]=`key_${M++}`;j.write("const newResult = {};");for(const q of A.keys){const H=I[q],K=$se(q),J=w[q],Q=((F=J==null?void 0:J._zod)==null?void 0:F.optin)==="optional",ee=((z=J==null?void 0:J._zod)==null?void 0:z.optout)==="optional";j.write(`const ${H} = ${C(q)};`),Q&&ee?j.write(` if (${H}.issues.length) { if (${K} in input) { payload.issues = payload.issues.concat(${H}.issues.map(iss => ({ ...iss, path: iss.path ? [${K}, ...iss.path] : [${K}] }))); } } if (${H}.value === undefined) { if (${K} in input) { newResult[${K}] = undefined; } } else { newResult[${K}] = ${H}.value; } `):Q?j.write(` if (${H}.issues.length) { payload.issues = payload.issues.concat(${H}.issues.map(iss => ({ ...iss, path: iss.path ? [${K}, ...iss.path] : [${K}] }))); } if (${H}.value === undefined) { if (${K} in input) { newResult[${K}] = undefined; } } else { newResult[${K}] = ${H}.value; } `):j.write(` const ${H}_present = ${K} in input; if (${H}.issues.length) { payload.issues = payload.issues.concat(${H}.issues.map(iss => ({ ...iss, path: iss.path ? [${K}, ...iss.path] : [${K}] }))); } if (!${H}_present && !${H}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${K}] }); } if (${H}_present) { if (${H}.value === undefined) { newResult[${K}] = undefined; } else { newResult[${K}] = ${H}.value; } } `)}j.write("payload.value = newResult;"),j.write("return payload;");const D=j.compile();return(q,H)=>D(w,q,H)};let o;const c=yO,a=!WW.jitless,m=a&&QGe.value,y=e.catchall;let v;t._zod.parse=(w,j)=>{v??(v=n.value);const A=w.value;return c(A)?a&&m&&(j==null?void 0:j.async)===!1&&j.jitless!==!0?(o||(o=i(e.shape)),w=o(w,j),y?Abe([],A,w,j,v,t):w):r(w,j):(w.issues.push({expected:"object",code:"invalid_type",input:A,inst:t}),w)}});function Vse(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=>!X1(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=>Lg(c,n,Rg())))}),e)}const $He=Cr("$ZodUnion",(t,e)=>{wo.init(t,e),ca(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ca(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ca(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),ca(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=>ZW(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 a of e.options){const f=a._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(a=>Vse(a,n,t,i)):Vse(c,n,t,i)}}),zHe=Cr("$ZodIntersection",(t,e)=>{wo.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,m])=>qse(r,f,m)):qse(r,o,c)}});function Nq(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(oT(t)&&oT(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=Nq(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;na.l&&a.r).map(([a])=>a);if(o.length&&i&&t.issues.push({...i,keys:o}),X1(t))return t;const c=Nq(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 UHe=Cr("$ZodRecord",(t,e)=>{wo.init(t,e),t._zod.parse=(r,n)=>{const i=r.value;if(!oT(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 a=new Set;for(const m of c)if(typeof m=="string"||typeof m=="number"||typeof m=="symbol"){a.add(typeof m=="number"?m.toString():m);const y=e.keyType._zod.run({value:m,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(j=>Lg(j,n,Rg())),input:m,path:[m],inst:t});continue}const v=y.value,w=e.valueType._zod.run({value:i[m],issues:[]},n);w instanceof Promise?o.push(w.then(j=>{j.issues.length&&r.issues.push(...Q1(m,j.issues)),r.value[v]=j.value})):(w.issues.length&&r.issues.push(...Q1(m,w.issues)),r.value[v]=w.value)}let f;for(const m in i)a.has(m)||(f=f??[],f.push(m));f&&f.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:f})}else{r.value={};for(const a of Reflect.ownKeys(i)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,a))continue;let f=e.keyType._zod.run({value:a,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&bbe.test(a)&&f.issues.length){const v=e.keyType._zod.run({value:Number(a),issues:[]},n);if(v instanceof Promise)throw new Error("Async schemas not supported in object keys currently");v.issues.length===0&&(f=v)}if(f.issues.length){e.mode==="loose"?r.value[a]=i[a]:r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(v=>Lg(v,n,Rg())),input:a,path:[a],inst:t});continue}const y=e.valueType._zod.run({value:i[a],issues:[]},n);y instanceof Promise?o.push(y.then(v=>{v.issues.length&&r.issues.push(...Q1(a,v.issues)),r.value[f.value]=v.value})):(y.issues.length&&r.issues.push(...Q1(a,y.issues)),r.value[f.value]=y.value)}}return o.length?Promise.all(o).then(()=>r):r}}),VHe=Cr("$ZodEnum",(t,e)=>{wo.init(t,e);const r=hbe(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>JGe.has(typeof i)).map(i=>typeof i=="string"?lT(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}}),qHe=Cr("$ZodLiteral",(t,e)=>{if(wo.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"?lT(n):n?lT(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}}),GHe=Cr("$ZodTransform",(t,e)=>{wo.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new dbe(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 wS;return r.value=i,r.fallback=!0,r}});function Gse(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const Nbe=Cr("$ZodOptional",(t,e)=>{wo.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ca(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ca(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${ZW(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=>Gse(c,i)):Gse(o,i)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),HHe=Cr("$ZodExactOptional",(t,e)=>{Nbe.init(t,e),ca(t._zod,"values",()=>e.innerType._zod.values),ca(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),WHe=Cr("$ZodNullable",(t,e)=>{wo.init(t,e),ca(t._zod,"optin",()=>e.innerType._zod.optin),ca(t._zod,"optout",()=>e.innerType._zod.optout),ca(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${ZW(r.source)}|null)$`):void 0}),ca(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)}),KHe=Cr("$ZodDefault",(t,e)=>{wo.init(t,e),t._zod.optin="optional",ca(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=>Hse(o,e)):Hse(i,e)}});function Hse(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const YHe=Cr("$ZodPrefault",(t,e)=>{wo.init(t,e),t._zod.optin="optional",ca(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))}),ZHe=Cr("$ZodNonOptional",(t,e)=>{wo.init(t,e),ca(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=>Wse(o,t)):Wse(i,t)}});function Wse(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 XHe=Cr("$ZodCatch",(t,e)=>{wo.init(t,e),t._zod.optin="optional",ca(t._zod,"optout",()=>e.innerType._zod.optout),ca(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=>Lg(c,n,Rg()))},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=>Lg(o,n,Rg()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),QHe=Cr("$ZodPipe",(t,e)=>{wo.init(t,e),ca(t._zod,"values",()=>e.in._zod.values),ca(t._zod,"optin",()=>e.in._zod.optin),ca(t._zod,"optout",()=>e.out._zod.optout),ca(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=>TL(c,e.in,n)):TL(o,e.in,n)}const i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>TL(o,e.out,n)):TL(i,e.out,n)}});function TL(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 JHe=Cr("$ZodReadonly",(t,e)=>{wo.init(t,e),ca(t._zod,"propValues",()=>e.innerType._zod.propValues),ca(t._zod,"values",()=>e.innerType._zod.values),ca(t._zod,"optin",()=>{var r,n;return(n=(r=e.innerType)==null?void 0:r._zod)==null?void 0:n.optin}),ca(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(Kse):Kse(i)}});function Kse(t){return t.value=Object.freeze(t.value),t}const eWe=Cr("$ZodCustom",(t,e)=>{ad.init(t,e),wo.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=>Yse(o,r,n,t));Yse(i,r,n,t)}});function Yse(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(fN(i))}}var Zse;class tWe{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 rWe(){return new tWe}(Zse=globalThis).__zod_globalRegistry??(Zse.__zod_globalRegistry=rWe());const Gk=globalThis.__zod_globalRegistry;function nWe(t,e){return new t({type:"string",...Yn(e)})}function sWe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Yn(e)})}function Xse(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Yn(e)})}function iWe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Yn(e)})}function aWe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Yn(e)})}function oWe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Yn(e)})}function lWe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Yn(e)})}function cWe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Yn(e)})}function uWe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Yn(e)})}function dWe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Yn(e)})}function hWe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Yn(e)})}function fWe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Yn(e)})}function mWe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Yn(e)})}function pWe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Yn(e)})}function gWe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Yn(e)})}function yWe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Yn(e)})}function xWe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Yn(e)})}function vWe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Yn(e)})}function _We(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Yn(e)})}function bWe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Yn(e)})}function wWe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Yn(e)})}function SWe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Yn(e)})}function TWe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Yn(e)})}function jWe(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Yn(e)})}function EWe(t,e){return new t({type:"string",format:"date",check:"string_format",...Yn(e)})}function kWe(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Yn(e)})}function AWe(t,e){return new t({type:"string",format:"duration",check:"string_format",...Yn(e)})}function NWe(t,e){return new t({type:"number",checks:[],...Yn(e)})}function CWe(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Yn(e)})}function IWe(t,e){return new t({type:"boolean",...Yn(e)})}function PWe(t){return new t({type:"unknown"})}function RWe(t,e){return new t({type:"never",...Yn(e)})}function Qse(t,e){return new Sbe({check:"less_than",...Yn(e),value:t,inclusive:!1})}function w6(t,e){return new Sbe({check:"less_than",...Yn(e),value:t,inclusive:!0})}function Jse(t,e){return new Tbe({check:"greater_than",...Yn(e),value:t,inclusive:!1})}function S6(t,e){return new Tbe({check:"greater_than",...Yn(e),value:t,inclusive:!0})}function eie(t,e){return new K7e({check:"multiple_of",...Yn(e),value:t})}function Cbe(t,e){return new Z7e({check:"max_length",...Yn(e),maximum:t})}function vO(t,e){return new X7e({check:"min_length",...Yn(e),minimum:t})}function Ibe(t,e){return new Q7e({check:"length_equals",...Yn(e),length:t})}function LWe(t,e){return new J7e({check:"string_format",format:"regex",...Yn(e),pattern:t})}function MWe(t){return new eHe({check:"string_format",format:"lowercase",...Yn(t)})}function DWe(t){return new tHe({check:"string_format",format:"uppercase",...Yn(t)})}function OWe(t,e){return new rHe({check:"string_format",format:"includes",...Yn(e),includes:t})}function FWe(t,e){return new nHe({check:"string_format",format:"starts_with",...Yn(e),prefix:t})}function BWe(t,e){return new sHe({check:"string_format",format:"ends_with",...Yn(e),suffix:t})}function hj(t){return new iHe({check:"overwrite",tx:t})}function $We(t){return hj(e=>e.normalize(t))}function zWe(){return hj(t=>t.trim())}function UWe(){return hj(t=>t.toLowerCase())}function VWe(){return hj(t=>t.toUpperCase())}function qWe(){return hj(t=>XGe(t))}function GWe(t,e,r){return new t({type:"array",element:e,...Yn(r)})}function HWe(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Yn(r)})}function WWe(t,e){const r=KWe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(fN(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(fN(o))}},t(n.value,n)),e);return r}function KWe(t,e){const r=new ad({check:"custom",...Yn(e)});return r._zod.check=t,r}function Pbe(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)??Gk,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 ll(t,e,r={path:[],schemaPath:[]}){var y,v;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 a=(v=(y=t._zod).toJSONSchema)==null?void 0:v.call(y);if(a)c.schema=a;else{const w={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,c.schema,w);else{const A=c.schema,C=e.processors[i.type];if(!C)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);C(t,e,A,w)}const j=t._zod.parent;j&&(c.ref||(c.ref=j),ll(j,e,w),e.seen.get(j).isParent=!0)}const f=e.metadataRegistry.get(t);return f&&Object.assign(c.schema,f),e.io==="input"&&lu(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 Rbe(t,e){var c,a,f,m;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const y of t.seen.entries()){const v=(c=t.metadataRegistry.get(y[0]))==null?void 0:c.id;if(v){const w=n.get(v);if(w&&w!==y[0])throw new Error(`Duplicate schema id "${v}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(v,y[0])}}const i=y=>{var C;const v=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const I=(C=t.external.registry.get(y[0]))==null?void 0:C.id,M=t.external.uri??(F=>F);if(I)return{ref:M(I)};const D=y[1].defId??y[1].schema.id??`schema${t.counter++}`;return y[1].defId=D,{defId:D,ref:`${M("__shared")}#/${v}/${D}`}}if(y[1]===r)return{ref:"#"};const j=`#/${v}/`,A=y[1].schema.id??`__schema${t.counter++}`;return{defId:A,ref:j+A}},o=y=>{if(y[1].schema.$ref)return;const v=y[1],{ref:w,defId:j}=i(y);v.def={...v.schema},j&&(v.defId=j);const A=v.schema;for(const C in A)delete A[C];A.$ref=w};if(t.cycles==="throw")for(const y of t.seen.entries()){const v=y[1];if(v.cycle)throw new Error(`Cycle detected: #/${(a=v.cycle)==null?void 0:a.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const y of t.seen.entries()){const v=y[1];if(e===y[0]){o(y);continue}if(t.external){const j=(f=t.external.registry.get(y[0]))==null?void 0:f.id;if(e!==y[0]&&j){o(y);continue}}if((m=t.metadataRegistry.get(y[0]))==null?void 0:m.id){o(y);continue}if(v.cycle){o(y);continue}if(v.count>1&&t.reused==="ref"){o(y);continue}}}function Lbe(t,e){var a,f,m,y;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=v=>{const w=t.seen.get(v);if(w.ref===null)return;const j=w.def??w.schema,A={...j},C=w.ref;if(w.ref=null,C){n(C);const M=t.seen.get(C),D=M.schema;if(D.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(j.allOf=j.allOf??[],j.allOf.push(D)):Object.assign(j,D),Object.assign(j,A),v._zod.parent===C)for(const z in j)z==="$ref"||z==="allOf"||z in A||delete j[z];if(D.$ref&&M.def)for(const z in j)z==="$ref"||z==="allOf"||z in M.def&&JSON.stringify(j[z])===JSON.stringify(M.def[z])&&delete j[z]}const I=v._zod.parent;if(I&&I!==C){n(I);const M=t.seen.get(I);if(M!=null&&M.schema.$ref&&(j.$ref=M.schema.$ref,M.def))for(const D in j)D==="$ref"||D==="allOf"||D in M.def&&JSON.stringify(j[D])===JSON.stringify(M.def[D])&&delete j[D]}t.override({zodSchema:v,jsonSchema:j,path:w.path??[]})};for(const v of[...t.seen.entries()].reverse())n(v[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,(a=t.external)!=null&&a.uri){const v=(f=t.external.registry.get(e))==null?void 0:f.id;if(!v)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(v)}Object.assign(i,r.def??r.schema);const o=(m=t.metadataRegistry.get(e))==null?void 0:m.id;o!==void 0&&i.id===o&&delete i.id;const c=((y=t.external)==null?void 0:y.defs)??{};for(const v of t.seen.entries()){const w=v[1];w.def&&w.defId&&(w.def.id===w.defId&&delete w.def.id,c[w.defId]=w.def)}t.external||Object.keys(c).length>0&&(t.target==="draft-2020-12"?i.$defs=c:i.definitions=c);try{const v=JSON.parse(JSON.stringify(i));return Object.defineProperty(v,"~standard",{value:{...e["~standard"],jsonSchema:{input:_O(e,"input",t.processors),output:_O(e,"output",t.processors)}},enumerable:!1,writable:!1}),v}catch{throw new Error("Error converting schema to JSON.")}}function lu(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 lu(n.element,r);if(n.type==="set")return lu(n.valueType,r);if(n.type==="lazy")return lu(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 lu(n.innerType,r);if(n.type==="intersection")return lu(n.left,r)||lu(n.right,r);if(n.type==="record"||n.type==="map")return lu(n.keyType,r)||lu(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:lu(n.in,r)||lu(n.out,r);if(n.type==="object"){for(const i in n.shape)if(lu(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(lu(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(lu(i,r))return!0;return!!(n.rest&&lu(n.rest,r))}return!1}const YWe=(t,e={})=>r=>{const n=Pbe({...r,processors:e});return ll(t,n),Rbe(n,t),Lbe(n,t)},_O=(t,e,r={})=>n=>{const{libraryOptions:i,target:o}=n??{},c=Pbe({...i??{},target:o,io:e,processors:r});return ll(t,c),Rbe(c,t),Lbe(c,t)},ZWe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},XWe=(t,e,r,n)=>{const i=r;i.type="string";const{minimum:o,maximum:c,format:a,patterns:f,contentEncoding:m}=t._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof c=="number"&&(i.maxLength=c),a&&(i.format=ZWe[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),m&&(i.contentEncoding=m),f&&f.size>0){const y=[...f];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(v=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:v.source}))])}},QWe=(t,e,r,n)=>{const i=r,{minimum:o,maximum:c,format:a,multipleOf:f,exclusiveMaximum:m,exclusiveMinimum:y}=t._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number";const v=typeof y=="number"&&y>=(o??Number.NEGATIVE_INFINITY),w=typeof m=="number"&&m<=(c??Number.POSITIVE_INFINITY),j=e.target==="draft-04"||e.target==="openapi-3.0";v?j?(i.minimum=y,i.exclusiveMinimum=!0):i.exclusiveMinimum=y:typeof o=="number"&&(i.minimum=o),w?j?(i.maximum=m,i.exclusiveMaximum=!0):i.exclusiveMaximum=m:typeof c=="number"&&(i.maximum=c),typeof f=="number"&&(i.multipleOf=f)},JWe=(t,e,r,n)=>{r.type="boolean"},eKe=(t,e,r,n)=>{r.not={}},tKe=(t,e,r,n)=>{},rKe=(t,e,r,n)=>{const i=t._zod.def,o=hbe(i.entries);o.every(c=>typeof c=="number")&&(r.type="number"),o.every(c=>typeof c=="string")&&(r.type="string"),r.enum=o},nKe=(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},sKe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},iKe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},aKe=(t,e,r,n)=>{const i=r,o=t._zod.def,{minimum:c,maximum:a}=t._zod.bag;typeof c=="number"&&(i.minItems=c),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=ll(o.element,e,{...n,path:[...n.path,"items"]})},oKe=(t,e,r,n)=>{var m;const i=r,o=t._zod.def;i.type="object",i.properties={};const c=o.shape;for(const y in c)i.properties[y]=ll(c[y],e,{...n,path:[...n.path,"properties",y]});const a=new Set(Object.keys(c)),f=new Set([...a].filter(y=>{const v=o.shape[y]._zod;return e.io==="input"?v.optin===void 0:v.optout===void 0}));f.size>0&&(i.required=Array.from(f)),((m=o.catchall)==null?void 0:m._zod.def.type)==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=ll(o.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},lKe=(t,e,r,n)=>{const i=t._zod.def,o=i.inclusive===!1,c=i.options.map((a,f)=>ll(a,e,{...n,path:[...n.path,o?"oneOf":"anyOf",f]}));o?r.oneOf=c:r.anyOf=c},cKe=(t,e,r,n)=>{const i=t._zod.def,o=ll(i.left,e,{...n,path:[...n.path,"allOf",0]}),c=ll(i.right,e,{...n,path:[...n.path,"allOf",1]}),a=m=>"allOf"in m&&Object.keys(m).length===1,f=[...a(o)?o.allOf:[o],...a(c)?c.allOf:[c]];r.allOf=f},uKe=(t,e,r,n)=>{const i=r,o=t._zod.def;i.type="object";const c=o.keyType,a=c._zod.bag,f=a==null?void 0:a.patterns;if(o.mode==="loose"&&f&&f.size>0){const y=ll(o.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const v of f)i.patternProperties[v.source]=y}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=ll(o.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=ll(o.valueType,e,{...n,path:[...n.path,"additionalProperties"]});const m=c._zod.values;if(m){const y=[...m].filter(v=>typeof v=="string"||typeof v=="number");y.length>0&&(i.required=y)}},dKe=(t,e,r,n)=>{const i=t._zod.def,o=ll(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"}]},hKe=(t,e,r,n)=>{const i=t._zod.def;ll(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},fKe=(t,e,r,n)=>{const i=t._zod.def;ll(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},mKe=(t,e,r,n)=>{const i=t._zod.def;ll(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)))},pKe=(t,e,r,n)=>{const i=t._zod.def;ll(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},gKe=(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;ll(c,e,n);const a=e.seen.get(t);a.ref=c},yKe=(t,e,r,n)=>{const i=t._zod.def;ll(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.readOnly=!0},Mbe=(t,e,r,n)=>{const i=t._zod.def;ll(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},xKe=Cr("ZodISODateTime",(t,e)=>{vHe.init(t,e),To.init(t,e)});function vKe(t){return jWe(xKe,t)}const _Ke=Cr("ZodISODate",(t,e)=>{_He.init(t,e),To.init(t,e)});function bKe(t){return EWe(_Ke,t)}const wKe=Cr("ZodISOTime",(t,e)=>{bHe.init(t,e),To.init(t,e)});function SKe(t){return kWe(wKe,t)}const TKe=Cr("ZodISODuration",(t,e)=>{wHe.init(t,e),To.init(t,e)});function jKe(t){return AWe(TKe,t)}const Dbe=(t,e)=>{gbe.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>d7e(t,r)},flatten:{value:r=>u7e(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Aq,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Aq,2)}},isEmpty:{get(){return t.issues.length===0}}})},EKe=Cr("ZodError",Dbe),Oh=Cr("ZodError",Dbe,{Parent:Error}),kKe=QW(Oh),AKe=JW(Oh),NKe=sF(Oh),CKe=iF(Oh),IKe=m7e(Oh),PKe=p7e(Oh),RKe=g7e(Oh),LKe=y7e(Oh),MKe=x7e(Oh),DKe=v7e(Oh),OKe=_7e(Oh),FKe=b7e(Oh),tie=new WeakMap;function WC(t,e,r){const n=Object.getPrototypeOf(t);let i=tie.get(n);if(i||(i=new Set,tie.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 a=c.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const So=Cr("ZodType",(t,e)=>(wo.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:_O(t,"input"),output:_O(t,"output")}}),t.toJSONSchema=YWe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>kKe(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>NKe(t,r,n),t.parseAsync=async(r,n)=>AKe(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>CKe(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>IKe(t,r,n),t.decode=(r,n)=>PKe(t,r,n),t.encodeAsync=async(r,n)=>RKe(t,r,n),t.decodeAsync=async(r,n)=>LKe(t,r,n),t.safeEncode=(r,n)=>MKe(t,r,n),t.safeDecode=(r,n)=>DKe(t,r,n),t.safeEncodeAsync=async(r,n)=>OKe(t,r,n),t.safeDecodeAsync=async(r,n)=>FKe(t,r,n),WC(t,"ZodType",{check(...r){const n=this.def;return this.clone(_0(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 b0(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(LYe(r,n))},superRefine(r,n){return this.check(MYe(r,n))},overwrite(r){return this.check(hj(r))},optional(){return iie(this)},exactOptional(){return bYe(this)},nullable(){return aie(this)},nullish(){return iie(aie(this))},nonoptional(r){return kYe(this,r)},array(){return uYe(this)},or(r){return fYe([this,r])},and(r){return pYe(this,r)},transform(r){return oie(this,vYe(r))},default(r){return TYe(this,r)},prefault(r){return EYe(this,r)},catch(r){return NYe(this,r)},pipe(r){return oie(this,r)},readonly(){return PYe(this)},describe(r){const n=this.clone();return Gk.add(n,{description:r}),n},meta(...r){if(r.length===0)return Gk.get(this);const n=this.clone();return Gk.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=Gk.get(t))==null?void 0:r.description},configurable:!0}),t)),Obe=Cr("_ZodString",(t,e)=>{eK.init(t,e),So.init(t,e),t._zod.processJSONSchema=(n,i,o)=>XWe(t,n,i);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,WC(t,"_ZodString",{regex(...n){return this.check(LWe(...n))},includes(...n){return this.check(OWe(...n))},startsWith(...n){return this.check(FWe(...n))},endsWith(...n){return this.check(BWe(...n))},min(...n){return this.check(vO(...n))},max(...n){return this.check(Cbe(...n))},length(...n){return this.check(Ibe(...n))},nonempty(...n){return this.check(vO(1,...n))},lowercase(n){return this.check(MWe(n))},uppercase(n){return this.check(DWe(n))},trim(){return this.check(zWe())},normalize(...n){return this.check($We(...n))},toLowerCase(){return this.check(UWe())},toUpperCase(){return this.check(VWe())},slugify(){return this.check(qWe())}})}),BKe=Cr("ZodString",(t,e)=>{eK.init(t,e),Obe.init(t,e),t.email=r=>t.check(sWe($Ke,r)),t.url=r=>t.check(cWe(zKe,r)),t.jwt=r=>t.check(TWe(rYe,r)),t.emoji=r=>t.check(uWe(UKe,r)),t.guid=r=>t.check(Xse(rie,r)),t.uuid=r=>t.check(iWe(jL,r)),t.uuidv4=r=>t.check(aWe(jL,r)),t.uuidv6=r=>t.check(oWe(jL,r)),t.uuidv7=r=>t.check(lWe(jL,r)),t.nanoid=r=>t.check(dWe(VKe,r)),t.guid=r=>t.check(Xse(rie,r)),t.cuid=r=>t.check(hWe(qKe,r)),t.cuid2=r=>t.check(fWe(GKe,r)),t.ulid=r=>t.check(mWe(HKe,r)),t.base64=r=>t.check(bWe(JKe,r)),t.base64url=r=>t.check(wWe(eYe,r)),t.xid=r=>t.check(pWe(WKe,r)),t.ksuid=r=>t.check(gWe(KKe,r)),t.ipv4=r=>t.check(yWe(YKe,r)),t.ipv6=r=>t.check(xWe(ZKe,r)),t.cidrv4=r=>t.check(vWe(XKe,r)),t.cidrv6=r=>t.check(_We(QKe,r)),t.e164=r=>t.check(SWe(tYe,r)),t.datetime=r=>t.check(vKe(r)),t.date=r=>t.check(bKe(r)),t.time=r=>t.check(SKe(r)),t.duration=r=>t.check(jKe(r))});function Ds(t){return nWe(BKe,t)}const To=Cr("ZodStringFormat",(t,e)=>{so.init(t,e),Obe.init(t,e)}),$Ke=Cr("ZodEmail",(t,e)=>{uHe.init(t,e),To.init(t,e)}),rie=Cr("ZodGUID",(t,e)=>{lHe.init(t,e),To.init(t,e)}),jL=Cr("ZodUUID",(t,e)=>{cHe.init(t,e),To.init(t,e)}),zKe=Cr("ZodURL",(t,e)=>{dHe.init(t,e),To.init(t,e)}),UKe=Cr("ZodEmoji",(t,e)=>{hHe.init(t,e),To.init(t,e)}),VKe=Cr("ZodNanoID",(t,e)=>{fHe.init(t,e),To.init(t,e)}),qKe=Cr("ZodCUID",(t,e)=>{mHe.init(t,e),To.init(t,e)}),GKe=Cr("ZodCUID2",(t,e)=>{pHe.init(t,e),To.init(t,e)}),HKe=Cr("ZodULID",(t,e)=>{gHe.init(t,e),To.init(t,e)}),WKe=Cr("ZodXID",(t,e)=>{yHe.init(t,e),To.init(t,e)}),KKe=Cr("ZodKSUID",(t,e)=>{xHe.init(t,e),To.init(t,e)}),YKe=Cr("ZodIPv4",(t,e)=>{SHe.init(t,e),To.init(t,e)}),ZKe=Cr("ZodIPv6",(t,e)=>{THe.init(t,e),To.init(t,e)}),XKe=Cr("ZodCIDRv4",(t,e)=>{jHe.init(t,e),To.init(t,e)}),QKe=Cr("ZodCIDRv6",(t,e)=>{EHe.init(t,e),To.init(t,e)}),JKe=Cr("ZodBase64",(t,e)=>{kHe.init(t,e),To.init(t,e)}),eYe=Cr("ZodBase64URL",(t,e)=>{NHe.init(t,e),To.init(t,e)}),tYe=Cr("ZodE164",(t,e)=>{CHe.init(t,e),To.init(t,e)}),rYe=Cr("ZodJWT",(t,e)=>{PHe.init(t,e),To.init(t,e)}),Fbe=Cr("ZodNumber",(t,e)=>{Ebe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(n,i,o)=>QWe(t,n,i),WC(t,"ZodNumber",{gt(n,i){return this.check(Jse(n,i))},gte(n,i){return this.check(S6(n,i))},min(n,i){return this.check(S6(n,i))},lt(n,i){return this.check(Qse(n,i))},lte(n,i){return this.check(w6(n,i))},max(n,i){return this.check(w6(n,i))},int(n){return this.check(nie(n))},safe(n){return this.check(nie(n))},positive(n){return this.check(Jse(0,n))},nonnegative(n){return this.check(S6(0,n))},negative(n){return this.check(Qse(0,n))},nonpositive(n){return this.check(w6(0,n))},multipleOf(n,i){return this.check(eie(n,i))},step(n,i){return this.check(eie(n,i))},finite(){return this}});const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function yA(t){return NWe(Fbe,t)}const nYe=Cr("ZodNumberFormat",(t,e)=>{RHe.init(t,e),Fbe.init(t,e)});function nie(t){return CWe(nYe,t)}const sYe=Cr("ZodBoolean",(t,e)=>{LHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>JWe(t,r,n)});function iYe(t){return IWe(sYe,t)}const aYe=Cr("ZodUnknown",(t,e)=>{MHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tKe()});function Cq(){return PWe(aYe)}const oYe=Cr("ZodNever",(t,e)=>{DHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>eKe(t,r,n)});function lYe(t){return RWe(oYe,t)}const cYe=Cr("ZodArray",(t,e)=>{OHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>aKe(t,r,n,i),t.element=e.element,WC(t,"ZodArray",{min(r,n){return this.check(vO(r,n))},nonempty(r){return this.check(vO(1,r))},max(r,n){return this.check(Cbe(r,n))},length(r,n){return this.check(Ibe(r,n))},unwrap(){return this.element}})});function uYe(t,e){return GWe(cYe,t,e)}const dYe=Cr("ZodObject",(t,e)=>{BHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oKe(t,r,n,i),ca(t,"shape",()=>e.shape),WC(t,"ZodObject",{keyof(){return cT(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Cq()})},loose(){return this.clone({...this._zod.def,catchall:Cq()})},strict(){return this.clone({...this._zod.def,catchall:lYe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return s7e(this,r)},safeExtend(r){return i7e(this,r)},merge(r){return a7e(this,r)},pick(r){return r7e(this,r)},omit(r){return n7e(this,r)},partial(...r){return o7e(Bbe,this,r[0])},required(...r){return l7e($be,this,r[0])}})});function qg(t,e){const r={type:"object",shape:t??{},...Yn(e)};return new dYe(r)}const hYe=Cr("ZodUnion",(t,e)=>{$He.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lKe(t,r,n,i),t.options=e.options});function fYe(t,e){return new hYe({type:"union",options:t,...Yn(e)})}const mYe=Cr("ZodIntersection",(t,e)=>{zHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cKe(t,r,n,i)});function pYe(t,e){return new mYe({type:"intersection",left:t,right:e})}const sie=Cr("ZodRecord",(t,e)=>{UHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uKe(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function gYe(t,e,r){return!e||!e._zod?new sie({type:"record",keyType:Ds(),valueType:t,...Yn(e)}):new sie({type:"record",keyType:t,valueType:e,...Yn(r)})}const Iq=Cr("ZodEnum",(t,e)=>{VHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(n,i,o)=>rKe(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 Iq({...e,checks:[],...Yn(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 Iq({...e,checks:[],...Yn(i),entries:o})}});function cT(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Iq({type:"enum",entries:r,...Yn(e)})}const yYe=Cr("ZodLiteral",(t,e)=>{qHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>nKe(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 bO(t,e){return new yYe({type:"literal",values:Array.isArray(t)?t:[t],...Yn(e)})}const xYe=Cr("ZodTransform",(t,e)=>{GHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>iKe(t,r),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new dbe(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(fN(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(fN(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 vYe(t){return new xYe({type:"transform",transform:t})}const Bbe=Cr("ZodOptional",(t,e)=>{Nbe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Mbe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function iie(t){return new Bbe({type:"optional",innerType:t})}const _Ye=Cr("ZodExactOptional",(t,e)=>{HHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Mbe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function bYe(t){return new _Ye({type:"optional",innerType:t})}const wYe=Cr("ZodNullable",(t,e)=>{WHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>dKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function aie(t){return new wYe({type:"nullable",innerType:t})}const SYe=Cr("ZodDefault",(t,e)=>{KHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>fKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function TYe(t,e){return new SYe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():mbe(e)}})}const jYe=Cr("ZodPrefault",(t,e)=>{YHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function EYe(t,e){return new jYe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():mbe(e)}})}const $be=Cr("ZodNonOptional",(t,e)=>{ZHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function kYe(t,e){return new $be({type:"nonoptional",innerType:t,...Yn(e)})}const AYe=Cr("ZodCatch",(t,e)=>{XHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>pKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function NYe(t,e){return new AYe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const CYe=Cr("ZodPipe",(t,e)=>{QHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gKe(t,r,n,i),t.in=e.in,t.out=e.out});function oie(t,e){return new CYe({type:"pipe",in:t,out:e})}const IYe=Cr("ZodReadonly",(t,e)=>{JHe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yKe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function PYe(t){return new IYe({type:"readonly",innerType:t})}const RYe=Cr("ZodCustom",(t,e)=>{eWe.init(t,e),So.init(t,e),t._zod.processJSONSchema=(r,n,i)=>sKe(t,r)});function LYe(t,e={}){return HWe(RYe,t,e)}function MYe(t,e){return WWe(t,e)}var DYe="Label",zbe=N.forwardRef((t,e)=>s.jsx(cn.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())}}));zbe.displayName=DYe;var Ube=zbe;const OYe=YT("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Br=N.forwardRef(({className:t,...e},r)=>s.jsx(Ube,{ref:r,className:Xt(OYe(),t),...e}));Br.displayName=Ube.displayName;const tK=NGe,Vbe=N.createContext({}),wl=({...t})=>s.jsx(Vbe.Provider,{value:{name:t.name},children:s.jsx(RGe,{...t})}),oF=()=>{const t=N.useContext(Vbe),e=N.useContext(qbe),{getFieldState:r,formState:n}=nF(),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}},qbe=N.createContext({}),rl=N.forwardRef(({className:t,...e},r)=>{const n=N.useId();return s.jsx(qbe.Provider,{value:{id:n},children:s.jsx("div",{ref:r,className:Xt("space-y-2",t),...e})})});rl.displayName="FormItem";const nl=N.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=oF();return s.jsx(Br,{ref:r,className:Xt(n&&"text-destructive",t),htmlFor:i,...e})});nl.displayName="FormLabel";const sl=N.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=oF();return s.jsx(Gge,{ref:e,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});sl.displayName="FormControl";const HM=N.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=oF();return s.jsx("p",{ref:r,id:n,className:Xt("text-sm text-muted-foreground",t),...e})});HM.displayName="FormDescription";const Cf=N.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:o}=oF(),c=i?String(i==null?void 0:i.message):e;return c?s.jsx("p",{ref:n,id:o,className:Xt("text-sm font-medium text-destructive",t),...r,children:c}):null});Cf.displayName="FormMessage";const Or=N.forwardRef(({className:t,type:e,...r},n)=>s.jsx("input",{type:e,className:Xt("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}));Or.displayName="Input";function KC(t){const e=N.useRef({value:t,previous:t});return N.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var FYe=[" ","Enter","ArrowUp","ArrowDown"],BYe=[" ","Enter"],J_="Select",[lF,cF,$Ye]=jC(J_),[fj,rer]=dl(J_,[$Ye,g0]),uF=g0(),[zYe,w0]=fj(J_),[UYe,VYe]=fj(J_),Gbe=t=>{const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:o,value:c,defaultValue:a,onValueChange:f,dir:m,name:y,autoComplete:v,disabled:w,required:j,form:A}=t,C=uF(e),[I,M]=N.useState(null),[D,F]=N.useState(null),[z,q]=N.useState(!1),H=gb(m),[K,J]=rd({prop:n,defaultProp:i??!1,onChange:o,caller:J_}),[Q,ee]=rd({prop:c,defaultProp:a,onChange:f,caller:J_}),oe=N.useRef(null),de=I?A||!!I.closest("form"):!0,[ye,we]=N.useState(new Set),Le=Array.from(ye).map(Se=>Se.props.value).join(";");return s.jsx(FC,{...C,children:s.jsxs(zYe,{required:j,scope:e,trigger:I,onTriggerChange:M,valueNode:D,onValueNodeChange:F,valueNodeHasChildren:z,onValueNodeHasChildrenChange:q,contentId:ol(),value:Q,onValueChange:ee,open:K,onOpenChange:J,dir:H,triggerPointerDownPosRef:oe,disabled:w,children:[s.jsx(lF.Provider,{scope:e,children:s.jsx(UYe,{scope:t.__scopeSelect,onNativeOptionAdd:N.useCallback(Se=>{we(ve=>new Set(ve).add(Se))},[]),onNativeOptionRemove:N.useCallback(Se=>{we(ve=>{const me=new Set(ve);return me.delete(Se),me})},[]),children:r})}),de?s.jsxs(gwe,{"aria-hidden":!0,required:j,tabIndex:-1,name:y,autoComplete:v,value:Q,onChange:Se=>ee(Se.target.value),disabled:w,form:A,children:[Q===void 0?s.jsx("option",{value:""}):null,Array.from(ye)]},Le):null]})})};Gbe.displayName=J_;var Hbe="SelectTrigger",Wbe=N.forwardRef((t,e)=>{const{__scopeSelect:r,disabled:n=!1,...i}=t,o=uF(r),c=w0(Hbe,r),a=c.disabled||n,f=is(e,c.onTriggerChange),m=cF(r),y=N.useRef("touch"),[v,w,j]=xwe(C=>{const I=m().filter(F=>!F.disabled),M=I.find(F=>F.value===c.value),D=vwe(I,C,M);D!==void 0&&c.onValueChange(D.value)}),A=C=>{a||(c.onOpenChange(!0),j()),C&&(c.triggerPointerDownPosRef.current={x:Math.round(C.pageX),y:Math.round(C.pageY)})};return s.jsx(BC,{asChild:!0,...o,children:s.jsx(cn.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:a,"data-disabled":a?"":void 0,"data-placeholder":ywe(c.value)?"":void 0,...i,ref:f,onClick:Gr(i.onClick,C=>{C.currentTarget.focus(),y.current!=="mouse"&&A(C)}),onPointerDown:Gr(i.onPointerDown,C=>{y.current=C.pointerType;const I=C.target;I.hasPointerCapture(C.pointerId)&&I.releasePointerCapture(C.pointerId),C.button===0&&C.ctrlKey===!1&&C.pointerType==="mouse"&&(A(C),C.preventDefault())}),onKeyDown:Gr(i.onKeyDown,C=>{const I=v.current!=="";!(C.ctrlKey||C.altKey||C.metaKey)&&C.key.length===1&&w(C.key),!(I&&C.key===" ")&&FYe.includes(C.key)&&(A(),C.preventDefault())})})})});Wbe.displayName=Hbe;var Kbe="SelectValue",Ybe=N.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,children:o,placeholder:c="",...a}=t,f=w0(Kbe,r),{onValueNodeHasChildrenChange:m}=f,y=o!==void 0,v=is(e,f.onValueNodeChange);return Ho(()=>{m(y)},[m,y]),s.jsx(cn.span,{...a,ref:v,style:{pointerEvents:"none"},children:ywe(f.value)?s.jsx(s.Fragment,{children:c}):o})});Ybe.displayName=Kbe;var qYe="SelectIcon",Zbe=N.forwardRef((t,e)=>{const{__scopeSelect:r,children:n,...i}=t;return s.jsx(cn.span,{"aria-hidden":!0,...i,ref:e,children:n||"▼"})});Zbe.displayName=qYe;var GYe="SelectPortal",Xbe=t=>s.jsx(KT,{asChild:!0,...t});Xbe.displayName=GYe;var eb="SelectContent",Qbe=N.forwardRef((t,e)=>{const r=w0(eb,t.__scopeSelect),[n,i]=N.useState();if(Ho(()=>{i(new DocumentFragment)},[]),!r.open){const o=n;return o?op.createPortal(s.jsx(Jbe,{scope:t.__scopeSelect,children:s.jsx(lF.Slot,{scope:t.__scopeSelect,children:s.jsx("div",{children:t.children})})}),o):null}return s.jsx(ewe,{...t,ref:e})});Qbe.displayName=eb;var df=10,[Jbe,S0]=fj(eb),HYe="SelectContentImpl",WYe=Gx("SelectContent.RemoveScroll"),ewe=N.forwardRef((t,e)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:c,side:a,sideOffset:f,align:m,alignOffset:y,arrowPadding:v,collisionBoundary:w,collisionPadding:j,sticky:A,hideWhenDetached:C,avoidCollisions:I,...M}=t,D=w0(eb,r),[F,z]=N.useState(null),[q,H]=N.useState(null),K=is(e,yt=>z(yt)),[J,Q]=N.useState(null),[ee,oe]=N.useState(null),de=cF(r),[ye,we]=N.useState(!1),Le=N.useRef(!1);N.useEffect(()=>{if(F)return A3(F)},[F]),E3();const Se=N.useCallback(yt=>{const[gt,...ft]=de().map(xt=>xt.ref.current),[kt]=ft.slice(-1),Vt=document.activeElement;for(const xt of yt)if(xt===Vt||(xt==null||xt.scrollIntoView({block:"nearest"}),xt===gt&&q&&(q.scrollTop=0),xt===kt&&q&&(q.scrollTop=q.scrollHeight),xt==null||xt.focus(),document.activeElement!==Vt))return},[de,q]),ve=N.useCallback(()=>Se([J,F]),[Se,J,F]);N.useEffect(()=>{ye&&ve()},[ye,ve]);const{onOpenChange:me,triggerPointerDownPosRef:ke}=D;N.useEffect(()=>{if(F){let yt={x:0,y:0};const gt=kt=>{var Vt,xt;yt={x:Math.abs(Math.round(kt.pageX)-(((Vt=ke.current)==null?void 0:Vt.x)??0)),y:Math.abs(Math.round(kt.pageY)-(((xt=ke.current)==null?void 0:xt.y)??0))}},ft=kt=>{yt.x<=10&&yt.y<=10?kt.preventDefault():F.contains(kt.target)||me(!1),document.removeEventListener("pointermove",gt),ke.current=null};return ke.current!==null&&(document.addEventListener("pointermove",gt),document.addEventListener("pointerup",ft,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",gt),document.removeEventListener("pointerup",ft,{capture:!0})}}},[F,me,ke]),N.useEffect(()=>{const yt=()=>me(!1);return window.addEventListener("blur",yt),window.addEventListener("resize",yt),()=>{window.removeEventListener("blur",yt),window.removeEventListener("resize",yt)}},[me]);const[Pe,Ee]=xwe(yt=>{const gt=de().filter(Vt=>!Vt.disabled),ft=gt.find(Vt=>Vt.ref.current===document.activeElement),kt=vwe(gt,yt,ft);kt&&setTimeout(()=>kt.ref.current.focus())}),xe=N.useCallback((yt,gt,ft)=>{const kt=!Le.current&&!ft;(D.value!==void 0&&D.value===gt||kt)&&(Q(yt),kt&&(Le.current=!0))},[D.value]),Ue=N.useCallback(()=>F==null?void 0:F.focus(),[F]),Ze=N.useCallback((yt,gt,ft)=>{const kt=!Le.current&&!ft;(D.value!==void 0&&D.value===gt||kt)&&oe(yt)},[D.value]),lt=n==="popper"?Pq:twe,wt=lt===Pq?{side:a,sideOffset:f,align:m,alignOffset:y,arrowPadding:v,collisionBoundary:w,collisionPadding:j,sticky:A,hideWhenDetached:C,avoidCollisions:I}:{};return s.jsx(Jbe,{scope:r,content:F,viewport:q,onViewportChange:H,itemRefCallback:xe,selectedItem:J,onItemLeave:Ue,itemTextRefCallback:Ze,focusSelectedItem:ve,selectedItemText:ee,position:n,isPositioned:ye,searchRef:Pe,children:s.jsx(PC,{as:WYe,allowPinchZoom:!0,children:s.jsx(IC,{asChild:!0,trapped:D.open,onMountAutoFocus:yt=>{yt.preventDefault()},onUnmountAutoFocus:Gr(i,yt=>{var gt;(gt=D.trigger)==null||gt.focus({preventScroll:!0}),yt.preventDefault()}),children:s.jsx(fb,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:yt=>yt.preventDefault(),onDismiss:()=>D.onOpenChange(!1),children:s.jsx(lt,{role:"listbox",id:D.contentId,"data-state":D.open?"open":"closed",dir:D.dir,onContextMenu:yt=>yt.preventDefault(),...M,...wt,onPlaced:()=>we(!0),ref:K,style:{display:"flex",flexDirection:"column",outline:"none",...M.style},onKeyDown:Gr(M.onKeyDown,yt=>{const gt=yt.ctrlKey||yt.altKey||yt.metaKey;if(yt.key==="Tab"&&yt.preventDefault(),!gt&&yt.key.length===1&&Ee(yt.key),["ArrowUp","ArrowDown","Home","End"].includes(yt.key)){let kt=de().filter(Vt=>!Vt.disabled).map(Vt=>Vt.ref.current);if(["ArrowUp","End"].includes(yt.key)&&(kt=kt.slice().reverse()),["ArrowUp","ArrowDown"].includes(yt.key)){const Vt=yt.target,xt=kt.indexOf(Vt);kt=kt.slice(xt+1)}setTimeout(()=>Se(kt)),yt.preventDefault()}})})})})})})});ewe.displayName=HYe;var KYe="SelectItemAlignedPosition",twe=N.forwardRef((t,e)=>{const{__scopeSelect:r,onPlaced:n,...i}=t,o=w0(eb,r),c=S0(eb,r),[a,f]=N.useState(null),[m,y]=N.useState(null),v=is(e,K=>y(K)),w=cF(r),j=N.useRef(!1),A=N.useRef(!0),{viewport:C,selectedItem:I,selectedItemText:M,focusSelectedItem:D}=c,F=N.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&m&&C&&I&&M){const K=o.trigger.getBoundingClientRect(),J=m.getBoundingClientRect(),Q=o.valueNode.getBoundingClientRect(),ee=M.getBoundingClientRect();if(o.dir!=="rtl"){const Vt=ee.left-J.left,xt=Q.left-Vt,or=K.left-xt,Tr=K.width+or,rn=Math.max(Tr,J.width),Lr=window.innerWidth-df,$r=hN(xt,[df,Math.max(df,Lr-rn)]);a.style.minWidth=Tr+"px",a.style.left=$r+"px"}else{const Vt=J.right-ee.right,xt=window.innerWidth-Q.right-Vt,or=window.innerWidth-K.right-xt,Tr=K.width+or,rn=Math.max(Tr,J.width),Lr=window.innerWidth-df,$r=hN(xt,[df,Math.max(df,Lr-rn)]);a.style.minWidth=Tr+"px",a.style.right=$r+"px"}const oe=w(),de=window.innerHeight-df*2,ye=C.scrollHeight,we=window.getComputedStyle(m),Le=parseInt(we.borderTopWidth,10),Se=parseInt(we.paddingTop,10),ve=parseInt(we.borderBottomWidth,10),me=parseInt(we.paddingBottom,10),ke=Le+Se+ye+me+ve,Pe=Math.min(I.offsetHeight*5,ke),Ee=window.getComputedStyle(C),xe=parseInt(Ee.paddingTop,10),Ue=parseInt(Ee.paddingBottom,10),Ze=K.top+K.height/2-df,lt=de-Ze,wt=I.offsetHeight/2,yt=I.offsetTop+wt,gt=Le+Se+yt,ft=ke-gt;if(gt<=Ze){const Vt=oe.length>0&&I===oe[oe.length-1].ref.current;a.style.bottom="0px";const xt=m.clientHeight-C.offsetTop-C.offsetHeight,or=Math.max(lt,wt+(Vt?Ue:0)+xt+ve),Tr=gt+or;a.style.height=Tr+"px"}else{const Vt=oe.length>0&&I===oe[0].ref.current;a.style.top="0px";const or=Math.max(Ze,Le+C.offsetTop+(Vt?xe:0)+wt)+ft;a.style.height=or+"px",C.scrollTop=gt-Ze+C.offsetTop}a.style.margin=`${df}px 0`,a.style.minHeight=Pe+"px",a.style.maxHeight=de+"px",n==null||n(),requestAnimationFrame(()=>j.current=!0)}},[w,o.trigger,o.valueNode,a,m,C,I,M,o.dir,n]);Ho(()=>F(),[F]);const[z,q]=N.useState();Ho(()=>{m&&q(window.getComputedStyle(m).zIndex)},[m]);const H=N.useCallback(K=>{K&&A.current===!0&&(F(),D==null||D(),A.current=!1)},[F,D]);return s.jsx(ZYe,{scope:r,contentWrapper:a,shouldExpandOnScrollRef:j,onScrollButtonChange:H,children:s.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:z},children:s.jsx(cn.div,{...i,ref:v,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});twe.displayName=KYe;var YYe="SelectPopperPosition",Pq=N.forwardRef((t,e)=>{const{__scopeSelect:r,align:n="start",collisionPadding:i=df,...o}=t,c=uF(r);return s.jsx(M3,{...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)"}})});Pq.displayName=YYe;var[ZYe,rK]=fj(eb,{}),Rq="SelectViewport",rwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,nonce:n,...i}=t,o=S0(Rq,r),c=rK(Rq,r),a=is(e,o.onViewportChange),f=N.useRef(0);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),s.jsx(lF.Slot,{scope:r,children:s.jsx(cn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Gr(i.onScroll,m=>{const y=m.currentTarget,{contentWrapper:v,shouldExpandOnScrollRef:w}=c;if(w!=null&&w.current&&v){const j=Math.abs(f.current-y.scrollTop);if(j>0){const A=window.innerHeight-df*2,C=parseFloat(v.style.minHeight),I=parseFloat(v.style.height),M=Math.max(C,I);if(M0?z:0,v.style.justifyContent="flex-end")}}}f.current=y.scrollTop})})})]})});rwe.displayName=Rq;var nwe="SelectGroup",[XYe,QYe]=fj(nwe),swe=N.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=ol();return s.jsx(XYe,{scope:r,id:i,children:s.jsx(cn.div,{role:"group","aria-labelledby":i,...n,ref:e})})});swe.displayName=nwe;var iwe="SelectLabel",awe=N.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=QYe(iwe,r);return s.jsx(cn.div,{id:i.id,...n,ref:e})});awe.displayName=iwe;var wO="SelectItem",[JYe,owe]=fj(wO),lwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,value:n,disabled:i=!1,textValue:o,...c}=t,a=w0(wO,r),f=S0(wO,r),m=a.value===n,[y,v]=N.useState(o??""),[w,j]=N.useState(!1),A=is(e,D=>{var F;return(F=f.itemRefCallback)==null?void 0:F.call(f,D,n,i)}),C=ol(),I=N.useRef("touch"),M=()=>{i||(a.onValueChange(n),a.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 s.jsx(JYe,{scope:r,value:n,disabled:i,textId:C,isSelected:m,onItemTextChange:N.useCallback(D=>{v(F=>F||((D==null?void 0:D.textContent)??"").trim())},[]),children:s.jsx(lF.ItemSlot,{scope:r,value:n,disabled:i,textValue:y,children:s.jsx(cn.div,{role:"option","aria-labelledby":C,"data-highlighted":w?"":void 0,"aria-selected":m&&w,"data-state":m?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...c,ref:A,onFocus:Gr(c.onFocus,()=>j(!0)),onBlur:Gr(c.onBlur,()=>j(!1)),onClick:Gr(c.onClick,()=>{I.current!=="mouse"&&M()}),onPointerUp:Gr(c.onPointerUp,()=>{I.current==="mouse"&&M()}),onPointerDown:Gr(c.onPointerDown,D=>{I.current=D.pointerType}),onPointerMove:Gr(c.onPointerMove,D=>{var F;I.current=D.pointerType,i?(F=f.onItemLeave)==null||F.call(f):I.current==="mouse"&&D.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Gr(c.onPointerLeave,D=>{var F;D.currentTarget===document.activeElement&&((F=f.onItemLeave)==null||F.call(f))}),onKeyDown:Gr(c.onKeyDown,D=>{var z;((z=f.searchRef)==null?void 0:z.current)!==""&&D.key===" "||(BYe.includes(D.key)&&M(),D.key===" "&&D.preventDefault())})})})})});lwe.displayName=wO;var Hk="SelectItemText",cwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,...o}=t,c=w0(Hk,r),a=S0(Hk,r),f=owe(Hk,r),m=VYe(Hk,r),[y,v]=N.useState(null),w=is(e,M=>v(M),f.onItemTextChange,M=>{var D;return(D=a.itemTextRefCallback)==null?void 0:D.call(a,M,f.value,f.disabled)}),j=y==null?void 0:y.textContent,A=N.useMemo(()=>s.jsx("option",{value:f.value,disabled:f.disabled,children:j},f.value),[f.disabled,f.value,j]),{onNativeOptionAdd:C,onNativeOptionRemove:I}=m;return Ho(()=>(C(A),()=>I(A)),[C,I,A]),s.jsxs(s.Fragment,{children:[s.jsx(cn.span,{id:f.textId,...o,ref:w}),f.isSelected&&c.valueNode&&!c.valueNodeHasChildren?op.createPortal(o.children,c.valueNode):null]})});cwe.displayName=Hk;var uwe="SelectItemIndicator",dwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return owe(uwe,r).isSelected?s.jsx(cn.span,{"aria-hidden":!0,...n,ref:e}):null});dwe.displayName=uwe;var Lq="SelectScrollUpButton",hwe=N.forwardRef((t,e)=>{const r=S0(Lq,t.__scopeSelect),n=rK(Lq,t.__scopeSelect),[i,o]=N.useState(!1),c=is(e,n.onScrollButtonChange);return Ho(()=>{if(r.viewport&&r.isPositioned){let a=function(){const m=f.scrollTop>0;o(m)};const f=r.viewport;return a(),f.addEventListener("scroll",a),()=>f.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(mwe,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:f}=r;a&&f&&(a.scrollTop=a.scrollTop-f.offsetHeight)}}):null});hwe.displayName=Lq;var Mq="SelectScrollDownButton",fwe=N.forwardRef((t,e)=>{const r=S0(Mq,t.__scopeSelect),n=rK(Mq,t.__scopeSelect),[i,o]=N.useState(!1),c=is(e,n.onScrollButtonChange);return Ho(()=>{if(r.viewport&&r.isPositioned){let a=function(){const m=f.scrollHeight-f.clientHeight,y=Math.ceil(f.scrollTop)f.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(mwe,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:f}=r;a&&f&&(a.scrollTop=a.scrollTop+f.offsetHeight)}}):null});fwe.displayName=Mq;var mwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,onAutoScroll:n,...i}=t,o=S0("SelectScrollButton",r),c=N.useRef(null),a=cF(r),f=N.useCallback(()=>{c.current!==null&&(window.clearInterval(c.current),c.current=null)},[]);return N.useEffect(()=>()=>f(),[f]),Ho(()=>{var y;const m=a().find(v=>v.ref.current===document.activeElement);(y=m==null?void 0:m.ref.current)==null||y.scrollIntoView({block:"nearest"})},[a]),s.jsx(cn.div,{"aria-hidden":!0,...i,ref:e,style:{flexShrink:0,...i.style},onPointerDown:Gr(i.onPointerDown,()=>{c.current===null&&(c.current=window.setInterval(n,50))}),onPointerMove:Gr(i.onPointerMove,()=>{var m;(m=o.onItemLeave)==null||m.call(o),c.current===null&&(c.current=window.setInterval(n,50))}),onPointerLeave:Gr(i.onPointerLeave,()=>{f()})})}),eZe="SelectSeparator",pwe=N.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return s.jsx(cn.div,{"aria-hidden":!0,...n,ref:e})});pwe.displayName=eZe;var Dq="SelectArrow",tZe=N.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=uF(r),o=w0(Dq,r),c=S0(Dq,r);return o.open&&c.position==="popper"?s.jsx(D3,{...i,...n,ref:e}):null});tZe.displayName=Dq;var rZe="SelectBubbleInput",gwe=N.forwardRef(({__scopeSelect:t,value:e,...r},n)=>{const i=N.useRef(null),o=is(n,i),c=KC(e);return N.useEffect(()=>{const a=i.current;if(!a)return;const f=window.HTMLSelectElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&y){const v=new Event("change",{bubbles:!0});y.call(a,e),a.dispatchEvent(v)}},[c,e]),s.jsx(cn.select,{...r,style:{...Xge,...r.style},ref:o,defaultValue:e})});gwe.displayName=rZe;function ywe(t){return t===""||t===void 0}function xwe(t){const e=go(t),r=N.useRef(""),n=N.useRef(0),i=N.useCallback(c=>{const a=r.current+c;e(a),function f(m){r.current=m,window.clearTimeout(n.current),m!==""&&(n.current=window.setTimeout(()=>f(""),1e3))}(a)},[e]),o=N.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,o]}function vwe(t,e,r){const i=e.length>1&&Array.from(e).every(m=>m===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=nZe(t,Math.max(o,0));i.length===1&&(c=c.filter(m=>m!==r));const f=c.find(m=>m.textValue.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function nZe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var sZe=Gbe,_we=Wbe,iZe=Ybe,aZe=Zbe,oZe=Xbe,bwe=Qbe,lZe=rwe,cZe=swe,wwe=awe,Swe=lwe,uZe=cwe,dZe=dwe,Twe=hwe,jwe=fwe,Ewe=pwe;const Pa=sZe,ner=cZe,Ra=iZe,va=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(_we,{ref:n,className:Xt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...r,children:[e,s.jsx(aZe,{asChild:!0,children:s.jsx(Wo,{className:"h-4 w-4 opacity-50"})})]}));va.displayName=_we.displayName;const kwe=N.forwardRef(({className:t,...e},r)=>s.jsx(Twe,{ref:r,className:Xt("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(bye,{className:"h-4 w-4"})}));kwe.displayName=Twe.displayName;const Awe=N.forwardRef(({className:t,...e},r)=>s.jsx(jwe,{ref:r,className:Xt("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(Wo,{className:"h-4 w-4"})}));Awe.displayName=jwe.displayName;const _a=N.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>s.jsx(oZe,{children:s.jsxs(bwe,{ref:i,className:Xt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:r,...n,children:[s.jsx(kwe,{}),s.jsx(lZe,{className:Xt("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),s.jsx(Awe,{})]})}));_a.displayName=bwe.displayName;const hZe=N.forwardRef(({className:t,...e},r)=>s.jsx(wwe,{ref:r,className:Xt("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));hZe.displayName=wwe.displayName;const gn=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Swe,{ref:n,className:Xt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(dZe,{children:s.jsx(pa,{className:"h-4 w-4"})})}),s.jsx(uZe,{children:e})]}));gn.displayName=Swe.displayName;const fZe=N.forwardRef(({className:t,...e},r)=>s.jsx(Ewe,{ref:r,className:Xt("-mx-1 my-1 h-px bg-muted",t),...e}));fZe.displayName=Ewe.displayName;const mZe=qg({category:cT(["general","technology","crm","marketing"]),subject:Ds().min(5,"Subject must be at least 5 characters").max(200),description:Ds().min(20,"Please provide more details (at least 20 characters)").max(1e4,"Please keep the description under 10,000 characters")}),pZe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function gZe({trigger:t}){const[e,r]=N.useState(!1),[n,i]=N.useState(!1),{user:o}=Zn(),c=GW({resolver:HW(mZe),defaultValues:{category:"general",subject:"",description:""}}),a=async f=>{if(!o){$t.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:m}=await Ce.from("support_tickets").insert({user_id:o.id,category:f.category,subject:f.subject,description:f.description});if(m)throw m;try{await Ce.functions.invoke("support-ticket-notify",{body:{category:pZe[f.category],subject:f.subject}})}catch(y){console.log("Notification send attempted:",y)}$t.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(m){console.error("Error submitting ticket:",m),$t.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return s.jsxs(Wa,{open:e,onOpenChange:r,children:[s.jsx(C_e,{asChild:!0,children:t||s.jsxs(Lt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(Q3e,{className:"h-5 w-5"}),s.jsx("span",{className:"sr-only",children:"Support"})]})}),s.jsxs(La,{className:"sm:max-w-[500px]",children:[s.jsxs(Ko,{children:[s.jsx(Po,{children:"Need Help?"}),s.jsx(sd,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),s.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[s.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",s.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),s.jsx(tK,{...c,children:s.jsxs("form",{onSubmit:c.handleSubmit(a),className:"space-y-4",children:[s.jsx(wl,{control:c.control,name:"category",render:({field:f})=>s.jsxs(rl,{children:[s.jsx(nl,{children:"Category"}),s.jsxs(Pa,{onValueChange:f.onChange,defaultValue:f.value,children:[s.jsx(sl,{children:s.jsx(va,{children:s.jsx(Ra,{placeholder:"Select a category"})})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"general",children:"General Support"}),s.jsx(gn,{value:"technology",children:"Technology Support"}),s.jsx(gn,{value:"crm",children:"CRM Support"}),s.jsx(gn,{value:"marketing",children:"Marketing Support"})]})]}),s.jsx(Cf,{})]})}),s.jsx(wl,{control:c.control,name:"subject",render:({field:f})=>s.jsxs(rl,{children:[s.jsx(nl,{children:"Subject"}),s.jsx(sl,{children:s.jsx(Or,{placeholder:"Brief description of your issue",...f})}),s.jsx(Cf,{})]})}),s.jsx(wl,{control:c.control,name:"description",render:({field:f})=>{var m;return s.jsxs(rl,{children:[s.jsx(nl,{children:"Description"}),s.jsx(sl,{children:s.jsx(qc,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...f})}),s.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[(((m=f.value)==null?void 0:m.length)??0).toLocaleString()," / 10,000"]}),s.jsx(Cf,{})]})}}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Lt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(Lt,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}function qn(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 la(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function ql(t,e){const r=qn(t);return isNaN(e)?la(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function Vd(t,e){const r=qn(t);if(isNaN(e))return la(t,NaN);if(!e)return r;const n=r.getDate(),i=la(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 nK=6048e5,yZe=864e5,sK=6e4,iK=36e5,xZe=1e3,EL=43200,lie=1440;let vZe={};function T0(){return vZe}function Uc(t,e){var a,f,m,y;const r=T0(),n=(e==null?void 0:e.weekStartsOn)??((f=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:f.weekStartsOn)??r.weekStartsOn??((y=(m=r.locale)==null?void 0:m.options)==null?void 0:y.weekStartsOn)??0,i=qn(t),o=i.getDay(),c=(o=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function Qx(t){const e=qn(t);return e.setHours(0,0,0,0),e}function Jx(t){const e=qn(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 If(t,e){const r=Qx(t),n=Qx(e),i=+r-Jx(r),o=+n-Jx(n);return Math.round((i-o)/yZe)}function _Ze(t){const e=Nwe(t),r=la(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),Mg(r)}function Oq(t,e){const r=e*7;return ql(t,r)}function bZe(t,e){return Vd(t,e*12)}function wZe(t){let e;return t.forEach(function(r){const n=qn(r);(e===void 0||e{const n=qn(r);(!e||e>n||isNaN(+n))&&(e=n)}),e||new Date(NaN)}function WM(t,e){const r=qn(t),n=qn(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function aK(t){return la(t,Date.now())}function mc(t,e){const r=Qx(t),n=Qx(e);return+r==+n}function oK(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Fq(t){if(!oK(t)&&typeof t!="number")return!1;const e=qn(t);return!isNaN(Number(e))}function uT(t,e){const r=qn(t),n=qn(e),i=r.getFullYear()-n.getFullYear(),o=r.getMonth()-n.getMonth();return i*12+o}function TZe(t,e,r){const n=Uc(t,r),i=Uc(e,r),o=+n-Jx(n),c=+i-Jx(i);return Math.round((o-c)/nK)}function jZe(t,e){const r=qn(t),n=qn(e),i=cie(r,n),o=Math.abs(If(r,n));r.setDate(r.getDate()-i*o);const c=+(cie(r,n)===-i),a=i*(o-c);return a===0?0:a}function cie(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 EZe(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function kZe(t,e){return+qn(t)-+qn(e)}function AZe(t){const e=qn(t);return e.setHours(23,59,59,999),e}function YC(t){const e=qn(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function NZe(t){const e=qn(t);return+AZe(e)==+YC(e)}function CZe(t,e){const r=qn(t),n=qn(e),i=WM(r,n),o=Math.abs(uT(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 a=WM(r,n)===-i;NZe(qn(t))&&o===1&&WM(t,n)===1&&(a=!1),c=i*(o-Number(a))}return c===0?0:c}function IZe(t,e,r){const n=kZe(t,e)/1e3;return EZe(r==null?void 0:r.roundingMethod)(n)}function PZe(t,e){const r=qn(t.start),n=qn(t.end);let i=+r>+n;const o=i?+r:+n,c=i?n:r;c.setHours(0,0,0,0);let a=1;const f=[];for(;+c<=o;)f.push(qn(c)),c.setDate(c.getDate()+a),c.setHours(0,0,0,0);return i?f.reverse():f}function Eu(t){const e=qn(t);return e.setDate(1),e.setHours(0,0,0,0),e}function Cwe(t){const e=qn(t),r=la(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function dF(t,e){var a,f,m,y;const r=T0(),n=(e==null?void 0:e.weekStartsOn)??((f=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:f.weekStartsOn)??r.weekStartsOn??((y=(m=r.locale)==null?void 0:m.options)==null?void 0:y.weekStartsOn)??0,i=qn(t),o=i.getDay(),c=(o{let n;const i=RZe[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 T6(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const MZe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},DZe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},OZe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},FZe={date:T6({formats:MZe,defaultWidth:"full"}),time:T6({formats:DZe,defaultWidth:"full"}),dateTime:T6({formats:OZe,defaultWidth:"full"})},BZe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},$Ze=(t,e,r,n)=>BZe[t];function uk(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,a=r!=null&&r.width?String(r.width):c;i=t.formattingValues[a]||t.formattingValues[c]}else{const c=t.defaultWidth,a=r!=null&&r.width?String(r.width):t.defaultWidth;i=t.values[a]||t.values[c]}const o=t.argumentCallback?t.argumentCallback(e):e;return i[o]}}const zZe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},UZe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},VZe={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"]},qZe={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"]},GZe={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"}},HZe={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"}},WZe=(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"},KZe={ordinalNumber:WZe,era:uk({values:zZe,defaultWidth:"wide"}),quarter:uk({values:UZe,defaultWidth:"wide",argumentCallback:t=>t-1}),month:uk({values:VZe,defaultWidth:"wide"}),day:uk({values:qZe,defaultWidth:"wide"}),dayPeriod:uk({values:GZe,defaultWidth:"wide",formattingValues:HZe,defaultFormattingWidth:"wide"})};function dk(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],a=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],f=Array.isArray(a)?ZZe(a,v=>v.test(c)):YZe(a,v=>v.test(c));let m;m=t.valueCallback?t.valueCallback(f):f,m=r.valueCallback?r.valueCallback(m):m;const y=e.slice(c.length);return{value:m,rest:y}}}function YZe(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function ZZe(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 a=e.slice(i.length);return{value:c,rest:a}}}const QZe=/^(\d+)(th|st|nd|rd)?/i,JZe=/\d+/i,eXe={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},tXe={any:[/^b/i,/^(a|c)/i]},rXe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},nXe={any:[/1/i,/2/i,/3/i,/4/i]},sXe={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},iXe={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]},aXe={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},oXe={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]},lXe={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},cXe={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}},uXe={ordinalNumber:XZe({matchPattern:QZe,parsePattern:JZe,valueCallback:t=>parseInt(t,10)}),era:dk({matchPatterns:eXe,defaultMatchWidth:"wide",parsePatterns:tXe,defaultParseWidth:"any"}),quarter:dk({matchPatterns:rXe,defaultMatchWidth:"wide",parsePatterns:nXe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:dk({matchPatterns:sXe,defaultMatchWidth:"wide",parsePatterns:iXe,defaultParseWidth:"any"}),day:dk({matchPatterns:aXe,defaultMatchWidth:"wide",parsePatterns:oXe,defaultParseWidth:"any"}),dayPeriod:dk({matchPatterns:lXe,defaultMatchWidth:"any",parsePatterns:cXe,defaultParseWidth:"any"})},hF={code:"en-US",formatDistance:LZe,formatLong:FZe,formatRelative:$Ze,localize:KZe,match:uXe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function dXe(t){const e=qn(t);return If(e,Cwe(e))+1}function lK(t){const e=qn(t),r=+Mg(e)-+_Ze(e);return Math.round(r/nK)+1}function cK(t,e){var y,v,w,j;const r=qn(t),n=r.getFullYear(),i=T0(),o=(e==null?void 0:e.firstWeekContainsDate)??((v=(y=e==null?void 0:e.locale)==null?void 0:y.options)==null?void 0:v.firstWeekContainsDate)??i.firstWeekContainsDate??((j=(w=i.locale)==null?void 0:w.options)==null?void 0:j.firstWeekContainsDate)??1,c=la(t,0);c.setFullYear(n+1,0,o),c.setHours(0,0,0,0);const a=Uc(c,e),f=la(t,0);f.setFullYear(n,0,o),f.setHours(0,0,0,0);const m=Uc(f,e);return r.getTime()>=a.getTime()?n+1:r.getTime()>=m.getTime()?n:n-1}function hXe(t,e){var a,f,m,y;const r=T0(),n=(e==null?void 0:e.firstWeekContainsDate)??((f=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:f.firstWeekContainsDate)??r.firstWeekContainsDate??((y=(m=r.locale)==null?void 0:m.options)==null?void 0:y.firstWeekContainsDate)??1,i=cK(t,e),o=la(t,0);return o.setFullYear(i,0,n),o.setHours(0,0,0,0),Uc(o,e)}function uK(t,e){const r=qn(t),n=+Uc(r,e)-+hXe(r,e);return Math.round(n/nK)+1}function Xi(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const $y={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return Xi(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):Xi(r+1,2)},d(t,e){return Xi(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 Xi(t.getHours()%12||12,e.length)},H(t,e){return Xi(t.getHours(),e.length)},m(t,e){return Xi(t.getMinutes(),e.length)},s(t,e){return Xi(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return Xi(i,e.length)}},d1={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},uie={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 $y.y(t,e)},Y:function(t,e,r,n){const i=cK(t,n),o=i>0?i:1-i;if(e==="YY"){const c=o%100;return Xi(c,2)}return e==="Yo"?r.ordinalNumber(o,{unit:"year"}):Xi(o,e.length)},R:function(t,e){const r=Nwe(t);return Xi(r,e.length)},u:function(t,e){const r=t.getFullYear();return Xi(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 Xi(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 Xi(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 $y.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 Xi(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=uK(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):Xi(i,e.length)},I:function(t,e,r){const n=lK(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):Xi(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):$y.d(t,e)},D:function(t,e,r){const n=dXe(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Xi(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 Xi(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 Xi(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 Xi(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=d1.noon:n===0?i=d1.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=d1.evening:n>=12?i=d1.afternoon:n>=4?i=d1.morning:i=d1.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 $y.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):$y.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Xi(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):Xi(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):$y.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):$y.s(t,e)},S:function(t,e){return $y.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return hie(n);case"XXXX":case"XX":return t_(n);case"XXXXX":case"XXX":default:return t_(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return hie(n);case"xxxx":case"xx":return t_(n);case"xxxxx":case"xxx":default:return t_(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+die(n,":");case"OOOO":default:return"GMT"+t_(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+die(n,":");case"zzzz":default:return"GMT"+t_(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return Xi(n,e.length)},T:function(t,e,r){const n=t.getTime();return Xi(n,e.length)}};function die(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+Xi(o,2)}function hie(t,e){return t%60===0?(t>0?"-":"+")+Xi(Math.abs(t)/60,2):t_(t,e)}function t_(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Xi(Math.trunc(n/60),2),o=Xi(n%60,2);return r+i+e+o}const fie=(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"})}},Pwe=(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"})}},fXe=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return fie(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}}",fie(n,e)).replace("{{time}}",Pwe(i,e))},Bq={p:Pwe,P:fXe},mXe=/^D+$/,pXe=/^Y+$/,gXe=["D","DD","YY","YYYY"];function Rwe(t){return mXe.test(t)}function Lwe(t){return pXe.test(t)}function $q(t,e,r){const n=yXe(t,e,r);if(console.warn(n),gXe.includes(t))throw new RangeError(n)}function yXe(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 xXe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,vXe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,_Xe=/^'([^]*?)'?$/,bXe=/''/g,wXe=/[a-zA-Z]/;function Ls(t,e,r){var y,v,w,j,A,C,I,M;const n=T0(),i=(r==null?void 0:r.locale)??n.locale??hF,o=(r==null?void 0:r.firstWeekContainsDate)??((v=(y=r==null?void 0:r.locale)==null?void 0:y.options)==null?void 0:v.firstWeekContainsDate)??n.firstWeekContainsDate??((j=(w=n.locale)==null?void 0:w.options)==null?void 0:j.firstWeekContainsDate)??1,c=(r==null?void 0:r.weekStartsOn)??((C=(A=r==null?void 0:r.locale)==null?void 0:A.options)==null?void 0:C.weekStartsOn)??n.weekStartsOn??((M=(I=n.locale)==null?void 0:I.options)==null?void 0:M.weekStartsOn)??0,a=qn(t);if(!Fq(a))throw new RangeError("Invalid time value");let f=e.match(vXe).map(D=>{const F=D[0];if(F==="p"||F==="P"){const z=Bq[F];return z(D,i.formatLong)}return D}).join("").match(xXe).map(D=>{if(D==="''")return{isToken:!1,value:"'"};const F=D[0];if(F==="'")return{isToken:!1,value:SXe(D)};if(uie[F])return{isToken:!0,value:D};if(F.match(wXe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+F+"`");return{isToken:!1,value:D}});i.localize.preprocessor&&(f=i.localize.preprocessor(a,f));const m={firstWeekContainsDate:o,weekStartsOn:c,locale:i};return f.map(D=>{if(!D.isToken)return D.value;const F=D.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&Lwe(F)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&Rwe(F))&&$q(F,e,String(t));const z=uie[F[0]];return z(a,F,i.localize,m)}).join("")}function SXe(t){const e=t.match(_Xe);return e?e[1].replace(bXe,"'"):t}function TXe(t,e,r){const n=T0(),i=(r==null?void 0:r.locale)??n.locale??hF,o=2520,c=WM(t,e);if(isNaN(c))throw new RangeError("Invalid time value");const a=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:c});let f,m;c>0?(f=qn(e),m=qn(t)):(f=qn(t),m=qn(e));const y=IZe(m,f),v=(Jx(m)-Jx(f))/1e3,w=Math.round((y-v)/60);let j;if(w<2)return r!=null&&r.includeSeconds?y<5?i.formatDistance("lessThanXSeconds",5,a):y<10?i.formatDistance("lessThanXSeconds",10,a):y<20?i.formatDistance("lessThanXSeconds",20,a):y<40?i.formatDistance("halfAMinute",0,a):y<60?i.formatDistance("lessThanXMinutes",1,a):i.formatDistance("xMinutes",1,a):w===0?i.formatDistance("lessThanXMinutes",1,a):i.formatDistance("xMinutes",w,a);if(w<45)return i.formatDistance("xMinutes",w,a);if(w<90)return i.formatDistance("aboutXHours",1,a);if(wn.getTime()}function dK(t,e){const r=qn(t),n=qn(e);return+r<+n}function IXe(t,e){const r=e instanceof Date?la(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 PXe=10;class Dwe{constructor(){Vr(this,"subPriority",0)}validate(e,r){return!0}}class RXe extends Dwe{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 LXe extends Dwe{constructor(){super(...arguments);Vr(this,"priority",PXe);Vr(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:la(r,IXe(r,Date))}}class $i{run(e,r,n,i){const o=this.parse(e,r,n,i);return o?{setter:new RXe(o.value,this.validate,this.set,this.priority,this.subPriority),rest:o.rest}:null}validate(e,r,n){return!0}}class MXe extends $i{constructor(){super(...arguments);Vr(this,"priority",140);Vr(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 Vo={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}/},Om={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 qo(t,e){return t&&{value:e(t.value),rest:t.rest}}function yo(t,e){const r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function Fm(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*iK+o*sK+c*xZe),rest:e.slice(r[0].length)}}function Owe(t){return yo(Vo.anyDigitsSigned,t)}function Ro(t,e){switch(t){case 1:return yo(Vo.singleDigit,e);case 2:return yo(Vo.twoDigits,e);case 3:return yo(Vo.threeDigits,e);case 4:return yo(Vo.fourDigits,e);default:return yo(new RegExp("^\\d{1,"+t+"}"),e)}}function SO(t,e){switch(t){case 1:return yo(Vo.singleDigitSigned,e);case 2:return yo(Vo.twoDigitsSigned,e);case 3:return yo(Vo.threeDigitsSigned,e);case 4:return yo(Vo.fourDigitsSigned,e);default:return yo(new RegExp("^-?\\d{1,"+t+"}"),e)}}function hK(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 Fwe(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,a=t>=o%100;i=t+c-(a?100:0)}return r?i:1-i}function Bwe(t){return t%400===0||t%4===0&&t%100!==0}class DXe extends $i{constructor(){super(...arguments);Vr(this,"priority",130);Vr(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 qo(Ro(4,r),o);case"yo":return qo(i.ordinalNumber(r,{unit:"year"}),o);default:return qo(Ro(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 a=Fwe(i.year,o);return r.setFullYear(a,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 OXe extends $i{constructor(){super(...arguments);Vr(this,"priority",130);Vr(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 qo(Ro(4,r),o);case"Yo":return qo(i.ordinalNumber(r,{unit:"year"}),o);default:return qo(Ro(n.length,r),o)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i,o){const c=cK(r,o);if(i.isTwoDigitYear){const f=Fwe(i.year,c);return r.setFullYear(f,0,o.firstWeekContainsDate),r.setHours(0,0,0,0),Uc(r,o)}const a=!("era"in n)||n.era===1?i.year:1-i.year;return r.setFullYear(a,0,o.firstWeekContainsDate),r.setHours(0,0,0,0),Uc(r,o)}}class FXe extends $i{constructor(){super(...arguments);Vr(this,"priority",130);Vr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return SO(n==="R"?4:n.length,r)}set(r,n,i){const o=la(r,0);return o.setFullYear(i,0,4),o.setHours(0,0,0,0),Mg(o)}}class BXe extends $i{constructor(){super(...arguments);Vr(this,"priority",130);Vr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return SO(n==="u"?4:n.length,r)}set(r,n,i){return r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}class $Xe extends $i{constructor(){super(...arguments);Vr(this,"priority",120);Vr(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 Ro(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 zXe extends $i{constructor(){super(...arguments);Vr(this,"priority",120);Vr(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 Ro(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 UXe extends $i{constructor(){super(...arguments);Vr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Vr(this,"priority",110)}parse(r,n,i){const o=c=>c-1;switch(n){case"M":return qo(yo(Vo.month,r),o);case"MM":return qo(Ro(2,r),o);case"Mo":return qo(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 VXe extends $i{constructor(){super(...arguments);Vr(this,"priority",110);Vr(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 qo(yo(Vo.month,r),o);case"LL":return qo(Ro(2,r),o);case"Lo":return qo(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 qXe(t,e,r){const n=qn(t),i=uK(n,r)-e;return n.setDate(n.getDate()-i*7),n}class GXe extends $i{constructor(){super(...arguments);Vr(this,"priority",100);Vr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,i){switch(n){case"w":return yo(Vo.week,r);case"wo":return i.ordinalNumber(r,{unit:"week"});default:return Ro(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i,o){return Uc(qXe(r,i,o),o)}}function HXe(t,e){const r=qn(t),n=lK(r)-e;return r.setDate(r.getDate()-n*7),r}class WXe extends $i{constructor(){super(...arguments);Vr(this,"priority",100);Vr(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 yo(Vo.week,r);case"Io":return i.ordinalNumber(r,{unit:"week"});default:return Ro(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i){return Mg(HXe(r,i))}}const KXe=[31,28,31,30,31,30,31,31,30,31,30,31],YXe=[31,29,31,30,31,30,31,31,30,31,30,31];class ZXe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(this,"subPriority",1);Vr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"d":return yo(Vo.date,r);case"do":return i.ordinalNumber(r,{unit:"date"});default:return Ro(n.length,r)}}validate(r,n){const i=r.getFullYear(),o=Bwe(i),c=r.getMonth();return o?n>=1&&n<=YXe[c]:n>=1&&n<=KXe[c]}set(r,n,i){return r.setDate(i),r.setHours(0,0,0,0),r}}class XXe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(this,"subpriority",1);Vr(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 yo(Vo.dayOfYear,r);case"Do":return i.ordinalNumber(r,{unit:"date"});default:return Ro(n.length,r)}}validate(r,n){const i=r.getFullYear();return Bwe(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 fK(t,e,r){var v,w,j,A;const n=T0(),i=(r==null?void 0:r.weekStartsOn)??((w=(v=r==null?void 0:r.locale)==null?void 0:v.options)==null?void 0:w.weekStartsOn)??n.weekStartsOn??((A=(j=n.locale)==null?void 0:j.options)==null?void 0:A.weekStartsOn)??0,o=qn(t),c=o.getDay(),f=(e%7+7)%7,m=7-i,y=e<0||e>6?e-(c+m)%7:(f+m)%7-(c+m)%7;return ql(o,y)}class QXe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(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=fK(r,i,o),r.setHours(0,0,0,0),r}}class JXe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,i,o){const c=a=>{const f=Math.floor((a-1)/7)*7;return(a+o.weekStartsOn+6)%7+f};switch(n){case"e":case"ee":return qo(Ro(n.length,r),c);case"eo":return qo(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=fK(r,i,o),r.setHours(0,0,0,0),r}}class eQe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,i,o){const c=a=>{const f=Math.floor((a-1)/7)*7;return(a+o.weekStartsOn+6)%7+f};switch(n){case"c":case"cc":return qo(Ro(n.length,r),c);case"co":return qo(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=fK(r,i,o),r.setHours(0,0,0,0),r}}function tQe(t,e){const r=qn(t),n=kXe(r),i=e-n;return ql(r,i)}class rQe extends $i{constructor(){super(...arguments);Vr(this,"priority",90);Vr(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 Ro(n.length,r);case"io":return i.ordinalNumber(r,{unit:"day"});case"iii":return qo(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 qo(i.day(r,{width:"narrow",context:"formatting"}),o);case"iiiiii":return qo(i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),o);case"iiii":default:return qo(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=tQe(r,i),r.setHours(0,0,0,0),r}}class nQe extends $i{constructor(){super(...arguments);Vr(this,"priority",80);Vr(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(hK(i),0,0,0),r}}class sQe extends $i{constructor(){super(...arguments);Vr(this,"priority",80);Vr(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(hK(i),0,0,0),r}}class iQe extends $i{constructor(){super(...arguments);Vr(this,"priority",80);Vr(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(hK(i),0,0,0),r}}class aQe extends $i{constructor(){super(...arguments);Vr(this,"priority",70);Vr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,i){switch(n){case"h":return yo(Vo.hour12h,r);case"ho":return i.ordinalNumber(r,{unit:"hour"});default:return Ro(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 oQe extends $i{constructor(){super(...arguments);Vr(this,"priority",70);Vr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,i){switch(n){case"H":return yo(Vo.hour23h,r);case"Ho":return i.ordinalNumber(r,{unit:"hour"});default:return Ro(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,i){return r.setHours(i,0,0,0),r}}class lQe extends $i{constructor(){super(...arguments);Vr(this,"priority",70);Vr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,i){switch(n){case"K":return yo(Vo.hour11h,r);case"Ko":return i.ordinalNumber(r,{unit:"hour"});default:return Ro(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 cQe extends $i{constructor(){super(...arguments);Vr(this,"priority",70);Vr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,i){switch(n){case"k":return yo(Vo.hour24h,r);case"ko":return i.ordinalNumber(r,{unit:"hour"});default:return Ro(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 uQe extends $i{constructor(){super(...arguments);Vr(this,"priority",60);Vr(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"m":return yo(Vo.minute,r);case"mo":return i.ordinalNumber(r,{unit:"minute"});default:return Ro(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setMinutes(i,0,0),r}}class dQe extends $i{constructor(){super(...arguments);Vr(this,"priority",50);Vr(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"s":return yo(Vo.second,r);case"so":return i.ordinalNumber(r,{unit:"second"});default:return Ro(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setSeconds(i,0),r}}class hQe extends $i{constructor(){super(...arguments);Vr(this,"priority",30);Vr(this,"incompatibleTokens",["t","T"])}parse(r,n){const i=o=>Math.trunc(o*Math.pow(10,-n.length+3));return qo(Ro(n.length,r),i)}set(r,n,i){return r.setMilliseconds(i),r}}class fQe extends $i{constructor(){super(...arguments);Vr(this,"priority",10);Vr(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Fm(Om.basicOptionalMinutes,r);case"XX":return Fm(Om.basic,r);case"XXXX":return Fm(Om.basicOptionalSeconds,r);case"XXXXX":return Fm(Om.extendedOptionalSeconds,r);case"XXX":default:return Fm(Om.extended,r)}}set(r,n,i){return n.timestampIsSet?r:la(r,r.getTime()-Jx(r)-i)}}class mQe extends $i{constructor(){super(...arguments);Vr(this,"priority",10);Vr(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Fm(Om.basicOptionalMinutes,r);case"xx":return Fm(Om.basic,r);case"xxxx":return Fm(Om.basicOptionalSeconds,r);case"xxxxx":return Fm(Om.extendedOptionalSeconds,r);case"xxx":default:return Fm(Om.extended,r)}}set(r,n,i){return n.timestampIsSet?r:la(r,r.getTime()-Jx(r)-i)}}class pQe extends $i{constructor(){super(...arguments);Vr(this,"priority",40);Vr(this,"incompatibleTokens","*")}parse(r){return Owe(r)}set(r,n,i){return[la(r,i*1e3),{timestampIsSet:!0}]}}class gQe extends $i{constructor(){super(...arguments);Vr(this,"priority",20);Vr(this,"incompatibleTokens","*")}parse(r){return Owe(r)}set(r,n,i){return[la(r,i),{timestampIsSet:!0}]}}const yQe={G:new MXe,y:new DXe,Y:new OXe,R:new FXe,u:new BXe,Q:new $Xe,q:new zXe,M:new UXe,L:new VXe,w:new GXe,I:new WXe,d:new ZXe,D:new XXe,E:new QXe,e:new JXe,c:new eQe,i:new rQe,a:new nQe,b:new sQe,B:new iQe,h:new aQe,H:new oQe,K:new lQe,k:new cQe,m:new uQe,s:new dQe,S:new hQe,X:new fQe,x:new mQe,t:new pQe,T:new gQe},xQe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,vQe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,_Qe=/^'([^]*?)'?$/,bQe=/''/g,wQe=/\S/,SQe=/[a-zA-Z]/;function TQe(t,e,r,n){var C,I,M,D;const i=EXe(),o=i.locale??hF,c=i.firstWeekContainsDate??((I=(C=i.locale)==null?void 0:C.options)==null?void 0:I.firstWeekContainsDate)??1,a=i.weekStartsOn??((D=(M=i.locale)==null?void 0:M.options)==null?void 0:D.weekStartsOn)??0;if(e==="")return t===""?qn(r):la(r,NaN);const f={firstWeekContainsDate:c,weekStartsOn:a,locale:o},m=[new LXe],y=e.match(vQe).map(F=>{const z=F[0];if(z in Bq){const q=Bq[z];return q(F,o.formatLong)}return F}).join("").match(xQe),v=[];for(let F of y){Lwe(F)&&$q(F,e,t),Rwe(F)&&$q(F,e,t);const z=F[0],q=yQe[z];if(q){const{incompatibleTokens:H}=q;if(Array.isArray(H)){const J=v.find(Q=>H.includes(Q.token)||Q.token===z);if(J)throw new RangeError(`The format string mustn't contain \`${J.fullToken}\` and \`${F}\` at the same time`)}else if(q.incompatibleTokens==="*"&&v.length>0)throw new RangeError(`The format string mustn't contain \`${F}\` and any other token at the same time`);v.push({token:z,fullToken:F});const K=q.run(t,F,o.match,f);if(!K)return la(r,NaN);m.push(K.setter),t=K.rest}else{if(z.match(SQe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+z+"`");if(F==="''"?F="'":z==="'"&&(F=jQe(F)),t.indexOf(F)===0)t=t.slice(F.length);else return la(r,NaN)}}if(t.length>0&&wQe.test(t))return la(r,NaN);const w=m.map(F=>F.priority).sort((F,z)=>z-F).filter((F,z,q)=>q.indexOf(F)===z).map(F=>m.filter(z=>z.priority===F).sort((z,q)=>q.subPriority-z.subPriority)).map(F=>F[0]);let j=qn(r);if(isNaN(j.getTime()))return la(r,NaN);const A={};for(const F of w){if(!F.validate(j,f))return la(r,NaN);const z=F.set(j,A,f);Array.isArray(z)?(j=z[0],Object.assign(A,z[1])):j=z}return la(r,j)}function jQe(t){return t.match(_Qe)[1].replace(bQe,"'")}function dT(t){return+qn(t)2)return e;if(/:/.test(r[0])?n=r[0]:(e.date=r[0],n=r[1],kL.timeZoneDelimiter.test(e.date)&&(e.date=t.split(kL.timeZoneDelimiter)[0],n=t.substr(e.date.length,t.length))),n){const i=kL.timezone.exec(n);i?(e.time=n.replace(i[1],""),e.timezone=i[1]):e.time=n}return e}function RQe(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 LQe(t,e){if(e===null)return new Date(NaN);const r=t.match(NQe);if(!r)return new Date(NaN);const n=!!r[4],i=hk(r[1]),o=hk(r[2])-1,c=hk(r[3]),a=hk(r[4]),f=hk(r[5])-1;if(n)return zQe(e,a,f)?OQe(e,a,f):new Date(NaN);{const m=new Date(0);return!BQe(e,o,c)||!$Qe(e,i)?new Date(NaN):(m.setUTCFullYear(e,o,Math.max(i,c)),m)}}function hk(t){return t?parseInt(t):1}function MQe(t){const e=t.match(CQe);if(!e)return NaN;const r=E6(e[1]),n=E6(e[2]),i=E6(e[3]);return UQe(r,n,i)?r*iK+n*sK+i*1e3:NaN}function E6(t){return t&&parseFloat(t.replace(",","."))||0}function DQe(t){if(t==="Z")return 0;const e=t.match(IQe);if(!e)return 0;const r=e[1]==="+"?-1:1,n=parseInt(e[2]),i=e[3]&&parseInt(e[3])||0;return VQe(n,i)?r*(n*iK+i*sK):NaN}function OQe(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 FQe=[31,null,31,30,31,30,31,31,30,31,30,31];function $we(t){return t%400===0||t%4===0&&t%100!==0}function BQe(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(FQe[e]||($we(t)?29:28))}function $Qe(t,e){return e>=1&&e<=($we(t)?366:365)}function zQe(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}function UQe(t,e,r){return t===24?e===0&&r===0:r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}function VQe(t,e){return e>=0&&e<=59}function k6(t,e){const r=qn(t),n=r.getFullYear(),i=r.getDate(),o=la(t,0);o.setFullYear(n,e,15),o.setHours(0,0,0,0);const c=jXe(o);return r.setMonth(e,Math.min(i,c)),r}function mie(t,e){const r=qn(t);return isNaN(+r)?la(t,NaN):(r.setFullYear(e),r)}function qQe(t,e){return Vd(t,-e)}const GQe=()=>{const{user:t}=Zn(),e=Bi(),[r,n]=N.useState([]),[i,o]=N.useState(0),[c,a]=N.useState(!1),[f,m]=N.useState(null),y=N.useRef(null);N.useEffect(()=>{y.current=f},[f]),N.useEffect(()=>{if(!t)return;const C=`notification_last_read_${t.id}`,I=localStorage.getItem(C);I&&!y.current&&(y.current=I,m(I));const M=`nb_cache_${t.id}`,D=60*1e3,F=async()=>{try{const J=sessionStorage.getItem(M);if(J){const Q=JSON.parse(J);if(Q.ts&&Date.now()-Q.ts{n(H);const K=y.current?new Date(y.current):null,J=H.filter(Q=>K?new Date(Q.created_at)>K:!0);o(J.length)};F();const q=Ce.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},H=>{const K=H.new;n(Q=>{const ee=[K,...Q].slice(0,20);try{sessionStorage.setItem(M,JSON.stringify({ts:Date.now(),data:ee}))}catch{}return ee});const J=y.current?new Date(y.current):null;(!J||new Date(K.created_at)>J)&&o(Q=>Q+1),Notification.permission==="granted"&&new Notification(K.title,{body:K.body,icon:"/favicon.ico"})}).subscribe();return()=>{Ce.removeChannel(q)}},[t]);const v=C=>{const I=C.toLowerCase();return I.includes("community")||I.includes("post")?Ph:I.includes("academy")||I.includes("video")?dA:I.includes("template")?w3:I.includes("event")?bo:I.includes("newsletter")?Eye:I.includes("brokerage")?A8:I.includes("swag")||I.includes("social")?Mf:I.includes("toolbox")||I.includes("tool")?BH:I.includes("brief")?ki:Ph},w=C=>{a(!1),C.url&&C.url!=="/"&&e(C.url)},j=()=>{if(!t)return;const C=new Date().toISOString(),I=`notification_last_read_${t.id}`;localStorage.setItem(I,C),m(C),o(0)},A=C=>{a(C),C&&i>0&&j()};return s.jsxs(cj,{open:c,onOpenChange:A,children:[s.jsx(uj,{asChild:!0,children:s.jsxs(Lt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(kC,{className:"h-5 w-5"}),i>0&&s.jsx(gi,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:i>9?"9+":i})]})}),s.jsxs(xb,{align:"end",className:"w-80",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[s.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&s.jsx(Lt,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:j,children:"Mark all read"})]}),s.jsx(hp,{className:"h-[300px]",children:r.length===0?s.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(C=>{const I=v(C.title);return s.jsxs(yu,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>w(C),children:[s.jsx("div",{className:"flex-shrink-0 mt-0.5",children:s.jsx(I,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-medium text-sm",children:C.title}),s.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:C.body}),s.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Mwe(new Date(C.created_at),{addSuffix:!0})})]})]},C.id)})})]})]})};function HQe(t){if(!(t!=null&&t.length))return null;const e=n=>n.is_active&&!!n.mls_provider_id&&!n.no_mls_mode,r=n=>(n.owner_type||"agent")==="agent";return t.find(n=>e(n)&&r(n)&&!!(n.mls_agent_id||n.mls_agent_key))||t.find(n=>e(n)&&r(n))||t.find(e)||t.find(r)||t[0]}function mK(){const{user:t}=Zn(),{data:e,isLoading:r}=mr({queryKey:["agent-lead-site",t==null?void 0:t.id],queryFn:async()=>{const{data:n,error:i}=await Ce.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, owner_type").eq("agent_id",t.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(i)throw i;return HQe(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 WQe(t){const[e,r]=N.useState([]),[n,i]=N.useState(!1),[o,c]=N.useState(()=>Date.now());N.useEffect(()=>{const v=setInterval(()=>c(Date.now()),15e3);return()=>clearInterval(v)},[]);const{data:a,isLoading:f}=mr({queryKey:["active-visitors",t],queryFn:async()=>{if(!t)return[];try{await Ce.rpc("cleanup_stale_visitors")}catch{}const{data:v}=await Ce.from("lead_site_active_visitors").select("*").eq("lead_site_id",t).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!v)return[];const w=v.map(C=>C.contact_id).filter(Boolean);let j={};if(w.length>0){const{data:C}=await Ce.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",w);(C||[]).forEach(I=>{j[I.id]=I})}const A=v.map(C=>C.auth_user_id).filter(Boolean);if(A.length>0){const{data:C}=await Ce.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",t).in("user_id",A);(C||[]).forEach(I=>{const M=v.find(D=>D.auth_user_id===I.user_id);M&&!M.contact_id&&I.contact_id&&(M.contact_id=I.contact_id),M&&!j[M.contact_id||""]&&I.name&&(j[M.contact_id||M.auth_user_id||""]={first_name:I.name.split(" ")[0],last_name:I.name.split(" ").slice(1).join(" ")||null,email:null,phone:I.phone})})}return v.map(C=>{var I,M;return{...C,contact_name:j[C.contact_id||C.auth_user_id||""]?`${j[C.contact_id||C.auth_user_id||""].first_name} ${j[C.contact_id||C.auth_user_id||""].last_name||""}`.trim():null,contact_email:((I=j[C.contact_id||C.auth_user_id||""])==null?void 0:I.email)||null,contact_phone:((M=j[C.contact_id||C.auth_user_id||""])==null?void 0:M.phone)||null}})},enabled:!!t,refetchInterval:6e4});N.useEffect(()=>{if(!t)return;const v=Ce.channel(`active-visitors-${t}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${t}`},w=>{w.eventType==="INSERT"?r(j=>j.find(C=>C.id===w.new.id)?j:[w.new,...j]):w.eventType==="UPDATE"?r(j=>j.map(A=>A.id===w.new.id?{...A,...w.new}:A)):w.eventType==="DELETE"&&r(j=>j.filter(A=>A.id!==w.old.id))}).subscribe(w=>{w==="SUBSCRIBED"&&i(!0)});return()=>{Ce.removeChannel(v)}},[t]);const y=(n&&e.length>0?YQe([...e,...a||[]]):a||[]).filter(v=>o-new Date(v.last_seen_at).getTime()new Date(n.last_seen_at).getTime())&&e.set(r.id,r)}return[...e.values()]}let zy=null;function A6(){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return;zy=zy||new t,zy.state==="suspended"&&zy.resume();const e=zy.currentTime;[880,1318.5].forEach((r,n)=>{const i=zy.createOscillator(),o=zy.createGain();i.type="sine",i.frequency.value=r;const c=e+n*.14;o.gain.setValueAtTime(1e-4,c),o.gain.exponentialRampToValueAtTime(.25,c+.02),o.gain.exponentialRampToValueAtTime(1e-4,c+.6),i.connect(o).connect(zy.destination),i.start(c),i.stop(c+.65)})}catch{}}function ZQe(t,e=sessionStorage){const r=`lu_ding_${t}`;return e.getItem(r)?!1:(e.setItem(r,"1"),!0)}function XQe(t,e){return[`Hi there! I'm online right now — happy to answer any questions${t&&e?` about ${t}`:""}.`,e?"Would you like a private showing or a video walkthrough of this home?":"Looking for something specific? I can send you homes that match.","Hi! Want me to send you a list of similar homes, including ones not online yet?"]}const pie="lu_live_ding";function QQe(){const{user:t}=Zn(),{leadSite:e}=mK(),r=e==null?void 0:e.id,{activeVisitors:n}=WQe(r),[i,o]=N.useState(!1),[c,a]=N.useState(null),[f,m]=N.useState([]),[y,v]=N.useState(""),[w,j]=N.useState(()=>localStorage.getItem(pie)!=="off"),A=N.useRef(w);A.current=w,N.useEffect(()=>{for(const H of n){const K=H.visitor_fingerprint||H.id;ZQe(`${r}_${K}`)&&(A.current&&A6(),$t(`${H.contact_name||"Someone"} is on your website`,{description:H.current_page_title||H.current_page_path,action:{label:"Say hi",onClick:()=>{o(!0),a(K)}}}))}},[n,r]),N.useEffect(()=>{if(!r)return;const H=new Date(Date.now()-24*3600*1e3).toISOString();Ce.from("lead_site_live_chat_messages").select("id, visitor_token, sender, body, created_at").eq("lead_site_id",r).gte("created_at",H).order("created_at").limit(500).then(({data:J})=>m(J||[]));const K=Ce.channel(`live-chat-${r}-${Math.random().toString(36).slice(2)}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"lead_site_live_chat_messages",filter:`lead_site_id=eq.${r}`},J=>{const Q=J.new;m(ee=>ee.some(oe=>oe.id===Q.id)?ee:[...ee,Q]),Q.sender==="visitor"&&(A.current&&A6(),$t("New chat reply from your website",{description:Q.body.slice(0,120),action:{label:"Open",onClick:()=>{o(!0),a(Q.visitor_token)}}}))}).subscribe();return()=>{Ce.removeChannel(K)}},[r]);const C=N.useMemo(()=>f.filter(H=>H.visitor_token===c),[f,c]),I=n.find(H=>(H.visitor_fingerprint||H.id)===c),M=XQe(I==null?void 0:I.current_page_title,!!(I!=null&&I.current_mls_number)),D=async H=>{if(!r||!c||!t||!H.trim())return;const{error:K}=await Ce.from("lead_site_live_chat_messages").insert({lead_site_id:r,visitor_token:c,sender:"agent",body:H.trim(),agent_user_id:t.id});if(K){$t.error("Message could not be sent");return}v("")};if(!r)return null;const F=n.length,z=Array.from(new Set(f.map(H=>H.visitor_token))),q=[...n.map(H=>({key:H.visitor_fingerprint||H.id,v:H})),...z.filter(H=>!n.some(K=>(K.visitor_fingerprint||K.id)===H)).map(H=>({key:H}))];return s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{variant:"ghost",size:"icon",className:"relative","aria-label":"Live website visitors",title:"Live website visitors",onClick:()=>o(H=>!H),children:[s.jsx(WD,{className:`h-5 w-5 ${F?"text-primary":""}`}),F>0&&s.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] rounded-full bg-primary text-primary-foreground text-[10px] font-bold flex items-center justify-center px-1",children:F})]}),i&&op.createPortal(s.jsxs("div",{className:"fixed top-16 right-4 z-[70] w-[min(94vw,420px)] max-h-[80vh] rounded-2xl border bg-card text-card-foreground shadow-2xl flex flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b",children:[s.jsx(WD,{className:"h-4 w-4 text-primary"}),s.jsx("p",{className:"font-semibold text-sm flex-1",children:c?"Live chat":`Live on your website (${F})`}),s.jsx("button",{"aria-label":w?"Mute ding":"Turn on ding",onClick:()=>{const H=!w;j(H),localStorage.setItem(pie,H?"on":"off"),H&&A6()},children:w?s.jsx(Pye,{className:"h-4 w-4"}):s.jsx(Rye,{className:"h-4 w-4 text-muted-foreground"})}),c&&s.jsx("button",{className:"text-xs text-primary",onClick:()=>a(null),children:"All visitors"}),s.jsx("button",{"aria-label":"Close",onClick:()=>o(!1),children:s.jsx(Ci,{className:"h-4 w-4"})})]}),c?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-4 py-2 text-xs text-muted-foreground border-b",children:I?`${I.contact_name||"Anonymous visitor"} · viewing ${I.current_page_title||I.current_page_path}`:"Visitor may have left the site"}),s.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2 bg-muted/40 min-h-[160px]",children:[C.map(H=>s.jsx("div",{className:`max-w-[85%] rounded-2xl px-3 py-2 text-sm whitespace-pre-wrap ${H.sender==="agent"?"ml-auto bg-primary text-primary-foreground":"bg-background border"}`,children:H.body},H.id)),C.length===0&&M.map(H=>s.jsx("button",{className:"block w-full text-left text-sm rounded-xl border bg-background px-3 py-2 hover:border-primary",onClick:()=>D(H),children:H},H))]}),s.jsxs("form",{className:"flex gap-2 p-2 border-t",onSubmit:H=>{H.preventDefault(),D(y)},children:[s.jsx(qc,{rows:2,value:y,maxLength:2e3,placeholder:"Write a message…",onChange:H=>v(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),D(y))}}),s.jsx(Lt,{type:"submit",size:"icon","aria-label":"Send",children:s.jsx(JA,{className:"h-4 w-4"})})]})]}):s.jsxs("div",{className:"overflow-y-auto divide-y",children:[q.length===0&&s.jsx("p",{className:"p-6 text-sm text-muted-foreground text-center",children:"No one is on your website right now. You'll hear a ding when someone arrives."}),q.map(({key:H,v:K})=>s.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[s.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${K?"bg-primary animate-pulse":"bg-muted-foreground/40"}`}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium truncate",children:(K==null?void 0:K.contact_name)||"Anonymous visitor"}),s.jsx("p",{className:"text-xs text-muted-foreground truncate",children:K?K.current_page_title||K.current_page_path:"Left the site"})]}),s.jsxs(Lt,{size:"sm",variant:f.some(J=>J.visitor_token===H)?"outline":"default",onClick:()=>a(H),children:[s.jsx(K_,{className:"h-4 w-4 mr-1"}),f.some(J=>J.visitor_token===H)?"Open":"Say hi"]})]},H))]})]}),document.body)]})}function JQe(){const{managedBrokerages:t,selectedBrokerageId:e,setSelectedBrokerageId:r}=Zn(),n=kr();if(t.length<2)return null;const i=t.find(o=>o.id===e)??t[0];return s.jsxs(cj,{children:[s.jsx(uj,{asChild:!0,children:s.jsxs(Lt,{variant:"outline",size:"sm",className:"gap-2 max-w-[220px]",title:"Switch brokerage",children:[s.jsx(to,{className:"h-4 w-4 shrink-0 text-primary"}),s.jsx("span",{className:"truncate hidden md:inline",children:i.name}),s.jsx(Wo,{className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})}),s.jsxs(xb,{align:"end",className:"w-64",children:[s.jsx(CW,{className:"text-xs text-muted-foreground",children:"Managing brokerage"}),s.jsx(iT,{}),t.map(o=>s.jsxs(yu,{onSelect:()=>{o.id!==i.id&&(r(o.id),n.invalidateQueries(),$t.success(`Now managing ${o.name}`))},children:[s.jsx(pa,{className:`mr-2 h-4 w-4 ${o.id===i.id?"opacity-100":"opacity-0"}`}),s.jsx("span",{className:"truncate",children:o.name})]},o.id))]})]})}function eJe(t){return!!t&&t.plan_tier==="free_beta"&&!!t.no_mls_mode&&!t.mls_provider_id}function zwe(t=!0){const{user:e}=Zn(),{data:r,isLoading:n}=mr({queryKey:["free-lead-site-offer",e==null?void 0:e.id],enabled:!!e&&t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i}=await Ce.from("profiles").select("brokerage_id").eq("id",e.id).maybeSingle();if(!(i!=null&&i.brokerage_id))return null;const{data:o}=await Ce.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 tJe="coaching_access";function rJe(){const{user:t,loading:e,isAdmin:r,isCoach:n}=Zn(),{data:i,isLoading:o}=mr({queryKey:["coaching-access",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const[c,a]=await Promise.all([Ce.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1),Ce.from("feature_entitlements").select("enabled, expires_at").eq("user_id",t.id).eq("feature_key",tJe).maybeSingle()]),f=(c.data||[]).length>0,m=a.data,y=!!(m!=null&&m.enabled)&&(!m.expires_at||new Date(m.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 ti=Ce,ser=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function ier(t){return t.total_items===0?"not_started":t.rejected_items>0?"changes_requested":t.approved_items>=t.total_items?"compliant":"in_review"}const aer={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function nJe(){return mr({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:t}=await Ce.auth.getUser();if(!t.user)return[];const{data:e,error:r}=await ti.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",t.user.id);if(r)throw r;return e||[]}})}function oer(t){return mr({queryKey:["transaction-admins",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.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 ti.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 a,f;return{...c,name:((a=o.get(c.user_id))==null?void 0:a.name)??null,email:((f=o.get(c.user_id))==null?void 0:f.email)??null}})}})}function ler(){const t=kr();return Ar({mutationFn:async({brokerageId:e,userId:r})=>{const{error:n}=await ti.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 cer(){const t=kr();return Ar({mutationFn:async({id:e})=>{const{error:r}=await ti.from("brokerage_transaction_admins").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function uer(t){return mr({queryKey:["compliance-settings",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("brokerage_compliance_settings").select("*").eq("brokerage_id",t).maybeSingle();if(r)throw r;return e}})}function der(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await ti.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 her(t){return mr({queryKey:["compliance-templates",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("brokerage_checklist_templates").select("*").eq("brokerage_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]}})}function fer(t){return mr({queryKey:["compliance-template-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("brokerage_checklist_template_items").select("*").eq("template_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function mer(){const t=kr();return Ar({mutationFn:async e=>{if(e.id){const{error:i}=await ti.from("brokerage_checklist_templates").update(e).eq("id",e.id);if(i)throw i;return e.id}const{data:r,error:n}=await ti.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 per(){const t=kr();return Ar({mutationFn:async({id:e})=>{const{error:r}=await ti.from("brokerage_checklist_templates").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerageId]})})}function ger(){const t=kr();return Ar({mutationFn:async e=>{if(e.id){const{error:n}=await ti.from("brokerage_checklist_template_items").update(e).eq("id",e.id);if(n)throw n;return}const{error:r}=await ti.from("brokerage_checklist_template_items").insert(e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.template_id]})})}function yer(){const t=kr();return Ar({mutationFn:async({id:e})=>{const{error:r}=await ti.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 xer(t){return mr({queryKey:["compliance-deals",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.rpc("get_brokerage_compliance_deals",{_brokerage_id:t});if(r)throw r;return e||[]}})}function ver(t){return mr({queryKey:["deal-compliance-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("deal_compliance_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function _er(t){return mr({queryKey:["deal-compliance-events",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("deal_compliance_events").select("*").eq("deal_id",t).order("created_at",{ascending:!1}).limit(200);if(r)throw r;return e||[]}})}async function ZC(t){var r;const{data:e}=await Ce.auth.getUser();await ti.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 ber(){const t=kr();return Ar({mutationFn:async({item:e,status:r,note:n})=>{var c;const{data:i}=await Ce.auth.getUser(),{error:o}=await ti.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 ZC({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 wer(){const t=kr();return Ar({mutationFn:async({dealId:e,brokerageId:r,templateId:n,deal:i})=>{const{data:o,error:c}=await ti.from("brokerage_checklist_template_items").select("*").eq("template_id",n).order("sort_order",{ascending:!0});if(c)throw c;const a=(y,v)=>{if(!y)return null;const[w,j,A]=y.split(/[-/T]/).map(Number);return new Date(Date.UTC(w,j-1,A+(v||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"?a(i==null?void 0:i.contract_date,y.due_offset_days):y.due_anchor==="target_close_date"?a(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:m}=await ti.from("deal_compliance_items").insert(f);if(m)throw m;await ZC({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 Ser(t){return mr({queryKey:["deal-compliance-files",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.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 Ter(){const t=kr();return Ar({mutationFn:async({item:e,file:r})=>{var v,w;const{data:n}=await Ce.auth.getUser(),i=(v=n.user)==null?void 0:v.id;if(!i)throw new Error("Not signed in");const{data:o}=await ti.from("deal_files").select("id, version_no").eq("compliance_item_id",e.id).order("version_no",{ascending:!1}).limit(1),c=(((w=o==null?void 0:o[0])==null?void 0:w.version_no)||0)+1,a=r.name.split(".").pop(),f=`${i}/${e.deal_id}/${crypto.randomUUID()}.${a}`,{error:m}=await Ce.storage.from("deal-files").upload(f,r);if(m)throw m;o!=null&&o.length&&await ti.from("deal_files").update({is_current:!1}).eq("compliance_item_id",e.id);const{error:y}=await ti.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 ti.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",e.id),await ZC({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 jer(t){const{data:e,error:r}=await Ce.storage.from("deal-files").createSignedUrl(t,3600);if(r)throw r;window.open(e.signedUrl,"_blank","noopener,noreferrer")}function Eer(t){return mr({queryKey:["deal-compliance-messages",t],enabled:!!t,refetchInterval:3e4,queryFn:async()=>{const{data:e,error:r}=await ti.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(a=>a.sender_user_id)));if(i.length===0)return n;const{data:o}=await ti.from("profiles").select("id, name").in("id",i),c=new Map((o||[]).map(a=>[a.id,a.name??null]));return n.map(a=>({...a,sender_name:c.get(a.sender_user_id)??null}))}})}function ker(){const t=kr();return Ar({mutationFn:async({dealId:e,brokerageId:r,body:n,senderRole:i,itemId:o})=>{var y;const{data:c}=await Ce.auth.getUser(),a=(y=c.user)==null?void 0:y.id;if(!a)throw new Error("Not signed in");const{data:f,error:m}=await ti.from("deal_compliance_messages").insert({deal_id:e,brokerage_id:r,sender_user_id:a,sender_role:i,item_id:o??null,body:n.trim()}).select("id").single();if(m)throw m;try{await Ce.functions.invoke("compliance-message-notify",{body:{messageId:f.id}})}catch(v){console.error("compliance message notify failed",v)}return f.id},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["deal-compliance-messages",r.dealId]})})}function Aer(){const t=kr();return Ar({mutationFn:async({dealId:e,senderRole:r})=>{const{error:n}=await ti.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 Ner(t){return mr({queryKey:["brokerage-agent-roster",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",t).order("name",{ascending:!0});if(r)throw r;return e||[]}})}function Cer(t){return mr({queryKey:["agent-pipeline-stages",t],enabled:!!t,queryFn:async()=>{const e=async()=>{const{data:n,error:i}=await ti.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 ti.rpc("initialize_deal_pipeline_stages",{p_user_id:t});n||(r=await e())}return r}})}function Ier(){const t=kr();return Ar({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 ti.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 ti.rpc("ensure_deal_compliance",{_deal_id:o})}catch(c){console.error("ensure_deal_compliance failed",c)}return await ZC({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 Per(t){return mr({queryKey:["staff-deal-detail",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await ti.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 Rer(){const t=kr();return Ar({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{error:n}=await ti.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 ZC({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 mF=[{id:"home",label:"Home",icon:jye,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Jm,description:"Contacts and follow-up",accent:"nav-crm"},{id:"prospecting",label:"Prospecting",icon:L8,route:"/prospecting",accent:"nav-prospecting",visible:t=>t.hasPermission("contacts")},{id:"deals",label:"Deals",icon:RH,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:to,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:L_,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:R_,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:QA,description:"Training, programs and coaching",accent:"nav-academy"},{id:"mainstage",label:"Main Stage",icon:WD,route:"/main-stage",accent:"nav-mainstage"},{id:"events",label:"Events",icon:Cye,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:U3e,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:kl,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:_3,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager||t.isOnTeam)},{id:"more",label:"More",icon:D3e,description:"Community, marketplace and help",accent:"nav-more"}],yl=t=>e=>e.hasPermission(t),sJe=[{id:"prospecting",label:"Prospecting",route:"/prospecting",icon:L8,description:"Property searches, owner contacts and saved intelligence",primaryCategory:"prospecting",section:"Prospecting",visible:yl("contacts"),displayOrder:1,searchKeywords:["prospect","contact finder","homeowner","property search","prospecting credits","dossier"]},{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:P3e,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:yl("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:ki,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"net-sheets",label:"Seller Net Sheets",route:"/mission-control/net-sheets",icon:N8,description:"Interactive walk-away estimates for sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["net sheet","seller net","proceeds","offer comparison"],displayOrder:21},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:kl,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:yl("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"contact-map",label:"Contact Map",route:"/mission-control/sphere-map",icon:ii,iconTone:"red",description:"See your sphere on a map — boundaries, farms and prospects",primaryCategory:"crm",section:"Contacts",visible:yl("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:lne,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:yl("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:dFe,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:yl("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:JA,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:yl("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:fne,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:yl("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:to,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:Hm,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:yl("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:JS,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:rs,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:L8,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:Mf,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:yl("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:RH,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:yl("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"lending-partners",label:"Lending Partners",route:"/mission-control/lenders",icon:_3,description:"Loan officers, loan milestones and lead exchange",primaryCategory:"deals",section:"Pipeline",visible:yl("pipeline"),searchKeywords:["lender","loan officer","mortgage","pre-approval","referral"],displayOrder:135},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:I8,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:yl("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:O3e,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:yl("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:pFe,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:yl("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:XA,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:yl("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:Hm,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:Hm,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:"my-listings",label:"My Listings",route:t=>t.hasLeadSiteMLS?"/my-website/mls-listings?scope=mine":"/mission-control/listings?tab=my-listings",icon:ta,description:"Your own active listings",primaryCategory:"listings",section:"Manage Listings",visible:t=>t.hasLeadSiteMLS||t.hasPermission("listings"),searchKeywords:["my listings","my properties"],displayOrder:5},{id:"mls-listings-search",label:"MLS Listings",route:"/my-website/mls-listings",icon:to,description:"Search every listing in your MLS",primaryCategory:"listings",section:"Manage Listings",visible:t=>t.hasLeadSiteMLS,searchKeywords:["mls","idx","search homes","all listings"],displayOrder:6},{id:"ad-engine",label:"AdEngine",route:"/listings/ad-engine",icon:Kz,description:"Run Facebook & Instagram ads for your listings",primaryCategory:"listings",section:"Manage Listings",secondaryPlacements:[{category:"marketing",section:"Paid Ads",displayOrder:25}],visible:()=>!0,searchKeywords:["ads","facebook ads","instagram ads","boost","adengine","paid ads","advertising"],displayOrder:7},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:to,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:yl("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:aFe,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:Sye,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:ta,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:N8,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:I8,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:hne,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:w3,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:mFe,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:vc,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:hne,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:Yz,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:Yz,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:dne,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:Eye,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:rs,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Mail Studio",route:"/mission-control/direct-mail",icon:JA,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:Mf,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:yl("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:yl("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:dne,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:Kz,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:P8,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:fne,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:H3e,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:"site-grade",label:"Site Grade",route:"/websites/grade",icon:z3e,description:"How Google, AI search and your clients see your website",primaryCategory:"websites",section:"My Website",badge:"new",visible:t=>t.hasLeadSite||t.isBrokerageManager||t.isTeamLeader||t.isAdmin,searchKeywords:["seo","aeo","site grade","audit","google","ai search","score"],displayOrder:2},{id:"get-my-website",label:"Create Website",route:"/create-website",icon:R_,description:"Choose a design and create your included agent website",primaryCategory:"websites",section:"My Website",visible:t=>!t.hasLeadSite,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"upgrade-website-idx",label:"Upgrade to IDX",route:"/create-website?upgrade=1",icon:ki,description:"Add MLS search and listings to your free website",primaryCategory:"websites",section:"My Website",badge:"new",visible:t=>!!t.hasFreeNonIdxSite,searchKeywords:["idx","upgrade","mls","website"],displayOrder:3},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:R_,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:()=>!1,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:t=>t.siteUrl||"#",icon:v3,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:kye,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:to,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:kl,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:ta,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:XA,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:lne,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"behavior-alerts",label:"Behavior Alerts",route:"/my-website/behavior-alerts",icon:rs,description:"Your branded website follow-up emails",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite&&t.hasLeadSiteMLS,searchKeywords:["behavior","alerts","email","automation","follow up"],displayOrder:55},{id:"homeowner-hubs",label:"Homeowner Hubs",route:"/my-website/homeowner-hubs",icon:ta,description:"Monthly home value emails and equity dashboards for past clients",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite&&t.hasLeadSiteMLS,searchKeywords:["homebot","homeowner","equity","home value","past clients","digest"],displayOrder:56},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:Yz,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:ki,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:QA,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:QS,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:BH,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:Cye,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:Kz,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:QA,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:Jm,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:Ph,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:K3e,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:mb,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:FH,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:YD,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:Mf,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:W3e,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:ki,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:HD,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:HD,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:ki,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:Wx,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:JS,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:to,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!!t.brokerageId&&!t.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"brokerage-lead-engine",label:"Office Lead Engine",route:"/brokerage/lead-engine",icon:L_,description:"Office campaigns, lead team and inquiry assignments",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager),searchKeywords:["office leads","lead engine","ads","pond","round robin"],displayOrder:135},{id:"admin-office-lead-engine",label:"Office Lead Engine",route:"/brokerage/lead-engine",icon:L_,description:"Office lead programs and campaign assignments",primaryCategory:"more",section:"Admin",visible:t=>t.isAdmin,searchKeywords:["office leads","brokerage ads","lead engine"],displayOrder:125},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:q3e,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:QS,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:kl,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:kl,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:DH,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:kl,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:L_,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:Wz,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-agent-websites",label:"Agent Websites",route:"/brokerage/agent-websites",icon:R_,description:"Every agent's website, status and leads",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>t.isBrokerageManager||t.isAdmin,searchKeywords:["agent websites","agent sites","domains","idx"],displayOrder:197},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:jye,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:nFe,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-deals",label:"Agent Deals",route:"/brokerage/deals",icon:A8,description:"Every agent's listings, pending deals and production",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>(t.isBrokerageManager||t.isTransactionAdmin)&&!t.isAdmin,searchKeywords:["deals","pipeline","import","production","agent deals"],displayOrder:195.5},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:Wz,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:P8,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:Qm,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:A8,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:ki,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:Wz,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 Uwe(t,e){return typeof t.route=="function"?t.route(e):t.route}function Vwe(t,e){var r;return t.primaryCategory===e?{category:e,section:t.section,displayOrder:t.displayOrder}:((r=t.secondaryPlacements)==null?void 0:r.find(n=>n.category===e))??null}function iJe(t,e){return t.map(r=>({dest:r,placement:Vwe(r,e)})).filter(r=>r.placement!==null).sort((r,n)=>(r.placement.displayOrder??r.dest.displayOrder)-(n.placement.displayOrder??n.dest.displayOrder)).map(r=>({dest:r.dest,section:r.placement.section}))}function qwe(){const{user:t,isAdmin:e,isBrokerageManager:r,isCoach:n,brokerageId:i}=Zn(),{hasPermission:o}=Z3(),{isInnerCircleEnabled:c,isMarketplaceEnabled:a,isFeatureEnabled:f}=J3(),{hasAccess:m}=PW(),{data:y,teams:v}=dj(),{leadSite:w,hasLeadSite:j,siteUrl:A}=mK(),{hasOffer:C}=zwe(!j),I=N_e(),{hasAccess:M}=rJe(),{data:D}=nJe(),F=kr(),{data:z}=mr({queryKey:["my-coach-nav",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:ve}=await Ce.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1);return(ve||[]).length>0}}),{data:q}=mr({queryKey:["user-tool-favorites",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:60*1e3,queryFn:async()=>{const{data:ve}=await Ce.from("user_tool_favorites").select("tool_id").eq("user_id",t.id);return(ve||[]).map(me=>me.tool_id)}}),H=N.useMemo(()=>new Set(q||[]),[q]),K=Ar({mutationFn:async ve=>{t!=null&&t.id&&(H.has(ve)?await Ce.from("user_tool_favorites").delete().eq("user_id",t.id).eq("tool_id",ve):await Ce.from("user_tool_favorites").insert({user_id:t.id,tool_id:ve}))},onSuccess:()=>{F.invalidateQueries({queryKey:["user-tool-favorites"]}),F.invalidateQueries({queryKey:["app-catalog"]})}}),J=N.useMemo(()=>{var ve,me;return{isAdmin:!!e,isBrokerageManager:!!r,isTransactionAdmin:((D==null?void 0:D.length)||0)>0,isCoach:!!n,isOnTeam:!!y,isTeamLeader:(v||[]).some(ke=>ke.role==="team_leader"),hasCoach:!!z,brokerageId:i??null,hasPermission:o,isInnerCircleEnabled:!!c,stagingStudioEnabled:f("staging_studio_enabled"),isMarketplaceEnabled:!!a,hasWeeklyReels:!!m,hasLeadSite:!!j,hasLeadSiteMLS:!!(w!=null&&w.mls_provider_id),hasFreeNonIdxSite:eJe(w),hasFreeSiteOffer:!!C,leadSiteId:(w==null?void 0:w.id)??null,siteUrl:A??null,email:(t==null?void 0:t.email)??null,isPartnershipMember:I.isMember,hasCoachingOnboarding:I.isMember&&!!((ve=I.pkg)!=null&&ve.includes_coaching),hasCoachingAccess:!!M||I.isMember&&!!((me=I.pkg)!=null&&me.includes_coaching)}},[e,r,D,n,y,v,z,i,o,c,a,f,m,j,w,C,A,t==null?void 0:t.email,I.isMember,I.pkg,M]),Q=N.useMemo(()=>sJe.filter(ve=>ve.visible?ve.visible(J):!0).map(ve=>{if(!I.isRestricted)return ve;const me=Z9e(ve);return!me||I.hasFeature(me)?ve:{...ve,locked:!0,route:`/upgrade/${me}`}}).sort((ve,me)=>ve.displayOrder-me.displayOrder),[J,I.isRestricted,I.features]),ee=N.useMemo(()=>mF.filter(ve=>ve.visible?ve.visible(J):!0),[J]),oe=N.useMemo(()=>ee.filter(ve=>!ve.route).map(ve=>{const me=[],ke=new Map;for(const{dest:Pe,section:Ee}of iJe(Q,ve.id))ke.has(Ee)||(ke.set(Ee,[]),me.push(Ee)),ke.get(Ee).push(Pe);return{id:ve.id,label:ve.label,sections:me.map(Pe=>({title:Pe,items:ke.get(Pe)}))}}),[Q,ee]),de=N.useMemo(()=>new Map(oe.map(ve=>[ve.id,ve])),[oe]),ye=ve=>ve.toolId||`nav:${ve.id}`,we=ve=>H.has(ye(ve));return{ctx:J,categories:oe,railCategories:ee,categoryMap:de,destinations:Q,favorites:H,isFavorite:we,favoritesFor:ve=>Q.filter(me=>Vwe(me,ve)!==null&&we(me)),favoriteKey:ye,toggleFavorite:ve=>K.mutate(ve),searchDestinations:ve=>{const me=ve.trim().toLowerCase();return me?Q.map(Pe=>{const Ee=Pe.label.toLowerCase(),xe=(Pe.description||"").toLowerCase(),Ue=(Pe.searchKeywords||[]).join(" ").toLowerCase();let Ze=0;return Ee===me?Ze=100:Ee.startsWith(me)?Ze=80:Ee.includes(me)?Ze=60:Ue.includes(me)?Ze=40:xe.includes(me)?Ze=20:Pe.section.toLowerCase().includes(me)&&(Ze=10),Ze&&we(Pe)&&(Ze+=5),{d:Pe,score:Ze}}).filter(Pe=>Pe.score>0).sort((Pe,Ee)=>Ee.score-Pe.score).map(Pe=>Pe.d):[]},routeFor:ve=>Uwe(ve,J)}}var gie=1,aJe=.9,oJe=.8,lJe=.17,N6=.1,C6=.999,cJe=.9999,uJe=.99,dJe=/[\\\/_+.#"@\[\(\{&]/,hJe=/[\\\/_+.#"@\[\(\{&]/g,fJe=/[\s-]/,Gwe=/[\s-]/g;function zq(t,e,r,n,i,o,c){if(o===e.length)return i===t.length?gie:uJe;var a=`${i},${o}`;if(c[a]!==void 0)return c[a];for(var f=n.charAt(o),m=r.indexOf(f,i),y=0,v,w,j,A;m>=0;)v=zq(t,e,r,n,m+1,o+1,c),v>y&&(m===i?v*=gie:dJe.test(t.charAt(m-1))?(v*=oJe,j=t.slice(i,m-1).match(hJe),j&&i>0&&(v*=Math.pow(C6,j.length))):fJe.test(t.charAt(m-1))?(v*=aJe,A=t.slice(i,m-1).match(Gwe),A&&i>0&&(v*=Math.pow(C6,A.length))):(v*=lJe,i>0&&(v*=Math.pow(C6,m-i))),t.charAt(m)!==e.charAt(o)&&(v*=cJe)),(vv&&(v=w*N6)),v>y&&(y=v),m=r.indexOf(f,m+1);return c[a]=y,y}function yie(t){return t.toLowerCase().replace(Gwe," ")}function mJe(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,zq(t,e,yie(t),yie(e),0,0,{})}var fk='[cmdk-group=""]',I6='[cmdk-group-items=""]',pJe='[cmdk-group-heading=""]',Hwe='[cmdk-item=""]',xie=`${Hwe}:not([aria-disabled="true"])`,Uq="cmdk-item-select",L1="data-value",gJe=(t,e,r)=>mJe(t,e,r),Wwe=N.createContext(void 0),XC=()=>N.useContext(Wwe),Kwe=N.createContext(void 0),pK=()=>N.useContext(Kwe),Ywe=N.createContext(void 0),Zwe=N.forwardRef((t,e)=>{let r=M1(()=>{var xe,Ue;return{search:"",value:(Ue=(xe=t.value)!=null?xe:t.defaultValue)!=null?Ue:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=M1(()=>new Set),i=M1(()=>new Map),o=M1(()=>new Map),c=M1(()=>new Set),a=Xwe(t),{label:f,children:m,value:y,onValueChange:v,filter:w,shouldFilter:j,loop:A,disablePointerSelection:C=!1,vimBindings:I=!0,...M}=t,D=ol(),F=ol(),z=ol(),q=N.useRef(null),H=kJe();tb(()=>{if(y!==void 0){let xe=y.trim();r.current.value=xe,K.emit()}},[y]),tb(()=>{H(6,ye)},[]);let K=N.useMemo(()=>({subscribe:xe=>(c.current.add(xe),()=>c.current.delete(xe)),snapshot:()=>r.current,setState:(xe,Ue,Ze)=>{var lt,wt,yt,gt;if(!Object.is(r.current[xe],Ue)){if(r.current[xe]=Ue,xe==="search")de(),ee(),H(1,oe);else if(xe==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ft=document.getElementById(z);ft?ft.focus():(lt=document.getElementById(D))==null||lt.focus()}if(H(7,()=>{var ft;r.current.selectedItemId=(ft=we())==null?void 0:ft.id,K.emit()}),Ze||H(5,ye),((wt=a.current)==null?void 0:wt.value)!==void 0){let ft=Ue??"";(gt=(yt=a.current).onValueChange)==null||gt.call(yt,ft);return}}K.emit()}},emit:()=>{c.current.forEach(xe=>xe())}}),[]),J=N.useMemo(()=>({value:(xe,Ue,Ze)=>{var lt;Ue!==((lt=o.current.get(xe))==null?void 0:lt.value)&&(o.current.set(xe,{value:Ue,keywords:Ze}),r.current.filtered.items.set(xe,Q(Ue,Ze)),H(2,()=>{ee(),K.emit()}))},item:(xe,Ue)=>(n.current.add(xe),Ue&&(i.current.has(Ue)?i.current.get(Ue).add(xe):i.current.set(Ue,new Set([xe]))),H(3,()=>{de(),ee(),r.current.value||oe(),K.emit()}),()=>{o.current.delete(xe),n.current.delete(xe),r.current.filtered.items.delete(xe);let Ze=we();H(4,()=>{de(),(Ze==null?void 0:Ze.getAttribute("id"))===xe&&oe(),K.emit()})}),group:xe=>(i.current.has(xe)||i.current.set(xe,new Set),()=>{o.current.delete(xe),i.current.delete(xe)}),filter:()=>a.current.shouldFilter,label:f||t["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:D,inputId:z,labelId:F,listInnerRef:q}),[]);function Q(xe,Ue){var Ze,lt;let wt=(lt=(Ze=a.current)==null?void 0:Ze.filter)!=null?lt:gJe;return xe?wt(xe,r.current.search,Ue):0}function ee(){if(!r.current.search||a.current.shouldFilter===!1)return;let xe=r.current.filtered.items,Ue=[];r.current.filtered.groups.forEach(lt=>{let wt=i.current.get(lt),yt=0;wt.forEach(gt=>{let ft=xe.get(gt);yt=Math.max(ft,yt)}),Ue.push([lt,yt])});let Ze=q.current;Le().sort((lt,wt)=>{var yt,gt;let ft=lt.getAttribute("id"),kt=wt.getAttribute("id");return((yt=xe.get(kt))!=null?yt:0)-((gt=xe.get(ft))!=null?gt:0)}).forEach(lt=>{let wt=lt.closest(I6);wt?wt.appendChild(lt.parentElement===wt?lt:lt.closest(`${I6} > *`)):Ze.appendChild(lt.parentElement===Ze?lt:lt.closest(`${I6} > *`))}),Ue.sort((lt,wt)=>wt[1]-lt[1]).forEach(lt=>{var wt;let yt=(wt=q.current)==null?void 0:wt.querySelector(`${fk}[${L1}="${encodeURIComponent(lt[0])}"]`);yt==null||yt.parentElement.appendChild(yt)})}function oe(){let xe=Le().find(Ze=>Ze.getAttribute("aria-disabled")!=="true"),Ue=xe==null?void 0:xe.getAttribute(L1);K.setState("value",Ue||void 0)}function de(){var xe,Ue,Ze,lt;if(!r.current.search||a.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let wt=0;for(let yt of n.current){let gt=(Ue=(xe=o.current.get(yt))==null?void 0:xe.value)!=null?Ue:"",ft=(lt=(Ze=o.current.get(yt))==null?void 0:Ze.keywords)!=null?lt:[],kt=Q(gt,ft);r.current.filtered.items.set(yt,kt),kt>0&&wt++}for(let[yt,gt]of i.current)for(let ft of gt)if(r.current.filtered.items.get(ft)>0){r.current.filtered.groups.add(yt);break}r.current.filtered.count=wt}function ye(){var xe,Ue,Ze;let lt=we();lt&&(((xe=lt.parentElement)==null?void 0:xe.firstChild)===lt&&((Ze=(Ue=lt.closest(fk))==null?void 0:Ue.querySelector(pJe))==null||Ze.scrollIntoView({block:"nearest"})),lt.scrollIntoView({block:"nearest"}))}function we(){var xe;return(xe=q.current)==null?void 0:xe.querySelector(`${Hwe}[aria-selected="true"]`)}function Le(){var xe;return Array.from(((xe=q.current)==null?void 0:xe.querySelectorAll(xie))||[])}function Se(xe){let Ue=Le()[xe];Ue&&K.setState("value",Ue.getAttribute(L1))}function ve(xe){var Ue;let Ze=we(),lt=Le(),wt=lt.findIndex(gt=>gt===Ze),yt=lt[wt+xe];(Ue=a.current)!=null&&Ue.loop&&(yt=wt+xe<0?lt[lt.length-1]:wt+xe===lt.length?lt[0]:lt[wt+xe]),yt&&K.setState("value",yt.getAttribute(L1))}function me(xe){let Ue=we(),Ze=Ue==null?void 0:Ue.closest(fk),lt;for(;Ze&&!lt;)Ze=xe>0?jJe(Ze,fk):EJe(Ze,fk),lt=Ze==null?void 0:Ze.querySelector(xie);lt?K.setState("value",lt.getAttribute(L1)):ve(xe)}let ke=()=>Se(Le().length-1),Pe=xe=>{xe.preventDefault(),xe.metaKey?ke():xe.altKey?me(1):ve(1)},Ee=xe=>{xe.preventDefault(),xe.metaKey?Se(0):xe.altKey?me(-1):ve(-1)};return N.createElement(cn.div,{ref:e,tabIndex:-1,...M,"cmdk-root":"",onKeyDown:xe=>{var Ue;(Ue=M.onKeyDown)==null||Ue.call(M,xe);let Ze=xe.nativeEvent.isComposing||xe.keyCode===229;if(!(xe.defaultPrevented||Ze))switch(xe.key){case"n":case"j":{I&&xe.ctrlKey&&Pe(xe);break}case"ArrowDown":{Pe(xe);break}case"p":case"k":{I&&xe.ctrlKey&&Ee(xe);break}case"ArrowUp":{Ee(xe);break}case"Home":{xe.preventDefault(),Se(0);break}case"End":{xe.preventDefault(),ke();break}case"Enter":{xe.preventDefault();let lt=we();if(lt){let wt=new Event(Uq);lt.dispatchEvent(wt)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:J.inputId,id:J.labelId,style:NJe},f),pF(t,xe=>N.createElement(Kwe.Provider,{value:K},N.createElement(Wwe.Provider,{value:J},xe))))}),yJe=N.forwardRef((t,e)=>{var r,n;let i=ol(),o=N.useRef(null),c=N.useContext(Ywe),a=XC(),f=Xwe(t),m=(n=(r=f.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;tb(()=>{if(!m)return a.item(i,c==null?void 0:c.id)},[m]);let y=Qwe(i,o,[t.value,t.children,o],t.keywords),v=pK(),w=e0(H=>H.value&&H.value===y.current),j=e0(H=>m||a.filter()===!1?!0:H.search?H.filtered.items.get(i)>0:!0);N.useEffect(()=>{let H=o.current;if(!(!H||t.disabled))return H.addEventListener(Uq,A),()=>H.removeEventListener(Uq,A)},[j,t.onSelect,t.disabled]);function A(){var H,K;C(),(K=(H=f.current).onSelect)==null||K.call(H,y.current)}function C(){v.setState("value",y.current,!0)}if(!j)return null;let{disabled:I,value:M,onSelect:D,forceMount:F,keywords:z,...q}=t;return N.createElement(cn.div,{ref:Cg(o,e),...q,id:i,"cmdk-item":"",role:"option","aria-disabled":!!I,"aria-selected":!!w,"data-disabled":!!I,"data-selected":!!w,onPointerMove:I||a.getDisablePointerSelection()?void 0:C,onClick:I?void 0:A},t.children)}),xJe=N.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...o}=t,c=ol(),a=N.useRef(null),f=N.useRef(null),m=ol(),y=XC(),v=e0(j=>i||y.filter()===!1?!0:j.search?j.filtered.groups.has(c):!0);tb(()=>y.group(c),[]),Qwe(c,a,[t.value,t.heading,f]);let w=N.useMemo(()=>({id:c,forceMount:i}),[i]);return N.createElement(cn.div,{ref:Cg(a,e),...o,"cmdk-group":"",role:"presentation",hidden:v?void 0:!0},r&&N.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:m},r),pF(t,j=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?m:void 0},N.createElement(Ywe.Provider,{value:w},j))))}),vJe=N.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=N.useRef(null),o=e0(c=>!c.search);return!r&&!o?null:N.createElement(cn.div,{ref:Cg(i,e),...n,"cmdk-separator":"",role:"separator"})}),_Je=N.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,o=pK(),c=e0(m=>m.search),a=e0(m=>m.selectedItemId),f=XC();return N.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),N.createElement(cn.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":a,id:f.inputId,type:"text",value:i?t.value:c,onChange:m=>{i||o.setState("search",m.target.value),r==null||r(m.target.value)}})}),bJe=N.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,o=N.useRef(null),c=N.useRef(null),a=e0(m=>m.selectedItemId),f=XC();return N.useEffect(()=>{if(c.current&&o.current){let m=c.current,y=o.current,v,w=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let j=m.offsetHeight;y.style.setProperty("--cmdk-list-height",j.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(v),w.unobserve(m)}}},[]),N.createElement(cn.div,{ref:Cg(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":n,id:f.listId},pF(t,m=>N.createElement("div",{ref:Cg(c,f.listInnerRef),"cmdk-list-sizer":""},m)))}),wJe=N.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:o,container:c,...a}=t;return N.createElement(C3,{open:r,onOpenChange:n},N.createElement(I3,{container:c},N.createElement(JT,{"cmdk-overlay":"",className:i}),N.createElement(ej,{"aria-label":t.label,"cmdk-dialog":"",className:o},N.createElement(Zwe,{ref:e,...a}))))}),SJe=N.forwardRef((t,e)=>e0(r=>r.filtered.count===0)?N.createElement(cn.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),TJe=N.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...o}=t;return N.createElement(cn.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},pF(t,c=>N.createElement("div",{"aria-hidden":!0},c)))}),od=Object.assign(Zwe,{List:bJe,Item:yJe,Input:_Je,Group:xJe,Separator:vJe,Dialog:wJe,Empty:SJe,Loading:TJe});function jJe(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function EJe(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function Xwe(t){let e=N.useRef(t);return tb(()=>{e.current=t}),e}var tb=typeof window>"u"?N.useEffect:N.useLayoutEffect;function M1(t){let e=N.useRef();return e.current===void 0&&(e.current=t()),e}function e0(t){let e=pK(),r=()=>t(e.snapshot());return N.useSyncExternalStore(e.subscribe,r,r)}function Qwe(t,e,r,n=[]){let i=N.useRef(),o=XC();return tb(()=>{var c;let a=(()=>{var m;for(let y of r){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),f=n.map(m=>m.trim());o.value(t,a,f),(c=e.current)==null||c.setAttribute(L1,a),i.current=a}),i}var kJe=()=>{let[t,e]=N.useState(),r=M1(()=>new Map);return tb(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function AJe(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function pF({asChild:t,children:e},r){return t&&N.isValidElement(e)?N.cloneElement(AJe(e),{ref:e.ref},r(e.props.children)):r(e)}var NJe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const pN=N.forwardRef(({className:t,...e},r)=>s.jsx(od,{ref:r,className:Xt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));pN.displayName=od.displayName;const CJe=({children:t,...e})=>s.jsx(Wa,{...e,children:s.jsx(La,{className:"overflow-hidden p-0 shadow-lg",children:s.jsx(pN,{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})})}),gN=N.forwardRef(({className:t,...e},r)=>s.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[s.jsx(nd,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),s.jsx(od.Input,{ref:r,className:Xt("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})]}));gN.displayName=od.Input.displayName;const yN=N.forwardRef(({className:t,...e},r)=>s.jsx(od.List,{ref:r,className:Xt("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));yN.displayName=od.List.displayName;const xN=N.forwardRef((t,e)=>s.jsx(od.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));xN.displayName=od.Empty.displayName;const fg=N.forwardRef(({className:t,...e},r)=>s.jsx(od.Group,{ref:r,className:Xt("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}));fg.displayName=od.Group.displayName;const IJe=N.forwardRef(({className:t,...e},r)=>s.jsx(od.Separator,{ref:r,className:Xt("-mx-1 h-px bg-border",t),...e}));IJe.displayName=od.Separator.displayName;const Ef=N.forwardRef(({className:t,...e},r)=>s.jsx(od.Item,{ref:r,className:Xt("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}));Ef.displayName=od.Item.displayName;const wd=t=>Number.isFinite(Number(t))?Number(t):0,rg=t=>Math.round(t*100)/100,PJe=[{id:"closing",label:"Closing / settlement fee",amount:200},{id:"owners",label:"Owner's title insurance",amount:711.7},{id:"search",label:"Search & exam fee",amount:250},{id:"tief",label:"TIEF fee",amount:5},{id:"deed",label:"Deed preparation",amount:75},{id:"cpl",label:"Closing protection letter",amount:25}];function RJe(){return{listingCommissionPct:3,buyerCommissionPct:3,brokerageFee:0,titleFees:PJe.map(t=>({...t})),firstPayoff:0,secondPayoff:0,annualTaxes:0,taxesInArrears:!0,otherCosts:[]}}function LJe(t,e=5){const r=Math.max(0,wd(t)),n=Math.round(r*e/100/1e3)*1e3;return[{id:"low",label:"Quick sale",price:Math.max(0,r-n),concessions:0,repairs:0},{id:"target",label:"Target price",price:r,concessions:0,repairs:0},{id:"high",label:"Top of market",price:r+n,concessions:0,repairs:0}]}function Ler(t){const e=Math.max(0,wd(t));return["A","B","C"].map(r=>({id:`offer-${r}`,label:`Offer ${r}`,price:e,concessions:0,repairs:0}))}function MJe(t){if(!t)return null;const[e,r,n]=t.split(/[-/T]/).map(Number);if(!e||!r||!n)return null;const i=e%4===0&&e%100!==0||e%400===0,o=[31,i?29:28,31,30,31,30,31,31,30,31,30,31];let c=n;for(let a=0;aI+wd(M.amount),0)),m=rg(wd(t.firstPayoff)+wd(t.secondPayoff)),y=DJe(t.annualTaxes,r,t.taxesInArrears),v=rg((t.otherCosts||[]).reduce((I,M)=>I+wd(M.amount),0)),w=wd(e.concessions),j=wd(e.repairs),A=rg(c+a+f+m+y+v+w+j),C=rg(n-A);return{price:n,commission:c,listingCommission:i,buyerCommission:o,brokerageFee:a,titleTotal:f,payoffs:m,taxProration:y,concessions:w,repairs:j,otherTotal:v,totalCosts:A,net:C,netPct:n>0?C/n:0}}const wm=(t,e=!1)=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:e?2:0,maximumFractionDigits:e?2:0}).format(t||0),QC=()=>Ce.from("seller_net_sheets"),Mer=t=>`${window.location.origin}/net-sheet/${t}`;function Der(t){const e=zs();return mr({queryKey:["net-sheets",e,t??"all"],enabled:!!e,queryFn:async()=>{let r=QC().select("*").eq("owner_user_id",e).order("updated_at",{ascending:!1});t&&(r=r.eq("deal_id",t));const{data:n,error:i}=await r.range(0,999);if(i)throw i;return n??[]}})}function Oer(t){return mr({queryKey:["net-sheet",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await QC().select("*").eq("id",t).single();if(r)throw r;return e}})}function FJe(){const t=zs(),e=kr();return Ar({mutationFn:async r=>{const{price:n,...i}=r,{data:o,error:c}=await QC().insert({...i,owner_user_id:t,title:r.title??"Seller net sheet",mode:"price",inputs:RJe(),scenarios:LJe(n||3e5)}).select().single();if(c)throw c;return o},onSuccess:()=>e.invalidateQueries({queryKey:["net-sheets"]})})}function Fer(){const t=kr();return Ar({mutationFn:async({id:e,...r})=>{const{error:n}=await QC().update(r).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["net-sheets"]}),t.invalidateQueries({queryKey:["net-sheet",r.id]})}})}function Ber(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await QC().delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["net-sheets"]})})}function BJe(t){return mr({queryKey:["public-net-sheet",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ce.rpc("get_public_net_sheet",{_slug:t});if(r)throw r;return e}})}const $Je=[{id:"new-net-sheet",label:"New Net Sheet",hint:"Show a seller what they walk away with",keywords:["net","sheet","seller","proceeds"],path:"/mission-control/net-sheets"},{id:"drop-contract",label:"Drop Contract",hint:"Upload a purchase agreement to a deal",keywords:["contract","pdf","purchase","agreement","upload","dates"],path:"/mission-control/pipeline"},{id:"record-video",label:"Record Video",hint:"Open Video Studio",keywords:["video","record","studio","camera"],path:"/video-studio"},{id:"new-contact",label:"New Contact",hint:"Add someone to your CRM",keywords:["contact","add","lead","person"],path:"/mission-control/contacts?new=true"},{id:"new-deal",label:"Open Pipeline",hint:"See and add deals",keywords:["deal","pipeline","transaction","new"],path:"/mission-control/pipeline"},{id:"new-task",label:"My Tasks",hint:"See and add tasks",keywords:["task","todo","follow"],path:"/mission-control/tasks"},{id:"new-cma",label:"New CMA",hint:"Build a market analysis",keywords:["cma","market","analysis","comps","value"],path:"/mission-control/cma"},{id:"my-calendar",label:"My Calendar",hint:"Appointments and showings",keywords:["calendar","appointment","schedule"],path:"/mission-control/calendar"}];function zJe(t,e=$Je){const r=t.trim().toLowerCase();if(!r)return e.slice(0,4);const n=r.split(/\s+/);return e.filter(i=>{const o=`${i.label} ${i.keywords.join(" ")}`.toLowerCase();return n.every(c=>o.includes(c))})}function UJe(t){return/mac|iphone|ipad|ipod/i.test(t)?"⌘K":"Ctrl K"}function VJe(t){return t.replace(/[,()*%\\]/g," ").trim()}const qJe={event:{label:"Events",icon:Hm,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:w3,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:QA,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:BH,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:ki,color:"bg-fuchsia-500/10 text-fuchsia-600"}},vie=({hotkey:t=!0}={})=>{const[e,r]=N.useState(!1),[n,i]=N.useState(""),[o,c]=N.useState([]),[a,f]=N.useState(!1),m=Bi(),{searchDestinations:y,isFavorite:v,routeFor:w}=qwe(),j=n.trim()?y(n).slice(0,4):[],A=zs(),[C,I]=N.useState([]),[M,D]=N.useState([]),F=zJe(n),z=FJe(),q=typeof navigator<"u"?UJe(navigator.platform||navigator.userAgent):"Ctrl K",H=async ee=>{if(ee.id==="new-net-sheet"){r(!1),i("");try{const oe=await z.mutateAsync({});m(`/mission-control/net-sheets/${oe.id}`)}catch{m(ee.path)}return}J(ee.path)};N.useEffect(()=>{if(!t)return;const ee=oe=>{oe.key==="k"&&(oe.metaKey||oe.ctrlKey)&&(oe.preventDefault(),r(de=>!de))};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[t]);const K=N.useCallback(async ee=>{if(!ee.trim()){c([]),I([]),D([]);return}f(!0);const oe=`%${ee}%`;try{const[de,ye,we,Le,Se]=await Promise.all([Ce.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${oe},description.ilike.${oe}`).limit(5),Ce.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${oe},description.ilike.${oe}`).limit(5),Ce.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${oe},description.ilike.${oe}`).limit(5),Ce.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${oe},description.ilike.${oe}`).limit(5),Ce.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${oe},description.ilike.${oe}`).limit(5)]),ve=[],me=VJe(ee);if(me&&A){const ke=`%${me}%`,Pe=me.split(/\s+/),Ee=Pe.length>1?`and(first_name.ilike.%${Pe[0]}%,last_name.ilike.%${Pe.slice(1).join(" ")}%)`:null,[xe,Ue]=await Promise.all([Ce.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city").eq("owner_user_id",A).or([`first_name.ilike.${ke}`,`last_name.ilike.${ke}`,`email.ilike.${ke}`,`phone.ilike.${ke}`,`address.ilike.${ke}`,Ee].filter(Boolean).join(",")).limit(6),Ce.from("deal_pipeline").select("id, deal_name, property_address, city, deal_type").eq("owner_user_id",A).or(`deal_name.ilike.${ke},property_address.ilike.${ke},city.ilike.${ke}`).limit(6)]);I((xe.data??[]).map(Ze=>({id:Ze.id,title:[Ze.first_name,Ze.last_name].filter(Boolean).join(" ")||Ze.email||"Contact",sub:[Ze.phone,Ze.email,Ze.address].filter(Boolean).join(" · ")}))),D((Ue.data??[]).map(Ze=>({id:Ze.id,title:Ze.property_address||Ze.deal_name||"Deal",sub:[Ze.deal_name!==Ze.property_address?Ze.deal_name:null,Ze.city,Ze.deal_type].filter(Boolean).join(" · ")})))}de.data&&de.data.forEach(ke=>{ve.push({id:ke.id,title:ke.title,description:ke.description,type:"event",date:ke.event_date,path:`/event/${ke.id}`})}),ye.data&&ye.data.forEach(ke=>{ve.push({id:ke.id,title:ke.name,description:ke.description,type:"template",date:ke.publish_date,path:`/templates/${ke.id}`})}),we.data&&we.data.forEach(ke=>{ve.push({id:ke.id,title:ke.title,description:ke.description,type:"academy",date:ke.publish_date,path:`/academy/${ke.id}`})}),Le.data&&Le.data.forEach(ke=>{ve.push({id:ke.id,title:ke.name,description:ke.description,type:"toolbox",date:ke.publish_date,path:`/toolbox/${ke.id}`})}),Se.data&&Se.data.forEach(ke=>{ve.push({id:ke.id,title:ke.title,description:ke.description,type:"social-swag",date:ke.publish_date,path:`/social-swag/${ke.id}`})}),c(ve)}catch(de){console.error("Search error:",de)}finally{f(!1)}},[A]);N.useEffect(()=>{const ee=setTimeout(()=>{K(n)},200);return()=>clearTimeout(ee)},[n,K]);const J=ee=>{r(!1),i(""),m(ee)},Q=o.reduce((ee,oe)=>(ee[oe.type]||(ee[oe.type]=[]),ee[oe.type].push(oe),ee),{});return s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{variant:"outline","aria-label":"Search contacts, deals and actions",className:"relative h-9 w-9 p-0 md:h-10 md:w-full md:max-w-xl md:justify-start md:rounded-full md:bg-muted/40 md:px-4 md:pr-16 hover:bg-muted",onClick:()=>r(!0),children:[s.jsx(nd,{className:"h-4 w-4 md:mr-2 text-muted-foreground"}),s.jsx("span",{className:"hidden md:inline-flex truncate text-muted-foreground text-sm",children:"Search contacts, addresses, or type an action…"}),s.jsx("kbd",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 hidden h-6 select-none items-center rounded border bg-background px-1.5 font-mono text-[11px] font-medium text-muted-foreground md:flex",children:q})]}),s.jsxs(CJe,{open:e,onOpenChange:r,children:[s.jsx(gN,{placeholder:"Name, address, or an action like “New Net Sheet”…",value:n,onValueChange:i}),s.jsxs(yN,{className:"max-h-[70vh]",children:[C.length>0&&s.jsx(fg,{heading:"Contacts",children:C.map(ee=>s.jsxs(Ef,{value:`contact-${ee.id}-${ee.title}-${ee.sub}-${n}`,onSelect:()=>J(`/mission-control/contacts/${ee.id}`),className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("div",{className:"p-2 rounded-full bg-primary/10 text-primary",children:s.jsx(Wl,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium truncate",children:ee.title}),ee.sub&&s.jsx("div",{className:"text-sm text-muted-foreground truncate",children:ee.sub})]})]},`c-${ee.id}`))}),M.length>0&&s.jsx(fg,{heading:"Deals",children:M.map(ee=>s.jsxs(Ef,{value:`deal-${ee.id}-${ee.title}-${ee.sub}-${n}`,onSelect:()=>J(`/mission-control/pipeline?deal=${ee.id}`),className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("div",{className:"p-2 rounded-md bg-secondary text-secondary-foreground",children:s.jsx(ta,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium truncate",children:ee.title}),ee.sub&&s.jsx("div",{className:"text-sm text-muted-foreground truncate",children:ee.sub})]})]},`d-${ee.id}`))}),F.length>0&&s.jsx(fg,{heading:n?"Actions":"Quick actions",children:F.map(ee=>s.jsxs(Ef,{value:`action-${ee.id}-${ee.label}-${ee.keywords.join(" ")}`,onSelect:()=>H(ee),className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("div",{className:"p-2 rounded-md bg-accent text-accent-foreground",children:s.jsx(JS,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium truncate",children:ee.label}),s.jsx("div",{className:"text-sm text-muted-foreground truncate",children:ee.hint})]})]},`a-${ee.id}`))}),j.length>0&&s.jsx(fg,{heading:"Go to",children:j.map(ee=>{const oe=ee.icon;return s.jsxs(Ef,{value:`nav-${ee.id}-${ee.label}`,onSelect:()=>{const de=w(ee);ee.external||ee.openInNewTab?(r(!1),i(""),window.open(de,"_blank","noopener,noreferrer")):J(de)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:s.jsx(oe,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[ee.label,v(ee)&&s.jsx(qD,{className:"h-3 w-3 fill-current text-primary"})]}),ee.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate",children:ee.description})]}),s.jsx(gi,{variant:"secondary",className:"text-xs shrink-0",children:ee.section})]},`nav-${ee.id}`)})}),a&&s.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!a&&n&&o.length===0&&j.length===0&&C.length===0&&M.length===0&&F.length===0&&s.jsxs(xN,{children:['No results found for "',n,'"']}),!a&&!n&&s.jsx("div",{className:"py-3 text-center text-xs text-muted-foreground",children:"Type a name, address or phone — or an action"}),Object.entries(Q).map(([ee,oe])=>{const de=qJe[ee],ye=de.icon;return s.jsx(fg,{heading:de.label,children:oe.map(we=>s.jsxs(Ef,{value:`${we.type}-${we.id}-${we.title}`,onSelect:()=>J(we.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:`p-2 rounded-md ${de.color}`,children:s.jsx(ye,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium truncate",children:we.title}),we.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:we.description})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[s.jsx(gi,{variant:"secondary",className:"text-xs",children:de.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Mwe(new Date(we.date),{addSuffix:!0})})]})]},`${we.type}-${we.id}`))},ee)})]})]})]})},GJe=({expiresAt:t,className:e,showUpgradeButton:r=!0})=>{const[n,i]=N.useState(null),o=Bi();if(N.useEffect(()=>{const m=()=>{const v=new Date().getTime(),j=new Date(t).getTime()-v;if(j<=0){i({days:0,hours:0,minutes:0});return}const A=Math.floor(j/(1e3*60*60*24)),C=Math.floor(j%(1e3*60*60*24)/(1e3*60*60)),I=Math.floor(j%(1e3*60*60)/(1e3*60));i({days:A,hours:C,minutes:I})};m();const y=setInterval(m,6e4);return()=>clearInterval(y)},[t]),!n)return null;const c=n.days===0&&n.hours===0&&n.minutes===0,a=n.days<=1,f=n.days<=3&&!a;return c?s.jsxs("div",{className:Xt("flex items-center justify-between gap-3 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",e),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(XT,{className:"h-4 w-4 text-destructive"}),s.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&s.jsxs(Lt,{size:"sm",onClick:()=>o("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[s.jsx(ki,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):s.jsxs("div",{className:Xt("flex items-center justify-between gap-3 px-4 py-2 rounded-lg border transition-colors",a?"bg-destructive/10 border-destructive/20":f?"bg-amber-500/10 border-amber-500/20":"bg-primary/10 border-primary/20",e),children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Hl,{className:Xt("h-4 w-4",a?"text-destructive":f?"text-amber-500":"text-primary")}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:Xt("text-sm font-medium",a?"text-destructive":f?"text-amber-600":"text-primary"),children:"Free Trial:"}),s.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&s.jsxs("span",{className:Xt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.days,"d"]}),s.jsxs("span",{className:Xt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),s.jsxs("span",{className:Xt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),s.jsx("span",{className:Xt("text-xs",a?"text-destructive/70":f?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&s.jsxs(Lt,{size:"sm",onClick:()=>o("/subscription"),variant:a?"destructive":f?"default":"outline",className:Xt("text-xs h-7 px-3",f&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[s.jsx(ki,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},HJe=()=>{const t=Bi();return s.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:s.jsxs(Kn,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[s.jsxs(Rd,{className:"text-center pb-2",children:[s.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:s.jsx(XT,{className:"h-8 w-8 text-destructive"})}),s.jsx(Ld,{className:"text-2xl",children:"Your Free Trial Has Ended"}),s.jsx(dN,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),s.jsxs(ss,{className:"space-y-6",children:[s.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[s.jsx(Kn,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(ss,{className:"p-5 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(kl,{className:"h-6 w-6 text-primary"})}),s.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),s.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",s.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),s.jsxs(Lt,{className:"w-full",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(ki,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),s.jsx(Kn,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(ss,{className:"p-5 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:s.jsx(to,{className:"h-6 w-6 text-amber-600"})}),s.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),s.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",s.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),s.jsxs(Lt,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(to,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),s.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),s.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[s.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[s.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(Fn,{className:"h-4 w-4"}),s.jsx("span",{children:"1-866-527-8668"})]}),s.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(rs,{className:"h-4 w-4"}),s.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},WJe=({hasUnseenBrief:t,onClick:e,className:r})=>s.jsxs(wze,{children:[s.jsx(Sze,{asChild:!0,children:s.jsxs(Lt,{variant:"ghost",size:"icon",onClick:e,className:Xt("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[s.jsx(L_,{className:"h-5 w-5"}),t&&s.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),s.jsx(d0e,{children:s.jsx("p",{children:"The LevelUp Brief"})})]});var gF="Checkbox",[KJe,$er]=dl(gF),[YJe,gK]=KJe(gF);function ZJe(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:o,form:c,name:a,onCheckedChange:f,required:m,value:y="on",internal_do_not_use_render:v}=t,[w,j]=rd({prop:r,defaultProp:i??!1,onChange:f,caller:gF}),[A,C]=N.useState(null),[I,M]=N.useState(null),D=N.useRef(!1),F=A?!!c||!!A.closest("form"):!0,z={checked:w,disabled:o,setChecked:j,control:A,setControl:C,name:a,form:c,value:y,hasConsumerStoppedPropagationRef:D,required:m,defaultChecked:Fx(i)?!1:i,isFormControl:F,bubbleInput:I,setBubbleInput:M};return s.jsx(YJe,{scope:e,...z,children:XJe(v)?v(z):n})}var Jwe="CheckboxTrigger",e1e=N.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:r,...n},i)=>{const{control:o,value:c,disabled:a,checked:f,required:m,setControl:y,setChecked:v,hasConsumerStoppedPropagationRef:w,isFormControl:j,bubbleInput:A}=gK(Jwe,t),C=is(i,y),I=N.useRef(f);return N.useEffect(()=>{const M=o==null?void 0:o.form;if(M){const D=()=>v(I.current);return M.addEventListener("reset",D),()=>M.removeEventListener("reset",D)}},[o,v]),s.jsx(cn.button,{type:"button",role:"checkbox","aria-checked":Fx(f)?"mixed":f,"aria-required":m,"data-state":i1e(f),"data-disabled":a?"":void 0,disabled:a,value:c,...n,ref:C,onKeyDown:Gr(e,M=>{M.key==="Enter"&&M.preventDefault()}),onClick:Gr(r,M=>{v(D=>Fx(D)?!0:!D),A&&j&&(w.current=M.isPropagationStopped(),w.current||M.stopPropagation())})})});e1e.displayName=Jwe;var yK=N.forwardRef((t,e)=>{const{__scopeCheckbox:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:f,onCheckedChange:m,form:y,...v}=t;return s.jsx(ZJe,{__scopeCheckbox:r,checked:i,defaultChecked:o,disabled:a,required:c,onCheckedChange:m,name:n,form:y,value:f,internal_do_not_use_render:({isFormControl:w})=>s.jsxs(s.Fragment,{children:[s.jsx(e1e,{...v,ref:e,__scopeCheckbox:r}),w&&s.jsx(s1e,{__scopeCheckbox:r})]})})});yK.displayName=gF;var t1e="CheckboxIndicator",r1e=N.forwardRef((t,e)=>{const{__scopeCheckbox:r,forceMount:n,...i}=t,o=gK(t1e,r);return s.jsx(Pl,{present:n||Fx(o.checked)||o.checked===!0,children:s.jsx(cn.span,{"data-state":i1e(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e,style:{pointerEvents:"none",...t.style}})})});r1e.displayName=t1e;var n1e="CheckboxBubbleInput",s1e=N.forwardRef(({__scopeCheckbox:t,...e},r)=>{const{control:n,hasConsumerStoppedPropagationRef:i,checked:o,defaultChecked:c,required:a,disabled:f,name:m,value:y,form:v,bubbleInput:w,setBubbleInput:j}=gK(n1e,t),A=is(r,j),C=KC(o),I=OC(n);N.useEffect(()=>{const D=w;if(!D)return;const F=window.HTMLInputElement.prototype,q=Object.getOwnPropertyDescriptor(F,"checked").set,H=!i.current;if(C!==o&&q){const K=new Event("click",{bubbles:H});D.indeterminate=Fx(o),q.call(D,Fx(o)?!1:o),D.dispatchEvent(K)}},[w,C,o,i]);const M=N.useRef(Fx(o)?!1:o);return s.jsx(cn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??M.current,required:a,disabled:f,name:m,value:y,form:v,...e,tabIndex:-1,ref:A,style:{...e.style,...I,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});s1e.displayName=n1e;function XJe(t){return typeof t=="function"}function Fx(t){return t==="indeterminate"}function i1e(t){return Fx(t)?"indeterminate":t?"checked":"unchecked"}const mj=N.forwardRef(({className:t,...e},r)=>s.jsx(yK,{ref:r,className:Xt("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(r1e,{className:Xt("flex items-center justify-center text-current"),children:s.jsx(pa,{className:"h-4 w-4"})})}));mj.displayName=yK.displayName;var xK="Radio",[QJe,a1e]=dl(xK),[JJe,eet]=QJe(xK),o1e=N.forwardRef((t,e)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:o,disabled:c,value:a="on",onCheck:f,form:m,...y}=t,[v,w]=N.useState(null),j=is(e,I=>w(I)),A=N.useRef(!1),C=v?m||!!v.closest("form"):!0;return s.jsxs(JJe,{scope:r,checked:i,disabled:c,children:[s.jsx(cn.button,{type:"button",role:"radio","aria-checked":i,"data-state":d1e(i),"data-disabled":c?"":void 0,disabled:c,value:a,...y,ref:j,onClick:Gr(t.onClick,I=>{i||f==null||f(),C&&(A.current=I.isPropagationStopped(),A.current||I.stopPropagation())})}),C&&s.jsx(u1e,{control:v,bubbles:!A.current,name:n,value:a,checked:i,required:o,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});o1e.displayName=xK;var l1e="RadioIndicator",c1e=N.forwardRef((t,e)=>{const{__scopeRadio:r,forceMount:n,...i}=t,o=eet(l1e,r);return s.jsx(Pl,{present:n||o.checked,children:s.jsx(cn.span,{"data-state":d1e(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e})})});c1e.displayName=l1e;var tet="RadioBubbleInput",u1e=N.forwardRef(({__scopeRadio:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=N.useRef(null),a=is(c,o),f=KC(r),m=OC(e);return N.useEffect(()=>{const y=c.current;if(!y)return;const v=window.HTMLInputElement.prototype,j=Object.getOwnPropertyDescriptor(v,"checked").set;if(f!==r&&j){const A=new Event("click",{bubbles:n});j.call(y,r),y.dispatchEvent(A)}},[f,r,n]),s.jsx(cn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...m,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});u1e.displayName=tet;function d1e(t){return t?"checked":"unchecked"}var ret=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],yF="RadioGroup",[net,zer]=dl(yF,[lj,a1e]),h1e=lj(),f1e=a1e(),[set,iet]=net(yF),m1e=N.forwardRef((t,e)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:o,required:c=!1,disabled:a=!1,orientation:f,dir:m,loop:y=!0,onValueChange:v,...w}=t,j=h1e(r),A=gb(m),[C,I]=rd({prop:o,defaultProp:i??null,onChange:v,caller:yF});return s.jsx(set,{scope:r,name:n,required:c,disabled:a,value:C,onValueChange:I,children:s.jsx(_W,{asChild:!0,...j,orientation:f,dir:A,loop:y,children:s.jsx(cn.div,{role:"radiogroup","aria-required":c,"aria-orientation":f,"data-disabled":a?"":void 0,dir:A,...w,ref:e})})})});m1e.displayName=yF;var p1e="RadioGroupItem",g1e=N.forwardRef((t,e)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,o=iet(p1e,r),c=o.disabled||n,a=h1e(r),f=f1e(r),m=N.useRef(null),y=is(e,m),v=o.value===i.value,w=N.useRef(!1);return N.useEffect(()=>{const j=C=>{ret.includes(C.key)&&(w.current=!0)},A=()=>w.current=!1;return document.addEventListener("keydown",j),document.addEventListener("keyup",A),()=>{document.removeEventListener("keydown",j),document.removeEventListener("keyup",A)}},[]),s.jsx(bW,{asChild:!0,...a,focusable:!c,active:v,children:s.jsx(o1e,{disabled:c,required:o.required,checked:v,...f,...i,name:o.name,ref:y,onCheck:()=>o.onValueChange(i.value),onKeyDown:Gr(j=>{j.key==="Enter"&&j.preventDefault()}),onFocus:Gr(i.onFocus,()=>{var j;w.current&&((j=m.current)==null||j.click())})})})});g1e.displayName=p1e;var aet="RadioGroupIndicator",y1e=N.forwardRef((t,e)=>{const{__scopeRadioGroup:r,...n}=t,i=f1e(r);return s.jsx(c1e,{...i,...n,ref:e})});y1e.displayName=aet;var x1e=m1e,v1e=g1e,oet=y1e;const _1e=N.forwardRef(({className:t,...e},r)=>s.jsx(x1e,{className:Xt("grid gap-2",t),...e,ref:r}));_1e.displayName=x1e.displayName;const b1e=N.forwardRef(({className:t,...e},r)=>s.jsx(v1e,{ref:r,className:Xt("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(oet,{className:"flex items-center justify-center",children:s.jsx(W_,{className:"h-2.5 w-2.5 fill-current text-current"})})}));b1e.displayName=v1e.displayName;const cet=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=Zn(),[o,c]=N.useState({}),[a,f]=N.useState({}),[m,y]=N.useState([]);N.useEffect(()=>{e&&i&&t.polls.length>0&&v()},[e,i,t.polls]);const v=async()=>{if(!i)return;const I=t.polls.map(D=>D.id),{data:M}=await Ce.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",i.id).in("poll_id",I);if(M){const D={};M.forEach(F=>{D[F.poll_id]||(D[F.poll_id]=[]),D[F.poll_id].push(F.option_id)}),f(D)}},w=(I,M)=>{c(D=>({...D,[I]:M}))},j=(I,M,D)=>{c(F=>{const z=F[I]||[];return D?{...F,[I]:[...z,M]}:{...F,[I]:z.filter(q=>q!==M)}})},A=async I=>{if(!i)return;const M=o[I];if(!M||Array.isArray(M)&&M.length===0){$t.error("Please select an option");return}y(D=>[...D,I]);try{await Ce.from("levelup_brief_poll_responses").delete().eq("poll_id",I).eq("user_id",i.id);const D=Array.isArray(M)?M:[M],F=D.map(q=>({poll_id:I,option_id:q,user_id:i.id})),{error:z}=await Ce.from("levelup_brief_poll_responses").insert(F);if(z)throw z;f(q=>({...q,[I]:D})),$t.success("Response submitted!")}catch(D){console.error("Error submitting poll response:",D),$t.error("Failed to submit response")}finally{y(D=>D.filter(F=>F!==I))}},C=I=>(I.includes("mediadelivery.net")||I.includes("bunny"),I);return s.jsx(Wa,{open:e,onOpenChange:I=>!I&&r(),children:s.jsxs(La,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[s.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[s.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:s.jsx(Ci,{className:"h-5 w-5 text-white"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:s.jsx(L_,{className:"h-6 w-6"})}),s.jsxs("div",{children:[s.jsx(gi,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),s.jsx(Po,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})]}),s.jsx(hp,{className:"max-h-[calc(90vh-240px)]",children:s.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&s.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.brief.description}}),t.brief.video_url&&s.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:s.jsx("iframe",{src:C(t.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),t.brief.graphic_url&&!t.brief.video_url&&s.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:t.brief.graphic_link_url?s.jsx("a",{href:t.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),t.links.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(I=>s.jsxs(Lt,{variant:"outline",size:"sm",onClick:()=>window.open(I.url,"_blank"),className:"gap-2",children:[s.jsx(mb,{className:"h-4 w-4"}),I.title]},I.id))})]}),t.polls.map(I=>{var F,z;const M=((F=a[I.id])==null?void 0:F.length)>0,D=m.includes(I.id);return s.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:I.question}),M&&s.jsxs(gi,{variant:"secondary",className:"gap-1",children:[s.jsx(Il,{className:"h-3 w-3"}),"Responded"]})]}),I.poll_type==="single"?s.jsx(_1e,{value:o[I.id]||((z=a[I.id])==null?void 0:z[0])||"",onValueChange:q=>w(I.id,q),className:"space-y-2",children:I.options.map(q=>s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(b1e,{value:q.id,id:q.id}),s.jsx(Br,{htmlFor:q.id,className:"cursor-pointer",children:q.option_text})]},q.id))}):s.jsx("div",{className:"space-y-2",children:I.options.map(q=>{const K=(o[I.id]||a[I.id]||[]).includes(q.id);return s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(mj,{id:q.id,checked:K,onCheckedChange:J=>j(I.id,q.id,J)}),s.jsx(Br,{htmlFor:q.id,className:"cursor-pointer",children:q.option_text})]},q.id)})}),s.jsx(Lt,{size:"sm",onClick:()=>A(I.id),disabled:D,children:D?"Submitting...":M?"Update Response":"Submit"})]},I.id)})]})}),s.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[s.jsx(Lt,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),s.jsx(Lt,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},uet=()=>{const{user:t}=Zn(),[e,r]=N.useState(null),[n,i]=N.useState(!1),[o,c]=N.useState(!0),[a,f]=N.useState(!1),m=N.useCallback(async()=>{if(!t){c(!1);return}try{const{data:A,error:C}=await Ce.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(C||!A){c(!1);return}const{data:I}=await Ce.from("levelup_brief_views").select("*").eq("brief_id",A.id).eq("user_id",t.id).maybeSingle(),[M,D]=await Promise.all([Ce.from("levelup_brief_links").select("*").eq("brief_id",A.id).order("sort_order"),Ce.from("levelup_brief_polls").select("*").eq("brief_id",A.id).order("sort_order")]),F=[];if(D.data)for(const J of D.data){const{data:Q}=await Ce.from("levelup_brief_poll_options").select("*").eq("poll_id",J.id).order("sort_order");F.push({...J,options:Q||[]})}const z={brief:A,links:M.data||[],polls:F};r(z);const q=!!I,H=(I==null?void 0:I.dismissed_at)!=null,K=localStorage.getItem(`brief-dismissed-${A.id}`)==="true";if(H||K)f(!1),i(!1);else if(!q)i(!0),f(!0);else if(A.show_frequency==="every_login")i(!0),f(!0);else if(A.show_frequency==="daily"){const J=new Date(I.viewed_at);(new Date().getTime()-J.getTime())/(1e3*60*60)>=24&&(i(!0),f(!0))}else f(!1)}catch(A){console.error("Error fetching brief:",A)}finally{c(!1)}},[t]);N.useEffect(()=>{m()},[m]);const y=async()=>{if(!(!t||!e))try{const{data:A}=await Ce.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();A?await Ce.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",A.id):await Ce.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(A){console.error("Error marking brief as viewed:",A)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:a,loading:o,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),y()},dismissBrief:async()=>{if(!(!t||!e)){i(!1),f(!1);try{const{data:A,error:C}=await Ce.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();if(C&&console.error("Error checking existing brief view:",C),A){const{error:I}=await Ce.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",A.id).eq("user_id",t.id);I&&console.error("Error updating brief dismiss:",I)}else{const{error:I}=await Ce.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id,dismissed_at:new Date().toISOString()});I&&console.error("Error inserting brief dismiss:",I)}localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}catch(A){console.error("Error dismissing brief:",A),e&&localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}}},refetch:m}};function det(){const[t,e]=N.useState(!1),[r,n]=N.useState(!1),[i,o]=N.useState(null);N.useEffect(()=>{const f=localStorage.getItem("install-banner-dismissed"),m=localStorage.getItem("install-banner-shown");if(f||m)return;if(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches||window.matchMedia("(display-mode: minimal-ui)").matches||window.navigator.standalone===!0||document.referrer.startsWith("android-app://")){localStorage.setItem("install-banner-dismissed","true");return}if(!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const w=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(w),e(!0),localStorage.setItem("install-banner-shown","true");const j=A=>{A.preventDefault(),o(A)};return window.addEventListener("beforeinstallprompt",j),()=>{window.removeEventListener("beforeinstallprompt",j)}},[]);const c=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","true"),e(!1)},a=async()=>{if(i){await i.prompt();const{outcome:f}=await i.userChoice;f==="accepted"&&c(),o(null)}};return t?s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[s.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:s.jsx(yc,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?s.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",s.jsx(hFe,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):s.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&i&&s.jsx(Lt,{size:"sm",variant:"secondary",onClick:a,className:"text-xs",children:"Install"}),s.jsx(Lt,{size:"sm",variant:"secondary",onClick:c,className:"text-xs",children:"Got it"}),s.jsx("button",{onClick:c,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:s.jsx(Ci,{className:"h-4 w-4"})})]})]})}):null}const het=({children:t,onRefresh:e})=>{const[r,n]=N.useState(!1),[i,o]=N.useState(0),[c,a]=N.useState(!1),f=N.useRef(null),m=N.useRef(0),y=kr(),v=80,w=120,j=N.useCallback(D=>{const F=f.current;F&&F.scrollTop<=0&&(m.current=D.touches[0].clientY,n(!0))},[]),A=N.useCallback(D=>{if(!r||c)return;const F=f.current;if(!F||F.scrollTop>0){n(!1),o(0);return}const q=D.touches[0].clientY-m.current;if(q>0){const K=Math.min(q*.5,w);o(K),K>10&&D.preventDefault()}},[r,c]),C=N.useCallback(async()=>{if(r)if(n(!1),i>=v&&!c){a(!0),o(v);try{e?await e():await y.invalidateQueries()}catch(D){console.error("Refresh failed:",D)}finally{a(!1),o(0)}}else o(0)},[r,i,c,e,y]),I=Math.min(i/v,1),M=I*180;return s.jsxs("div",{ref:f,className:"h-full overflow-auto",onTouchStart:j,onTouchMove:A,onTouchEnd:C,children:[s.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:i>0?i:0,opacity:I},children:s.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${c?"animate-spin":""}`,style:{transform:c?void 0:`rotate(${M}deg)`,transition:c?void 0:"transform 0.1s ease-out"},children:s.jsx(Aye,{className:"h-5 w-5 text-primary"})})}),s.jsx("div",{style:{transform:i>0?`translateY(${Math.max(0,i-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:t})]})},fet=()=>{const{user:t}=Zn(),[e,r]=N.useState(!1),[n,i]=N.useState(!1),[o,c]=N.useState(0),[a,f]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!t){f(!1);return}try{const{data:j}=await Ce.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(j){i(!0),r(!1),f(!1);return}const{data:A}=await Ce.from("profiles").select("login_count").eq("id",t.id).single(),C=(A==null?void 0:A.login_count)||0;c(C);const I=sessionStorage.getItem("review-prompt-dismissed");r(C>=4&&!I)}catch(j){console.error("Error checking review eligibility:",j)}finally{f(!1)}})()},[t]);const m=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),y=N.useCallback(async(w,j)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:A}=await Ce.from("membership_reviews").insert({user_id:t.id,rating:w,review_text:j});if(A)throw A;return i(!0),r(!1),{success:!0,pointsAwarded:25}}catch(A){return console.error("Error submitting review:",A),{success:!1,error:A.message}}},[t]),v=N.useCallback(async()=>{if(t)try{await Ce.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",t.id)}catch(w){console.error("Error updating Google review status:",w)}},[t]);return{shouldShowPrompt:e,hasSubmittedReview:n,loginCount:o,isLoading:a,dismissPrompt:m,submitReview:y,markPostedToGoogle:v}},met="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",pet=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=fet(),[o,c]=N.useState(!1),[a,f]=N.useState("review"),[m,y]=N.useState(0),[v,w]=N.useState(0),[j,A]=N.useState(""),[C,I]=N.useState(!1),[M,D]=N.useState(!1);if(e||!t&&!M)return null;const F=async()=>{if(m===0){Fi({title:"Please select a rating",variant:"destructive"});return}I(!0);const H=await n(m,j);I(!1),H.success?(D(!0),Fi({title:"Thank you for your feedback!",description:"Your review helps us improve."}),f("google")):Fi({title:"Error submitting review",description:H.error,variant:"destructive"})},z=async H=>{H&&(await navigator.clipboard.writeText(j||`${m} star rating for LevelUp!`),Fi({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(met,"_blank")),c(!1),r()},q=()=>{c(!1),r()};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>c(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[s.jsx(vc,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),s.jsx(Wa,{open:o,onOpenChange:q,children:s.jsx(La,{className:"sm:max-w-md",children:a==="review"?s.jsxs(s.Fragment,{children:[s.jsxs(Ko,{children:[s.jsx(Po,{className:"text-center",children:"How are you enjoying LevelUp?"}),s.jsx(sd,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(H=>s.jsx("button",{type:"button",onClick:()=>y(H),onMouseEnter:()=>w(H),onMouseLeave:()=>w(0),className:"p-1 transition-transform hover:scale-110",children:s.jsx(vc,{className:Xt("h-8 w-8 transition-colors",(v||m)>=H?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},H))}),s.jsx(qc,{placeholder:"Tell us about your experience (optional)",value:j,onChange:H=>A(H.target.value),rows:4,className:"resize-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Lt,{variant:"outline",onClick:q,className:"flex-1",children:"Maybe Later"}),s.jsx(Lt,{onClick:F,disabled:C||m===0,className:"flex-1",children:C?"Submitting...":"Submit Review"})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Ko,{children:[s.jsx(Po,{className:"text-center",children:"🎉 Thank you!"}),s.jsx(sd,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Lt,{variant:"outline",onClick:()=>z(!1),className:"flex-1",children:"No Thanks"}),s.jsx(Lt,{onClick:()=>z(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function get(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(!v){c(!1);return}(async()=>{try{const C="vapid_public_key";let I=localStorage.getItem(C);if(!I){const{data:F,error:z}=await Ce.functions.invoke("get-vapid-public-key",{body:{}});if(z)throw z;if(I=(F==null?void 0:F.vapidPublicKey)??null,!I)throw new Error("Missing VAPID public key");localStorage.setItem(C,I)}y(I);const M=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});f(M),r(Notification.permission);const D=await M.pushManager.getSubscription();i(!!D)}catch(C){console.error("Error initializing push notifications:",C)}finally{c(!1)}})()},[v]);const w=N.useCallback(async()=>{if(!v||!a||!t)return console.error("Push notifications not supported or user not logged in"),!1;if(!m)return $t.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{c(!0);const A=await a.pushManager.getSubscription();if(A){try{await A.unsubscribe()}catch(z){console.warn("Failed to unsubscribe existing push subscription:",z)}const{error:F}=await Ce.from("push_subscriptions").delete().eq("user_id",t.id);F&&console.warn("Failed to cleanup push_subscriptions rows:",F)}if(Notification.permission!=="granted"){const F=await Notification.requestPermission();if(r(F),F!=="granted")return F==="denied"?$t.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):$t.error("Notification permission was dismissed. Please try again."),!1}const C=get(m);let I;try{I=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:C})}catch(F){console.error("PushManager.subscribe() failed:",F);const z=(F==null?void 0:F.message)||String(F);return z.includes("permission")?$t.error("Push permission denied. Check your browser notification settings."):z.includes("key")||z.includes("VAPID")?$t.error("Push configuration error. Please contact support."):z.includes("AbortError")?$t.error("Push subscription was cancelled. Please try again."):$t.error(`Failed to subscribe: ${z}`),!1}const M=I.toJSON(),{error:D}=await Ce.from("push_subscriptions").upsert({user_id:t.id,endpoint:M.endpoint,p256dh_key:M.keys.p256dh,auth_key:M.keys.auth},{onConflict:"user_id,endpoint"});if(D)throw console.error("Error saving subscription:",D),$t.error("Failed to save notification preferences. Please try again."),D;return i(!0),$t.success("Push notifications enabled!"),!0}catch(A){if(console.error("Error subscribing to push notifications:",A),!(A instanceof Error&&A.message.includes("toast"))){const C=A instanceof Error?A.message:"Unknown error";$t.error("Failed to enable push notifications: "+C)}return!1}finally{c(!1)}},[v,a,t,m]),j=N.useCallback(async()=>{if(!a||!t)return!1;try{c(!0);const A=await a.pushManager.getSubscription();return A&&await A.unsubscribe(),await Ce.from("push_subscriptions").delete().eq("user_id",t.id),i(!1),$t.success("Push notifications disabled"),!0}catch(A){console.error("Error unsubscribing:",A);const C=A instanceof Error?A.message:"Unknown error";return $t.error("Failed to disable push notifications: "+C),!1}finally{c(!1)}},[a,t]);return{isSupported:v,permission:e,isSubscribed:n,isLoading:o,vapidPublicKey:m,subscribe:w,unsubscribe:j}}const P6="push_notification_prompt_dismissed",xet=["/dashboard","/admin","/listings"],vet=()=>{const{user:t}=Zn(),{isSupported:e,isSubscribed:r,isLoading:n,subscribe:i}=yet(),o=xs(),[c,a]=N.useState(!1),[f,m]=N.useState(!1),y=xet.some(j=>o.pathname===j||o.pathname.startsWith(`${j}/`));N.useEffect(()=>{if(y){a(!1);return}if(!t||!e||r||n||localStorage.getItem(`${P6}_${t.id}`))return;const A=setTimeout(()=>{a(!0)},2e3);return()=>clearTimeout(A)},[t,e,r,n,y]);const v=async()=>{m(!0);const j=await i();m(!1),j&&(t&&localStorage.setItem(`${P6}_${t.id}`,"true"),a(!1))},w=()=>{t&&localStorage.setItem(`${P6}_${t.id}`,"true"),a(!1)};return!e||r||y?null:s.jsx(Wa,{open:c,onOpenChange:j=>!j&&w(),children:s.jsxs(La,{className:"sm:max-w-md",children:[s.jsxs(Ko,{children:[s.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:s.jsx(kC,{className:"h-6 w-6 text-primary"})}),s.jsx(Po,{className:"text-center",children:"Stay in the Loop!"}),s.jsx(sd,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),s.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Lt,{onClick:v,disabled:f,className:"w-full",children:f?"Enabling...":"Enable Notifications"}),s.jsx(Lt,{variant:"ghost",onClick:w,className:"w-full",children:"Not Now"})]}),s.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},_ie=t=>{let e;const r=new Set,n=(m,y)=>{const v=typeof m=="function"?m(e):m;if(!Object.is(v,e)){const w=e;e=y??(typeof v!="object"||v===null)?v:Object.assign({},e,v),r.forEach(j=>j(e,w))}},i=()=>e,a={setState:n,getState:i,getInitialState:()=>f,subscribe:m=>(r.add(m),()=>r.delete(m))},f=e=t(n,i,a);return a},_et=t=>t?_ie(t):_ie,bet=t=>t;function wet(t,e=bet){const r=Qe.useSyncExternalStore(t.subscribe,Qe.useCallback(()=>e(t.getState()),[t,e]),Qe.useCallback(()=>e(t.getInitialState()),[t,e]));return Qe.useDebugValue(r),r}const bie=t=>{const e=_et(t),r=n=>wet(e,n);return Object.assign(r,e),r},Tet=t=>t?bie(t):bie;function jet(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),a=(o=r.getItem(i))!=null?o:null;return a instanceof Promise?a.then(c):c(a)},setItem:(i,o)=>r.setItem(i,JSON.stringify(o,void 0)),removeItem:i=>r.removeItem(i)}}const Vq=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return Vq(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return Vq(n)(r)}}}},Eet=(t,e)=>(r,n,i)=>{let o={storage:jet(()=>window.localStorage),partialize:I=>I,version:0,merge:(I,M)=>({...M,...I}),...e},c=!1,a=0;const f=new Set,m=new Set;let y=o.storage;if(!y)return t((...I)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...I)},n,i);const v=()=>{const I=o.partialize({...n()});return y.setItem(o.name,{state:I,version:o.version})},w=i.setState;i.setState=(I,M)=>(w(I,M),v());const j=t((...I)=>(r(...I),v()),n,i);i.getInitialState=()=>j;let A;const C=()=>{var I,M;if(!y)return;const D=++a;c=!1,f.forEach(z=>{var q;return z((q=n())!=null?q:j)});const F=((M=o.onRehydrateStorage)==null?void 0:M.call(o,(I=n())!=null?I:j))||void 0;return Vq(y.getItem.bind(y))(o.name).then(z=>{if(z)if(typeof z.version=="number"&&z.version!==o.version){if(o.migrate){const q=o.migrate(z.state,z.version);return q instanceof Promise?q.then(H=>[!0,H]):[!0,q]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,z.state];return[!1,void 0]}).then(z=>{var q;if(D!==a)return;const[H,K]=z;if(A=o.merge(K,(q=n())!=null?q:j),r(A,!0),H)return v()}).then(()=>{D===a&&(F==null||F(n(),void 0),A=n(),c=!0,m.forEach(z=>z(A)))}).catch(z=>{D===a&&(F==null||F(void 0,z))})};return i.persist={setOptions:I=>{o={...o,...I},I.storage&&(y=I.storage)},clearStorage:()=>{y==null||y.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>C(),hasHydrated:()=>c,onHydrate:I=>(f.add(I),()=>{f.delete(I)}),onFinishHydration:I=>(m.add(I),()=>{m.delete(I)})},o.skipHydration||C(),A||j},ket=Eet,w1e=Tet()(ket((t,e)=>({cartItems:[],addToCart:(r,n,i=1,o)=>{t(c=>{const a=c.cartItems.findIndex(f=>{var m;return f.product.id===r.id&&((m=f.variant)==null?void 0:m.id)===(n==null?void 0:n.id)});if(a>=0){const f=[...c.cartItems];return f[a].quantity+=i,o&&(f[a].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 a;return c.product.id===r&&((a=c.variant)==null?void 0:a.id)===n?{...c,quantity:Math.max(1,i)}:c})}))},updateArtwork:(r,n,i)=>{t(o=>({cartItems:o.cartItems.map(c=>{var a;return c.product.id===r&&((a=c.variant)==null?void 0:a.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})})),Aet="/admin/beta/boost",Net=N.lazy(()=>Oe(()=>import("./BoostCompanion-YI4EjfiH.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])));function Cet(){const{user:t,isAdmin:e}=Zn(),{isFeatureEnabled:r}=J3(),{pathname:n}=xs(),i=n==="/main-stage"||n.startsWith("/main-stage/");return!(!!t&&(e||r("boost_mascot"))&&n!==Aet&&!i)||!t?null:s.jsx(N.Suspense,{fallback:null,children:s.jsx(Net,{userId:t.id})})}async function Iet(t){const{data:e,error:r}=await Ce.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 Uer(t){const{data:e,error:r}=await Ce.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 S1e="America/New_York",Ver=t=>new Intl.DateTimeFormat("en-US",{timeZone:S1e,weekday:"short",month:"short",day:"numeric"}).format(new Date(t)),qer=t=>new Intl.DateTimeFormat("en-US",{timeZone:S1e,hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(new Date(t)),Ger=t=>t.trim().toUpperCase().replace(/\s+/g,"");function Her(t,e="https://dashboard.relevelup.com"){const r=a=>a.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 Wer(t,e="https://dashboard.relevelup.com"){const r=a=>a.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 Ker=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 T1e(){const{data:t}=mr({queryKey:["main-stage-live-nav"],queryFn:async()=>(await Iet()).some(e=>e.status==="live"),refetchInterval:6e4,staleTime:3e4});return!!t}function Pet({activeCategory:t,currentCategory:e,onSelect:r,onHover:n,badgeCounts:i,categories:o=mF}){const c=T1e();return s.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:o.map(a=>{const f=a.icon,m=t===a.id,y=e===a.id,v=(i==null?void 0:i[a.id])??0,w=`hsl(var(--${a.accent}))`,j=m||y;return s.jsxs("button",{type:"button",onClick:()=>r(a.id),onMouseEnter:()=>n==null?void 0:n(a.id),"aria-expanded":a.route?void 0:m,"aria-controls":a.route?void 0:"primary-nav-flyout","aria-current":y?"page":void 0,style:{color:j?w:void 0,backgroundColor:j?`hsl(var(--${a.accent}) / 0.12)`:void 0},className:Xt("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&&s.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:w}}),s.jsxs("span",{className:"relative",children:[s.jsx(f,{className:"h-5 w-5 transition-colors",style:{color:w}}),a.id==="mainstage"&&c&&s.jsxs("span",{className:"absolute -right-1 -top-1 flex h-3 w-3",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-destructive opacity-75"}),s.jsx("span",{className:"relative inline-flex h-3 w-3 rounded-full bg-destructive"})]}),v>0&&s.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold text-primary-foreground",style:{backgroundColor:w},children:v>9?"9+":v})]}),a.id==="mainstage"&&c?s.jsx("span",{className:"rounded bg-destructive px-1 text-[9px] font-bold uppercase tracking-wider leading-tight text-destructive-foreground",children:"Live"}):s.jsx("span",{className:"leading-tight",children:a.label})]},a.id)})})}function Ret({category:t,top:e,left:r,onClose:n,onNavigate:i,isFavorite:o,favorites:c,onToggleFavorite:a,isCurrent:f,badgeCounts:m}){const y=N.useRef(null);N.useEffect(()=>{const w=A=>{A.key==="Escape"&&n()},j=A=>{var I;if(!y.current)return;const C=A.target;!y.current.contains(C)&&!((I=C==null?void 0:C.closest)!=null&&I.call(C,"[data-nav-rail]"))&&n()};return document.addEventListener("keydown",w),document.addEventListener("mousedown",j),()=>{document.removeEventListener("keydown",w),document.removeEventListener("mousedown",j)}},[n]);const v=w=>{const j=w.icon,A=w.badgeKey?(m==null?void 0:m[w.badgeKey])??0:0;return s.jsxs("div",{className:Xt("group flex items-start gap-3 rounded-lg border border-transparent p-2 transition-colors hover:bg-muted/60",f(w)&&"border-primary/30 bg-primary/5"),children:[s.jsxs("button",{type:"button",onClick:()=>i(w),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[s.jsx("span",{className:Xt("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",w.iconTone==="red"?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:s.jsx(j,{className:Xt("h-4 w-4",w.iconTone==="red"&&"fill-destructive/20")})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-sm font-medium text-foreground",children:w.label}),w.badge==="new"&&s.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),w.badge==="beta"&&s.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),w.locked&&s.jsx(Wx,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),A>0&&s.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:A>9?"9+":A})]}),w.description&&s.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:w.description})]})]}),s.jsx("button",{type:"button","aria-label":o(w)?`Remove ${w.label} from favorites`:`Add ${w.label} to favorites`,onClick:C=>{C.stopPropagation(),a(w)},className:Xt("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(w)&&"opacity-100 text-primary",!o(w)&&"text-muted-foreground/60 hover:text-primary"),children:s.jsx(qD,{className:Xt("h-4 w-4",o(w)&&"fill-current")})})]},w.id)};return s.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:[s.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:s.jsx("h2",{className:"text-sm font-semibold text-foreground",children:t.label})}),s.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[c.length>0&&s.jsxs("section",{className:"mb-4",children:[s.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[s.jsx(qD,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),s.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:c.map(v)})]}),t.sections.map(w=>s.jsxs("section",{className:"mb-4 last:mb-0",children:[s.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:w.title}),s.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:w.items.map(v)})]},w.title)),t.sections.length===0&&s.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function Let({categories:t,railCategories:e=mF,currentCategory:r,onNavigate:n,onNavigateRoute:i,isCurrent:o,badgeCounts:c,isFavorite:a,onToggleFavorite:f}){const[m,y]=N.useState(r),v=T1e();return s.jsx("nav",{"aria-label":"Primary",className:"p-2",children:e.map(w=>{const j=w.icon;if(w.route)return s.jsxs("button",{type:"button",onClick:()=>i(w.route),className:Xt("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===w.id&&"bg-sidebar-accent"),children:[s.jsx(j,{className:"h-4 w-4",style:{color:`hsl(var(--${w.accent}))`}}),w.label,w.id==="mainstage"&&v&&s.jsxs("span",{className:"ml-auto flex items-center gap-1 rounded-full bg-destructive px-2 py-0.5 text-[10px] font-bold uppercase text-destructive-foreground",children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-destructive-foreground"}),"Live"]})]},w.id);const A=t.find(I=>I.id===w.id),C=m===w.id;return s.jsxs("div",{children:[s.jsxs("button",{type:"button","aria-expanded":C,onClick:()=>y(C?null:w.id),className:Xt("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===w.id&&"text-primary"),children:[s.jsx(j,{className:"h-4 w-4",style:{color:`hsl(var(--${w.accent}))`}}),w.label,s.jsx(Wo,{className:Xt("ml-auto h-4 w-4 transition-transform",C&&"rotate-180")})]}),C&&A&&s.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:A.sections.map(I=>s.jsxs("div",{children:[s.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:I.title}),I.items.map(M=>{const D=M.icon,F=M.badgeKey?(c==null?void 0:c[M.badgeKey])??0:0,z=(a==null?void 0:a(M))??!1;return s.jsxs("div",{className:Xt("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",o(M)&&"bg-sidebar-accent"),children:[s.jsxs("button",{type:"button",onClick:()=>n(M),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[s.jsx(D,{className:Xt("h-4 w-4 shrink-0",M.iconTone==="red"&&"text-destructive")}),s.jsx("span",{className:"truncate",children:M.label}),F>0&&s.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:F>9?"9+":F})]}),f&&s.jsx("button",{type:"button","aria-label":z?`Remove ${M.label} from favorites`:`Add ${M.label} to favorites`,onClick:()=>f(M),className:Xt("rounded p-2",z?"text-primary":"text-muted-foreground/60"),children:s.jsx(qD,{className:Xt("h-4 w-4",z&&"fill-current")})})]},M.id)})]},I.title))})]},w.id)})})}function j1e(){const t=Bi(),e=xs(),r=qwe(),n=N.useCallback(a=>Uwe(a,r.ctx),[r.ctx]),i=N.useMemo(()=>{if(e.pathname.startsWith("/apps"))return"apps";if(e.pathname==="/dashboard")return"home";let a=null;for(const f of r.destinations){if(f.external)continue;const m=n(f);m!=="/"&&e.pathname.startsWith(m)&&(!a||m.length>a.len)&&(a={id:f.primaryCategory,len:m.length})}return(a==null?void 0:a.id)??null},[e.pathname,r.destinations,n]),o=N.useCallback(a=>!a.external&&e.pathname===n(a),[e.pathname,n]),c=N.useCallback(a=>{const f=n(a);if(a.external||a.openInNewTab){window.open(f,"_blank","noopener,noreferrer");return}t(f)},[t,n]);return{nav:r,navigate:t,currentCategory:i,isCurrent:o,go:c}}function Met({communityUnreadCount:t=0,wishlistOpenCount:e=0,flyoutTop:r=64,flyoutLeft:n=80}){const{nav:i,navigate:o,currentCategory:c,isCurrent:a,go:f}=j1e(),[m,y]=N.useState(null),v=N.useRef(null),w=C=>{const I=mF.find(M=>M.id===C);if(I!=null&&I.route){y(null),o(I.route);return}y(M=>M===C?null:C)},j=m?i.categoryMap.get(m):void 0,A={more:t+e};return s.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{v.current&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>y(null),250)},onMouseEnter:()=>{v.current&&window.clearTimeout(v.current)},children:[s.jsx(Pet,{activeCategory:m,currentCategory:c,onSelect:w,categories:i.railCategories,badgeCounts:A}),j&&s.jsx(Ret,{category:j,top:r,left:n,onClose:()=>y(null),onNavigate:C=>{y(null),f(C)},isFavorite:i.isFavorite,favorites:i.favoritesFor(j.id),onToggleFavorite:C=>i.toggleFavorite(i.favoriteKey(C)),isCurrent:a,badgeCounts:{community:t,wishlist:e}})]})}function Det({communityUnreadCount:t=0,wishlistOpenCount:e=0,onNavigated:r}){const{nav:n,navigate:i,currentCategory:o,isCurrent:c,go:a}=j1e();return s.jsx(Let,{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=>{a(f),r==null||r()},onNavigateRoute:f=>{i(f),r==null||r()}})}const Oet=({bannerHeight:t,communityUnreadCount:e,wishlistOpenCount:r,isTrial:n,isExpired:i})=>{const o=Bi();return s.jsxs("div",{className:"flex h-full flex-col",children:[s.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:s.jsx("button",{type:"button",onClick:()=>o("/dashboard"),"aria-label":"LevelUp home",children:s.jsx("img",{src:jGe,alt:"LevelUp",className:"h-8 w-auto"})})}),s.jsxs(hp,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[s.jsx(Met,{communityUnreadCount:e,wishlistOpenCount:r,flyoutTop:t+64,flyoutLeft:80}),n&&!i&&s.jsx("div",{className:"p-2",children:s.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:[s.jsx(ki,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},Fet=({isTrial:t,isExpired:e,expiresAt:r,communityUnreadCount:n,wishlistOpenCount:i,pathname:o,onSignOut:c,onNavigated:a})=>{const f=Bi();return s.jsxs("div",{className:"flex h-full flex-col",children:[s.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:s.jsx("img",{src:TGe,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsxs(hp,{className:"flex-1",children:[t&&!e&&s.jsx("div",{className:"p-2",children:s.jsx("button",{type:"button",onClick:()=>{f("/subscription"),a==null||a()},className:Xt("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:s.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[s.jsx(ki,{className:"h-4 w-4 text-amber-500"}),s.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),r&&s.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(r)-Date.now())/864e5)),"d left"]})]})})}),s.jsx(Det,{communityUnreadCount:n,wishlistOpenCount:i,onNavigated:a})]}),s.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[s.jsxs(Lt,{variant:"ghost",size:"sm",className:Xt("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"),a==null||a()},children:[s.jsx(Wl,{className:"h-4 w-4"}),"Profile"]}),s.jsxs(Lt,{variant:"ghost",size:"sm",className:Xt("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"),a==null||a()},children:[s.jsx(j3,{className:"h-4 w-4"}),"Credits & Wallet"]}),s.jsxs(Lt,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:c,children:[s.jsx(b3,{className:"h-4 w-4"}),"Sign Out"]})]})]})},hT=({children:t,title:e})=>{var lt;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:o,isCoach:c,brokerageId:a}=Zn(),{isAssistant:f,actingAsAgent:m,hasPermission:y}=Z3();PW();const{isImpersonating:v}=gve(),j=(f&&!!m?40:0)+(v?40:0),{avatarUrl:A}=rGe(r==null?void 0:r.id),{isTrial:C,isExpired:I,expiresAt:M}=nGe(r==null?void 0:r.id),{isInnerCircleEnabled:D,isMarketplaceEnabled:F}=J3(),{currentBrief:z,shouldShowPopup:q,hasUnseenBrief:H,openBrief:K,closeBrief:J,dismissBrief:Q}=uet(),{unreadCount:ee}=sGe(),{openCount:oe}=iGe();dj();const ye=w1e(wt=>wt.cartItems).reduce((wt,yt)=>wt+yt.quantity,0),{leadSite:we,hasLeadSite:Le,siteUrl:Se}=mK();zwe(!Le);const ve=Bi(),me=xs(),[ke,Pe]=N.useState(null);N.useEffect(()=>{r!=null&&r.id&&Ce.from("profiles").select("name").eq("id",r.id).single().then(({data:wt})=>{wt!=null&&wt.name&&Pe(wt.name)})},[r==null?void 0:r.id]);const Ee=ke||((lt=r==null?void 0:r.user_metadata)==null?void 0:lt.name)||(r==null?void 0:r.email)||"User",[xe,Ue]=N.useState(!1),Ze=wt=>wt.split(" ").map(yt=>yt[0]).join("").toUpperCase().slice(0,2);return s.jsx(u0e,{children:s.jsxs("div",{className:"min-h-screen bg-background flex",children:[C&&I&&me.pathname!=="/subscription"&&s.jsx(HJe,{}),typeof document<"u"&&op.createPortal(s.jsx("aside",{className:"hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto w-20",style:{top:`${j}px`,height:`calc(100vh - ${j}px)`},children:s.jsx(Oet,{bannerHeight:j,communityUnreadCount:ee,wishlistOpenCount:oe,isTrial:C,isExpired:I})}),document.body),s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${j}px)`,marginTop:`${j}px`},children:[s.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:s.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[s.jsxs(R_e,{open:xe,onOpenChange:Ue,children:[s.jsx(oGe,{asChild:!0,children:s.jsx(Lt,{variant:"ghost",size:"icon",className:"md:hidden",children:s.jsx(p0,{className:"h-5 w-5"})})}),s.jsx(RW,{side:"left",className:"w-72 p-0 bg-card",children:s.jsx(Fet,{isTrial:C,isExpired:I,expiresAt:M,communityUnreadCount:ee,wishlistOpenCount:oe,pathname:me.pathname,onSignOut:n,onNavigated:()=>Ue(!1)})})]}),s.jsx("div",{className:"flex-1 md:hidden",children:s.jsx("img",{src:EGe,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsx("div",{className:"hidden md:flex flex-1 justify-center px-4 min-w-0",children:s.jsx(vie,{})}),s.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[C&&!I&&M&&s.jsx(GJe,{expiresAt:M,className:"hidden lg:flex"}),s.jsx("div",{className:"md:hidden",children:s.jsx(vie,{hotkey:!1})}),z&&s.jsx(WJe,{hasUnseenBrief:H,onClick:K}),F&&s.jsxs(Lt,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ve("/marketplace/cart"),children:[s.jsx(Nye,{className:"h-5 w-5"}),ye>0&&s.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:ye>99?"99+":ye})]}),s.jsx(Lt,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>ve("/mission-control/calendar"),children:s.jsx(Hm,{className:"h-5 w-5"})}),s.jsx(JQe,{}),s.jsx(QQe,{}),s.jsx(GQe,{}),s.jsx(gZe,{}),s.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",Ee.split(" ")[0],"!"]}),s.jsxs(cj,{children:[s.jsx(uj,{asChild:!0,children:s.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:s.jsxs($d,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[s.jsx(zd,{src:A||void 0}),s.jsx(Ud,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Ze(Ee)})]})})}),s.jsxs(xb,{align:"end",className:"w-48",children:[s.jsxs(yu,{onClick:()=>ve("/profile"),className:"cursor-pointer",children:[s.jsx(Wl,{className:"h-4 w-4 mr-2"}),"Profile"]}),s.jsxs(yu,{onClick:()=>ve("/credits"),className:"cursor-pointer",children:[s.jsx(j3,{className:"h-4 w-4 mr-2"}),"Credits & Wallet"]}),s.jsxs(yu,{onClick:()=>ve("/mission-control/integrations"),className:"cursor-pointer",children:[s.jsx(HD,{className:"h-4 w-4 mr-2"}),"Integrations"]}),s.jsxs(yu,{onClick:()=>ve("/mission-control/browser-extension"),className:"cursor-pointer",children:[s.jsx(HD,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),s.jsx(iT,{}),s.jsxs(yu,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[s.jsx(b3,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),s.jsx(het,{children:s.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),z&&s.jsx(cet,{brief:z,open:q,onClose:J,onDismiss:Q}),s.jsx(det,{}),s.jsx(pet,{}),s.jsx(vet,{}),s.jsx(Cet,{})]})]})})},ct=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,rolesLoading:o,isAdmin:c,isBrokerageManager:a}=Zn(),f=xs(),m=N_e();if(i||(e||r)&&o)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const y=f.pathname+f.search+f.hash;return y&&y!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",y),s.jsx(ls,{to:"/auth",replace:!0})}if(e&&!c)return s.jsx(ls,{to:"/dashboard",replace:!0});if(r&&!a&&!c)return s.jsx(ls,{to:"/dashboard",replace:!0});if(m.isRestricted&&!m.isLoading){const y=Q9e(f.pathname);if(y&&!m.hasFeature(y))return s.jsx(hT,{title:"Upgrade required",children:s.jsx(tGe,{featureKey:y})})}return s.jsx(s.Fragment,{children:t})};function R6({children:t}){const{isAdmin:e,loading:r,rolesLoading:n}=Zn(),{isFeatureEnabled:i,isLoading:o}=J3();return r||n||o?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!e&&!i("staging_studio_enabled")?s.jsx(ls,{to:"/apps",replace:!0}):s.jsx(hT,{title:"Staging Studio",children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:t})})}var vK={};(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",a=function(){if(!e.OffscreenCanvas)return!1;try{var Pe=new OffscreenCanvas(1,1),Ee=Pe.getContext("2d");Ee.fillRect(0,0,1,1);var xe=Pe.transferToImageBitmap();Ee.createPattern(xe,"no-repeat")}catch{return!1}return!0}();function f(){}function m(Pe){var Ee=r.exports.Promise,xe=Ee!==void 0?Ee:e.Promise;return typeof xe=="function"?new xe(Pe):(Pe(f,f),null)}var y=function(Pe,Ee){return{transform:function(xe){if(Pe)return xe;if(Ee.has(xe))return Ee.get(xe);var Ue=new OffscreenCanvas(xe.width,xe.height),Ze=Ue.getContext("2d");return Ze.drawImage(xe,0,0),Ee.set(xe,Ue),Ue},clear:function(){Ee.clear()}}}(a,new Map),v=function(){var Pe=Math.floor(16.666666666666668),Ee,xe,Ue={},Ze=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(Ee=function(lt){var wt=Math.random();return Ue[wt]=requestAnimationFrame(function yt(gt){Ze===gt||Ze+Pe-1{const{data:e,error:r}=await Ce.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 $et(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await Ce.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}function Yer(){const t=kr(),{user:e}=Zn();return Ar({mutationFn:async r=>{const{error:n}=await Ce.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 zet={points_earned:YD,listing_created:ta,deal_closed:_g,custom:vc},Sie={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"},Tie=()=>{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 Uet(){const{user:t}=Zn(),e=kr(),{data:r}=Bet(),n=$et(),[i,o]=N.useState(null),[c,a]=N.useState(!1),f=N.useCallback(()=>{const j=Date.now()+3e3,A={startVelocity:30,spread:360,ticks:60,zIndex:9999},C=(M,D)=>Math.random()*(D-M)+M,I=setInterval(()=>{const M=j-Date.now();if(M<=0){clearInterval(I);return}const D=50*(M/3e3);wie({...A,particleCount:D,origin:{x:C(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),wie({...A,particleCount:D,origin:{x:C(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{Tie()||r&&r.length>0&&!i&&(o(r[0]),a(!0),setTimeout(f,100))},[r,i,f]);const m=async()=>{if(i){const w=i.id;a(!1),o(null),e.setQueryData(["celebrations","pending",t==null?void 0:t.id],j=>(j==null?void 0:j.filter(A=>A.id!==w))??[]),await n.mutateAsync(w)}};if(Tie()||!i)return null;const y=zet[i.celebration_type]||vc,v=Sie[i.celebration_type]||Sie.custom;return s.jsx(Wa,{open:c,onOpenChange:w=>!w&&m(),children:s.jsxs(La,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[s.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${v} opacity-10`}),s.jsxs("div",{className:"relative z-10 py-6",children:[s.jsx("div",{className:"flex justify-center mb-4",children:s.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${v} flex items-center justify-center animate-bounce`,children:s.jsx(y,{className:"w-10 h-10 text-white"})})}),s.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[s.jsx(ki,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),s.jsx(ki,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),s.jsx(ki,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),s.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",i.title]}),i.points_amount&&i.points_amount>0&&s.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",i.points_amount," points!"]}),i.message&&s.jsx("p",{className:"text-muted-foreground mb-6",children:i.message}),s.jsx(Lt,{onClick:m,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&s.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}function Al({className:t,...e}){return s.jsx("div",{className:Xt("animate-pulse rounded-md bg-muted",t),...e})}var xF="Tabs",[Vet,Zer]=dl(xF,[lj]),E1e=lj(),[qet,_K]=Vet(xF),k1e=N.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,onValueChange:i,defaultValue:o,orientation:c="horizontal",dir:a,activationMode:f="automatic",...m}=t,y=gb(a),[v,w]=rd({prop:n,onChange:i,defaultProp:o??"",caller:xF});return s.jsx(qet,{scope:r,baseId:ol(),value:v,onValueChange:w,orientation:c,dir:y,activationMode:f,children:s.jsx(cn.div,{dir:y,"data-orientation":c,...m,ref:e})})});k1e.displayName=xF;var A1e="TabsList",N1e=N.forwardRef((t,e)=>{const{__scopeTabs:r,loop:n=!0,...i}=t,o=_K(A1e,r),c=E1e(r);return s.jsx(_W,{asChild:!0,...c,orientation:o.orientation,dir:o.dir,loop:n,children:s.jsx(cn.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:e})})});N1e.displayName=A1e;var C1e="TabsTrigger",I1e=N.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,disabled:i=!1,...o}=t,c=_K(C1e,r),a=E1e(r),f=L1e(c.baseId,n),m=M1e(c.baseId,n),y=n===c.value;return s.jsx(bW,{asChild:!0,...a,focusable:!i,active:y,children:s.jsx(cn.button,{type:"button",role:"tab","aria-selected":y,"aria-controls":m,"data-state":y?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:f,...o,ref:e,onMouseDown:Gr(t.onMouseDown,v=>{!i&&v.button===0&&v.ctrlKey===!1?c.onValueChange(n):v.preventDefault()}),onKeyDown:Gr(t.onKeyDown,v=>{[" ","Enter"].includes(v.key)&&c.onValueChange(n)}),onFocus:Gr(t.onFocus,()=>{const v=c.activationMode!=="manual";!y&&!i&&v&&c.onValueChange(n)})})})});I1e.displayName=C1e;var P1e="TabsContent",R1e=N.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,forceMount:i,children:o,...c}=t,a=_K(P1e,r),f=L1e(a.baseId,n),m=M1e(a.baseId,n),y=n===a.value,v=N.useRef(y);return N.useEffect(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),s.jsx(Pl,{present:i||y,children:({present:w})=>s.jsx(cn.div,{"data-state":y?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":f,hidden:!w,id:m,tabIndex:0,...c,ref:e,style:{...t.style,animationDuration:v.current?"0s":void 0},children:w&&o})})});R1e.displayName=P1e;function L1e(t,e){return`${t}-trigger-${e}`}function M1e(t,e){return`${t}-content-${e}`}var Get=k1e,D1e=N1e,O1e=I1e,F1e=R1e;const vF=Get,JC=N.forwardRef(({className:t,...e},r)=>s.jsx(D1e,{ref:r,className:Xt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));JC.displayName=D1e.displayName;const Of=N.forwardRef(({className:t,...e},r)=>s.jsx(O1e,{ref:r,className:Xt("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}));Of.displayName=O1e.displayName;const Bx=N.forwardRef(({className:t,...e},r)=>s.jsx(F1e,{ref:r,className:Xt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));Bx.displayName=F1e.displayName;const vN="#0d0d0d",TO="#1a1a1a",dc="#c9a84c",eI="#f0d78c",tp={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function _F(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 Ce.functions.invoke("public-site-lead",{body:e});if(n)throw n;try{localStorage.setItem(tp.captured,JSON.stringify({email:t.email,ts:Date.now()}))}catch{}return r}function bK(){try{return!!localStorage.getItem(tp.captured)}catch{return!1}}function Het(){try{const t=localStorage.getItem(tp.captured);return t?JSON.parse(t).email??null:null}catch{return null}}function wK({open:t,onClose:e,children:r}){return N.useEffect(()=>{if(!t)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[t]),t?op.createPortal(s.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in",style:{background:"rgba(0,0,0,0.82)",backdropFilter:"blur(6px)"},onClick:e,children:s.jsxs("div",{onClick:n=>n.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${TO} 0%, ${vN} 100%)`,border:`1px solid ${dc}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${dc}22 inset`},children:[s.jsx("button",{onClick:e,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:s.jsx(Ci,{className:"h-4 w-4"})}),r]})}),document.body):null}function SK(){const[t,e]=N.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=N.useState(!1),[i,o]=N.useState("");return{values:t,setValues:e,loading:r,setLoading:n,honeypot:i,setHoneypot:o}}function TK({values:t,setValues:e,honeypot:r,setHoneypot:n,showPhone:i=!0,showArea:o=!0,areaPlaceholder:c="City, ZIP, or neighborhood"}){const a="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 s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"relative",children:[s.jsx(Wl,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"text",placeholder:"First name",value:t.first_name,onChange:m=>e({...t,first_name:m.target.value}),className:a,style:f})]}),s.jsxs("div",{className:"relative",children:[s.jsx(rs,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:t.email,onChange:m=>e({...t,email:m.target.value}),className:a,style:f})]}),i&&s.jsxs("div",{className:"relative",children:[s.jsx(Fn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:t.phone,onChange:m=>e({...t,phone:m.target.value}),className:a,style:f})]}),o&&s.jsxs("div",{className:"relative",children:[s.jsx(ii,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"text",placeholder:c,value:t.area,onChange:m=>e({...t,area:m.target.value}),className:a,style:f})]}),s.jsx("input",{type:"text",value:r,onChange:m=>n(m.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function jK({children:t,disabled:e,onClick:r,type:n="button"}){return s.jsx("button",{type:n,disabled:e,onClick:r,className:"w-full rounded-lg py-3 text-sm font-semibold uppercase tracking-widest transition disabled:opacity-60 disabled:cursor-not-allowed",style:{background:`linear-gradient(180deg, ${eI} 0%, ${dc} 100%)`,color:vN,boxShadow:`0 8px 24px ${dc}55`},children:t})}function jie({open:t,onClose:e,initialCriteria:r}){const{values:n,setValues:i,loading:o,setLoading:c,honeypot:a,setHoneypot:f}=SK(),[m,y]=N.useState(!1),v=async w=>{if(w.preventDefault(),!!n.email){c(!0);try{await _F({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(tp.stickyDismissed,"1")}catch{}setTimeout(e,2200)}catch{$t.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(wK,{open:t,onClose:e,children:s.jsxs("div",{className:"p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(kC,{className:"h-4 w-4",style:{color:dc}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:eI},children:"New Listing Alerts"})]}),s.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),s.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"The best homes go before they hit the market. Get instant alerts the moment new listings match your search."}),m?s.jsxs("div",{className:"py-6 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${dc}22`,border:`1px solid ${dc}55`},children:s.jsx(ki,{className:"h-5 w-5",style:{color:dc}})}),s.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),s.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(TK,{values:n,setValues:i,honeypot:a,setHoneypot:f}),s.jsx(jK,{type:"submit",disabled:o||!n.email,children:o?"Activating…":"Activate Alerts"}),s.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function Wet(){const[t,e]=N.useState(!0),[r,n]=N.useState(!1);N.useEffect(()=>{try{const o=!!localStorage.getItem(tp.stickyDismissed)||bK();e(o)}catch{e(!1)}},[]);const i=()=>{e(!0);try{localStorage.setItem(tp.stickyDismissed,"1")}catch{}};return t?s.jsx(jie,{open:r,onClose:()=>n(!1)}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${TO} 0%, ${vN} 100%)`,borderTop:`1px solid ${dc}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:s.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[s.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${dc}22`,border:`1px solid ${dc}55`},children:s.jsx(kC,{className:"h-4 w-4",style:{color:dc}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),s.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),s.jsx("button",{onClick:()=>n(!0),className:"rounded-lg px-4 py-2 text-xs font-semibold uppercase tracking-wider whitespace-nowrap transition hover:brightness-110",style:{background:`linear-gradient(180deg, ${eI} 0%, ${dc} 100%)`,color:vN},children:"Get Alerts"}),s.jsx("button",{onClick:i,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:s.jsx(Ci,{className:"h-4 w-4"})})]})}),s.jsx(jie,{open:r,onClose:()=>n(!1)})]})}function Ket(){const[t,e]=N.useState(!1),r=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(tp.exitShown)||bK())return}catch{}const w=setTimeout(()=>{r.current=!0},8e3),j=A=>{if(r.current&&!(A.clientY>0)){e(!0);try{sessionStorage.setItem(tp.exitShown,"1")}catch{}window.removeEventListener("mouseleave",j),document.removeEventListener("mouseleave",j)}};return document.addEventListener("mouseleave",j),()=>{clearTimeout(w),document.removeEventListener("mouseleave",j)}},[]);const{values:n,setValues:i,loading:o,setLoading:c,honeypot:a,setHoneypot:f}=SK(),[m,y]=N.useState(!1),v=async w=>{if(w.preventDefault(),!!n.email){c(!0);try{await _F({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{$t.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(wK,{open:t,onClose:()=>e(!1),children:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${vN} 0%, ${TO} 60%, ${dc} 130%)`},children:s.jsx("div",{className:"absolute top-4 left-6",children:s.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:eI},children:"Before You Go"})})}),s.jsxs("div",{className:"p-8 -mt-10",children:[s.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:TO,border:`1px solid ${dc}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:s.jsx(ki,{className:"h-6 w-6",style:{color:dc}})}),s.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),s.jsx("p",{className:"text-sm text-white/60 text-center mb-6 leading-relaxed",children:"Drop your email and we'll send you a curated list of homes matching your area, updated weekly."}),m?s.jsxs("div",{className:"py-4 text-center",children:[s.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),s.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(TK,{values:n,setValues:i,honeypot:a,setHoneypot:f,showPhone:!1}),s.jsx(jK,{type:"submit",disabled:o||!n.email,children:o?"Sending…":"Send My List"})]})]})]})})}function Yet(){const[t,e]=N.useState([]);N.useEffect(()=>{try{const a=localStorage.getItem(tp.savedListings);a&&e(JSON.parse(a))}catch{}},[]);const r=a=>{e(a);try{localStorage.setItem(tp.savedListings,JSON.stringify(a))}catch{}},n=N.useCallback(a=>t.includes(a),[t]),i=a=>{t.includes(a)||r([...t,a])},o=a=>r(t.filter(f=>f!==a));return{ids:t,has:n,add:i,remove:o,toggle:a=>t.includes(a)?o(a):i(a)}}function Zet({listingId:t,listingAddress:e,className:r}){const{has:n,add:i,remove:o}=Yet(),c=n(t),[a,f]=N.useState(!1),m=()=>{if(c){o(t);return}if(bK()){i(t),$t.success("Saved to your favorites"),_F({lead_type:"saved_listing",email:Het()||"unknown@local",listing_id:t,listing_address:e}).catch(()=>{});return}f(!0)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:m,className:r,"aria-label":c?"Remove from favorites":"Save to favorites",children:s.jsx(Jm,{className:`h-5 w-5 ${c?"fill-current":""}`})}),s.jsx(Xet,{open:a,onClose:()=>f(!1),listingId:t,listingAddress:e,onSaved:()=>i(t)})]})}function Xet({open:t,onClose:e,listingId:r,listingAddress:n,onSaved:i}){const{values:o,setValues:c,loading:a,setLoading:f,honeypot:m,setHoneypot:y}=SK(),v=async w=>{if(w.preventDefault(),!!o.email){f(!0);try{await _F({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(),$t.success("Saved to your favorites"),e()}catch{$t.error("Something went wrong. Please try again.")}finally{f(!1)}}};return s.jsx(wK,{open:t,onClose:e,children:s.jsxs("div",{className:"p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(Jm,{className:"h-4 w-4",style:{color:dc}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:eI},children:"Save This Home"})]}),s.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),s.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"Get an alert if the price drops or the status changes. No spam — just the updates that matter."}),s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(TK,{values:o,setValues:c,honeypot:m,setHoneypot:y}),s.jsx(jK,{type:"submit",disabled:a||!o.email,children:a?"Saving…":"Save Home"})]})]})})}var B1e=["PageUp","PageDown"],$1e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],z1e={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},pj="Slider",[qq,Qet,Jet]=jC(pj),[U1e,Xer]=dl(pj,[Jet]),[ett,bF]=U1e(pj),V1e=N.forwardRef((t,e)=>{const{name:r,min:n=0,max:i=100,step:o=1,orientation:c="horizontal",disabled:a=!1,minStepsBetweenThumbs:f=0,defaultValue:m=[n],value:y,onValueChange:v=()=>{},onValueCommit:w=()=>{},inverted:j=!1,form:A,...C}=t,I=N.useRef(new Set),M=N.useRef(0),F=c==="horizontal"?ttt:rtt,[z=[],q]=rd({prop:y,defaultProp:m,onChange:oe=>{var ye;(ye=[...I.current][M.current])==null||ye.focus(),v(oe)}}),H=N.useRef(z);function K(oe){const de=ott(z,oe);ee(oe,de)}function J(oe){ee(oe,M.current)}function Q(){const oe=H.current[M.current];z[M.current]!==oe&&w(z)}function ee(oe,de,{commit:ye}={commit:!1}){const we=dtt(o),Le=htt(Math.round((oe-n)/o)*o+n,we),Se=hN(Le,[n,i]);q((ve=[])=>{const me=itt(ve,Se,de);if(utt(me,f*o)){M.current=me.indexOf(Se);const ke=String(me)!==String(ve);return ke&&ye&&w(me),ke?me:ve}else return ve})}return s.jsx(ett,{scope:t.__scopeSlider,name:r,disabled:a,min:n,max:i,valueIndexToChangeRef:M,thumbs:I.current,values:z,orientation:c,form:A,children:s.jsx(qq.Provider,{scope:t.__scopeSlider,children:s.jsx(qq.Slot,{scope:t.__scopeSlider,children:s.jsx(F,{"aria-disabled":a,"data-disabled":a?"":void 0,...C,ref:e,onPointerDown:Gr(C.onPointerDown,()=>{a||(H.current=z)}),min:n,max:i,inverted:j,onSlideStart:a?void 0:K,onSlideMove:a?void 0:J,onSlideEnd:a?void 0:Q,onHomeKeyDown:()=>!a&&ee(n,0,{commit:!0}),onEndKeyDown:()=>!a&&ee(i,z.length-1,{commit:!0}),onStepKeyDown:({event:oe,direction:de})=>{if(!a){const Le=B1e.includes(oe.key)||oe.shiftKey&&$1e.includes(oe.key)?10:1,Se=M.current,ve=z[Se],me=o*Le*de;ee(ve+me,Se,{commit:!0})}}})})})})});V1e.displayName=pj;var[q1e,G1e]=U1e(pj,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ttt=N.forwardRef((t,e)=>{const{min:r,max:n,dir:i,inverted:o,onSlideStart:c,onSlideMove:a,onSlideEnd:f,onStepKeyDown:m,...y}=t,[v,w]=N.useState(null),j=is(e,F=>w(F)),A=N.useRef(void 0),C=gb(i),I=C==="ltr",M=I&&!o||!I&&o;function D(F){const z=A.current||v.getBoundingClientRect(),q=[0,z.width],K=EK(q,M?[r,n]:[n,r]);return A.current=z,K(F-z.left)}return s.jsx(q1e,{scope:t.__scopeSlider,startEdge:M?"left":"right",endEdge:M?"right":"left",direction:M?1:-1,size:"width",children:s.jsx(H1e,{dir:C,"data-orientation":"horizontal",...y,ref:j,style:{...y.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:F=>{const z=D(F.clientX);c==null||c(z)},onSlideMove:F=>{const z=D(F.clientX);a==null||a(z)},onSlideEnd:()=>{A.current=void 0,f==null||f()},onStepKeyDown:F=>{const q=z1e[M?"from-left":"from-right"].includes(F.key);m==null||m({event:F,direction:q?-1:1})}})})}),rtt=N.forwardRef((t,e)=>{const{min:r,max:n,inverted:i,onSlideStart:o,onSlideMove:c,onSlideEnd:a,onStepKeyDown:f,...m}=t,y=N.useRef(null),v=is(e,y),w=N.useRef(void 0),j=!i;function A(C){const I=w.current||y.current.getBoundingClientRect(),M=[0,I.height],F=EK(M,j?[n,r]:[r,n]);return w.current=I,F(C-I.top)}return s.jsx(q1e,{scope:t.__scopeSlider,startEdge:j?"bottom":"top",endEdge:j?"top":"bottom",size:"height",direction:j?1:-1,children:s.jsx(H1e,{"data-orientation":"vertical",...m,ref:v,style:{...m.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:C=>{const I=A(C.clientY);o==null||o(I)},onSlideMove:C=>{const I=A(C.clientY);c==null||c(I)},onSlideEnd:()=>{w.current=void 0,a==null||a()},onStepKeyDown:C=>{const M=z1e[j?"from-bottom":"from-top"].includes(C.key);f==null||f({event:C,direction:M?-1:1})}})})}),H1e=N.forwardRef((t,e)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:c,onEndKeyDown:a,onStepKeyDown:f,...m}=t,y=bF(pj,r);return s.jsx(cn.span,{...m,ref:e,onKeyDown:Gr(t.onKeyDown,v=>{v.key==="Home"?(c(v),v.preventDefault()):v.key==="End"?(a(v),v.preventDefault()):B1e.concat($1e).includes(v.key)&&(f(v),v.preventDefault())}),onPointerDown:Gr(t.onPointerDown,v=>{const w=v.target;w.setPointerCapture(v.pointerId),v.preventDefault(),y.thumbs.has(w)?w.focus():n(v)}),onPointerMove:Gr(t.onPointerMove,v=>{v.target.hasPointerCapture(v.pointerId)&&i(v)}),onPointerUp:Gr(t.onPointerUp,v=>{const w=v.target;w.hasPointerCapture(v.pointerId)&&(w.releasePointerCapture(v.pointerId),o(v))})})}),W1e="SliderTrack",K1e=N.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=bF(W1e,r);return s.jsx(cn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:e})});K1e.displayName=W1e;var Gq="SliderRange",Y1e=N.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=bF(Gq,r),o=G1e(Gq,r),c=N.useRef(null),a=is(e,c),f=i.values.length,m=i.values.map(w=>Q1e(w,i.min,i.max)),y=f>1?Math.min(...m):0,v=100-Math.max(...m);return s.jsx(cn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:a,style:{...t.style,[o.startEdge]:y+"%",[o.endEdge]:v+"%"}})});Y1e.displayName=Gq;var Hq="SliderThumb",Z1e=N.forwardRef((t,e)=>{const r=Qet(t.__scopeSlider),[n,i]=N.useState(null),o=is(e,a=>i(a)),c=N.useMemo(()=>n?r().findIndex(a=>a.ref.current===n):-1,[r,n]);return s.jsx(ntt,{...t,ref:o,index:c})}),ntt=N.forwardRef((t,e)=>{const{__scopeSlider:r,index:n,name:i,...o}=t,c=bF(Hq,r),a=G1e(Hq,r),[f,m]=N.useState(null),y=is(e,D=>m(D)),v=f?c.form||!!f.closest("form"):!0,w=OC(f),j=c.values[n],A=j===void 0?0:Q1e(j,c.min,c.max),C=att(n,c.values.length),I=w==null?void 0:w[a.size],M=I?ltt(I,A,a.direction):0;return N.useEffect(()=>{if(f)return c.thumbs.add(f),()=>{c.thumbs.delete(f)}},[f,c.thumbs]),s.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${A}% + ${M}px)`},children:[s.jsx(qq.ItemSlot,{scope:t.__scopeSlider,children:s.jsx(cn.span,{role:"slider","aria-label":t["aria-label"]||C,"aria-valuemin":c.min,"aria-valuenow":j,"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:j===void 0?{display:"none"}:t.style,onFocus:Gr(t.onFocus,()=>{c.valueIndexToChangeRef.current=n})})}),v&&s.jsx(X1e,{name:i??(c.name?c.name+(c.values.length>1?"[]":""):void 0),form:c.form,value:j},n)]})});Z1e.displayName=Hq;var stt="RadioBubbleInput",X1e=N.forwardRef(({__scopeSlider:t,value:e,...r},n)=>{const i=N.useRef(null),o=is(i,n),c=KC(e);return N.useEffect(()=>{const a=i.current;if(!a)return;const f=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&y){const v=new Event("input",{bubbles:!0});y.call(a,e),a.dispatchEvent(v)}},[c,e]),s.jsx(cn.input,{style:{display:"none"},...r,ref:o,defaultValue:e})});X1e.displayName=stt;function itt(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,o)=>i-o)}function Q1e(t,e,r){const o=100/(r-e)*(t-e);return hN(o,[0,100])}function att(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function ott(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 ltt(t,e,r){const n=t/2,o=EK([0,50],[0,n]);return(n-o(e)*r)*r}function ctt(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}function utt(t,e){if(e>0){const r=ctt(t);return Math.min(...r)>=e}return!0}function EK(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 dtt(t){return(String(t).split(".")[1]||"").length}function htt(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}var J1e=V1e,ftt=K1e,mtt=Y1e,ptt=Z1e;const Km=N.forwardRef(({className:t,...e},r)=>s.jsxs(J1e,{ref:r,className:Xt("relative flex w-full touch-none select-none items-center",t),...e,children:[s.jsx(ftt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:s.jsx(mtt,{className:"absolute h-full bg-primary"})}),s.jsx(ptt,{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"})]}));Km.displayName=J1e.displayName;const gtt=t=>mr({queryKey:["public-listings",t],queryFn:async()=>{let e=Ce.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!profiles_brokerage_id_fkey(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}}),ytt=()=>mr({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:e}=await Ce.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(),a=o.state?`${o.city}, ${o.state}`:o.city,f=r.get(c);f?f.count++:r.set(c,{label:a,city:o.city,state:o.state,count:1})}if(o.neighborhood){const c=`${o.neighborhood}|${o.city||""}`.toLowerCase(),a=o.city?`${o.neighborhood} — ${o.city}`:o.neighborhood,f=n.get(c);f?f.count++:n.set(c,{label:a,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 a=c[1],f=i.get(a);f?f.count++:i.set(a,{label:a,zip:a,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)}}}),xtt=t=>mr({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=Ce.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!profiles_brokerage_id_fkey(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).not("status","in","(temp_off_market,withdrawn)");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,a)=>(c.sort_order??0)-(a.sort_order??0)||(a.is_primary?1:0)-(c.is_primary?1:0))),o},enabled:!!t}),vtt=()=>Ar({mutationFn:async({listingId:t,agentId:e,firstName:r,lastName:n,email:i,phone:o,shareToken:c,leadType:a="info_request",preferredDate:f,preferredTime:m,showingMode:y,message:v})=>{let w=null,j=null;if(c){const{data:D}=await Ce.from("listing_shares").select("id, sharing_agent_id").eq("share_token",c).eq("listing_id",t).maybeSingle();D&&(w=D.id,j=D.sharing_agent_id)}const A=crypto.randomUUID(),C={id:A},{error:I}=await Ce.from("listing_leads").insert({id:A,listing_id:t,agent_id:j||e,first_name:r,last_name:n,email:i,phone:o,share_id:w,referred_by_agent_id:j,lead_type:a,preferred_date:f||null,preferred_time:m||null,showing_mode:y||null,message:v||null});if(I)throw I;const{error:M}=await Ce.functions.invoke("process-listing-lead",{body:{leadId:C.id}});return M&&console.error("Error processing lead:",M),C}}),_tt=()=>Ar({mutationFn:async t=>{const{error:e}=await Ce.rpc("increment_listing_share_click",{p_share_token:t});if(e)throw e}});function btt({title:t,subtitle:e,areaLabel:r,sections:n,agent:i,tone:o="light"}){const c=o==="dark",a=c?"text-white/65":"text-muted-foreground",f=c?"border-white/10":"border-border";return s.jsxs("div",{className:c?"text-white":"text-foreground",id:"community-guide-print",children:[s.jsxs("header",{className:`border-b ${f} pb-6 mb-8`,children:[s.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${a} mb-3`,children:[s.jsx(QS,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),s.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:t}),e&&s.jsx("p",{className:`mt-3 text-base leading-relaxed ${a}`,children:e}),r&&s.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${a}`,children:[s.jsx(ii,{className:"h-3.5 w-3.5"}),r]})]}),s.jsx("div",{className:"space-y-10",children:n.map((m,y)=>s.jsxs("section",{children:[s.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[s.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(y+1).padStart(2,"0")}),s.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:m.heading})]}),m.intro&&s.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${a} mb-4`,children:m.intro}),s.jsx("ul",{className:"space-y-3",children:(m.items??[]).map((v,w)=>s.jsxs("li",{className:`rounded-xl border ${f} ${c?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[s.jsx("p",{className:"font-medium text-sm sm:text-base",children:v.name}),v.note&&s.jsx("p",{className:`text-sm mt-1 leading-relaxed ${a}`,children:v.note})]},w))})]},y))}),(i==null?void 0:i.name)&&s.jsxs("footer",{className:`mt-10 pt-6 border-t ${f}`,children:[s.jsxs("div",{className:"flex items-center gap-4",children:[i.avatar_url?s.jsx("img",{src:i.avatar_url,alt:i.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${a}`,children:"Prepared for you by"}),s.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:i.name}),i.brokerage&&s.jsx("p",{className:`text-sm ${a}`,children:i.brokerage}),s.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${a}`,children:[i.phone&&s.jsxs("a",{href:`tel:${i.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[s.jsx(Fn,{className:"h-3.5 w-3.5"}),i.phone]}),i.email&&s.jsxs("a",{href:`mailto:${i.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[s.jsx(rs,{className:"h-3.5 w-3.5"}),i.email]})]})]})]}),s.jsxs("p",{className:`mt-4 text-sm ${a}`,children:["Thinking about a move in ",r||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const AL="border-white/15 bg-white/5 text-white placeholder:text-white/40";function wtt({listingId:t}){const[e,r]=N.useState(null),[n,i]=N.useState({firstName:"",lastName:"",email:"",phone:""}),[o,c]=N.useState(!1),[a,f]=N.useState(null),[m,y]=N.useState(!1);if(N.useEffect(()=>{let w=!1;return Ce.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:t}}).then(({data:j})=>{!w&&j&&r(j)}).catch(()=>{}),()=>{w=!0}},[t]),!(e!=null&&e.available))return null;const v=async w=>{if(w.preventDefault(),!n.firstName.trim()||!n.email.trim()){$t.error("Please add your name and email.");return}c(!0);try{const{data:j,error:A}=await Ce.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:t,...n}});if(A||j!=null&&j.error)throw new Error((j==null?void 0:j.error)||"Something went wrong.");f(j),y(!0),$t.success("Your guide is ready!")}catch(j){$t.error((j==null?void 0:j.message)||"We could not send your guide. Please try again.")}finally{c(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[s.jsx(QS,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),s.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:e.title}),e.subtitle&&s.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:e.subtitle}),(e.teaser??[]).length>0&&s.jsx("ul",{className:"mt-4 space-y-2",children:e.teaser.map((w,j)=>s.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[s.jsx(pa,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),w]},j))}),a?s.jsxs(Lt,{className:"w-full mt-5",onClick:()=>y(!0),children:[s.jsx(QS,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):s.jsxs("form",{onSubmit:v,className:"mt-5 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),s.jsx(Or,{id:"cg-first",value:n.firstName,onChange:w=>i({...n,firstName:w.target.value}),className:AL,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),s.jsx(Or,{id:"cg-last",value:n.lastName,onChange:w=>i({...n,lastName:w.target.value}),className:AL})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),s.jsx(Or,{id:"cg-email",type:"email",value:n.email,onChange:w=>i({...n,email:w.target.value}),className:AL,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),s.jsx(Or,{id:"cg-phone",type:"tel",value:n.phone,onChange:w=>i({...n,phone:w.target.value}),className:AL})]}),s.jsxs(Lt,{type:"submit",className:"w-full",disabled:o,children:[o?s.jsx(zc,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(yc,{className:"h-4 w-4 mr-2"}),o?"Preparing your guide…":"Get the free guide"]}),s.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[s.jsx(Wx,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),s.jsx(Wa,{open:m,onOpenChange:y,children:s.jsx(La,{className:"max-w-2xl p-0 gap-0",children:s.jsx(hp,{className:"max-h-[82vh]",children:s.jsxs("div",{className:"p-6 sm:p-8",children:[s.jsx("div",{id:"community-guide-print",children:a&&s.jsx(btt,{title:a.title,subtitle:a.subtitle,areaLabel:a.area_label,sections:a.sections??[],agent:a.agent})}),s.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:s.jsxs(Lt,{variant:"outline",onClick:()=>Stt(a==null?void 0:a.title),children:[s.jsx(yc,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function Stt(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 Eie={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},eSe={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"},Qer=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],Ttt={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},jtt={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},Jer={public:"Open download",email:"Email required",nda:"NDA required"},Ett={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},etr=[{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"}],L6=[{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"}],ttr=[{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 kf(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 kie(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`:kf(e)}function Wq(t){return t==null?null:`${new Intl.NumberFormat("en-US").format(Number(t))} SF`}function tSe(t,e=2){return t==null?null:`${Number(t).toFixed(e).replace(/\.?0+$/,"")}%`}function Kq(t){if(!(t!=null&&t.lease_rate))return null;const e=Ttt[t.lease_rate_unit||"sf_year"]??"";return`${t.lease_rate_unit==="month"?kf(t.lease_rate):`$${Number(t.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${e}${t.lease_type?` ${t.lease_type}`:""}`}function Aie(t,e){if(!t)return kf(e)??"Price on request";if(t.deal_type==="lease")return Kq(t)??"Rate on request";const r=t.asking_price??e;if(t.deal_type==="sale_or_lease"){const n=[kf(r),Kq(t)].filter(Boolean);return n.length?n.join(" · "):"Price on request"}return kf(r)??"Price on request"}function ktt(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?eSe[e.commercial_type]:"Commercial"} Opportunity`:t.property_address||`${t.city??""}, ${t.state??""}`}function Att(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 rtr(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 L6)(i[c.key]||r[c.key])&&n.push(c.key);return{done:n,total:L6.length,score:Math.round(n.length/L6.length*100)}}const ntr={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 str(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 itr="https://commercial.relevelup.com",rp=Ce;function atr(t){return mr({queryKey:["commercial-details",t],queryFn:async()=>{const{data:e,error:r}=await rp.from("commercial_listing_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function otr(){const t=kr(),{user:e}=Zn();return Ar({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await rp.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 ltr(t){return mr({queryKey:["commercial-pitch",t],queryFn:async()=>{const{data:e,error:r}=await rp.from("commercial_pitch_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function ctr(){const t=kr(),{user:e}=Zn();return Ar({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await rp.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 utr(){const t=kr();return Ar({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:a}=await rp.from("listings").update(c).eq("id",e);if(a)throw a;return(i||o)&&await rp.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 dtr(){const t=kr();return Ar({mutationFn:async({listingId:e,values:r})=>{const{error:n}=await rp.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 htr(t,e=90){return mr({queryKey:["commercial-engagement",t,e],queryFn:async()=>{const r=new Date(Date.now()-e*864e5).toISOString(),{data:n,error:i}=await rp.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 ftr(t){return mr({queryKey:["commercial-leads",t],queryFn:async()=>{const{data:e,error:r}=await rp.from("listing_leads").select("*").eq("listing_id",t).order("created_at",{ascending:!1});if(r)throw r;return e??[]},enabled:!!t})}const Nie="lu_commercial_session";function rSe(){try{let t=localStorage.getItem(Nie);return t||(t=crypto.randomUUID(),localStorage.setItem(Nie,t)),t}catch{return"anonymous"}}async function h1(t,e,r={}){try{await rp.from("commercial_engagement_events").insert({listing_id:t,event_type:e,session_id:rSe(),source:typeof document<"u"&&document.referrer||null,metadata:r})}catch{}}const Ntt={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 Ctt({open:t,onOpenChange:e,listingId:r,kind:n,documentId:i,requiresNda:o,brokerName:c}){const a=Ntt[n],[f,m]=N.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[y,v]=N.useState(!1),[w,j]=N.useState(!1),[A,C]=N.useState(null),I=async()=>{if(!f.firstName.trim()||!f.email.trim()){$t.error("Name and email are required");return}if(o&&n==="om_request"&&!y){$t.error("Please acknowledge the confidentiality terms");return}j(!0);try{const{data:M,error:D}=await Ce.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:rSe()}});if(D)throw D;if(M!=null&&M.error)throw new Error(M.error);C({signedUrl:(M==null?void 0:M.signedUrl)??null,fileName:(M==null?void 0:M.fileName)??null}),M!=null&&M.signedUrl&&window.open(M.signedUrl,"_blank")}catch(M){$t.error(M.message||"Something went wrong. Please try again.")}finally{j(!1)}};return s.jsx(Wa,{open:t,onOpenChange:M=>{e(M),M||C(null)},children:s.jsxs(La,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[s.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:a.eyebrow}),s.jsx("h2",{className:"mt-2 font-serif text-2xl",children:A?"Access granted":a.title}),s.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:A?A.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.`:a.blurb})]}),A?s.jsxs("div",{className:"space-y-4 px-7 py-7",children:[s.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[s.jsx(Il,{className:"h-5 w-5 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white/80",children:A.fileName??"Request received"})]}),A.signedUrl&&s.jsx(Lt,{className:"w-full",onClick:()=>window.open(A.signedUrl,"_blank"),children:"Download again"}),s.jsx(Lt,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>e(!1),children:"Close"})]}):s.jsxs("div",{className:"space-y-4 px-7 py-6",children:[s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Vv,{label:"First name *",children:s.jsx(Or,{value:f.firstName,onChange:M=>m({...f,firstName:M.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(Vv,{label:"Last name",children:s.jsx(Or,{value:f.lastName,onChange:M=>m({...f,lastName:M.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(Vv,{label:"Email *",children:s.jsx(Or,{type:"email",value:f.email,onChange:M=>m({...f,email:M.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Vv,{label:"Company",children:s.jsx(Or,{value:f.company,onChange:M=>m({...f,company:M.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(Vv,{label:"Phone",children:s.jsx(Or,{value:f.phone,onChange:M=>m({...f,phone:M.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(Vv,{label:"I am a *",children:s.jsxs(Pa,{value:f.role,onValueChange:M=>m({...f,role:M}),children:[s.jsx(va,{className:"border-white/15 bg-white/5 text-white",children:s.jsx(Ra,{})}),s.jsx(_a,{children:Object.entries(Ett).map(([M,D])=>s.jsx(gn,{value:M,children:D},M))})]})}),n!=="om_request"&&s.jsx(Vv,{label:"Message",children:s.jsx(qc,{rows:3,value:f.message,onChange:M=>m({...f,message:M.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"&&s.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[s.jsx(mj,{checked:y,onCheckedChange:M=>v(!!M),className:"mt-0.5 border-white/30"}),s.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[s.jsx(S3,{className:"mr-1 inline h-3.5 w-3.5"}),"I acknowledge these materials are confidential and agree not to distribute them without the listing broker's written consent."]})]}),s.jsxs(Lt,{className:"w-full",size:"lg",onClick:I,disabled:w,children:[w?s.jsx(zc,{className:"mr-2 h-4 w-4 animate-spin"}):s.jsx(Wx,{className:"mr-2 h-4 w-4"}),a.cta]}),s.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function Vv({label:t,children:e}){return s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:t}),e]})}function nSe(t){if(!t)return[];const e=[],r=(n,i)=>{i&&e.push({label:n,value:i})};return r("Cap Rate",tSe(t.cap_rate)),r("NOI",kie(t.noi)),r("Occupancy",t.occupancy_pct!=null?`${Math.round(Number(t.occupancy_pct))}%`:null),r("Building SF",Wq(t.building_sf)),r("Available SF",Wq(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?kf(t.price_per_sf,2):null),r("Price / Unit",kie(t.price_per_unit)),r("Lease Rate",t.deal_type!=="sale"?Kq(t):null),r("Year Built",null),r("Zoning",t.zoning??null),e}function mtr({details:t,className:e="",tone:r="light"}){const n=nSe(t).slice(0,8);if(!n.length)return null;const i=r==="dark";return s.jsx("div",{className:`grid gap-px overflow-hidden rounded-xl border ${i?"border-white/10 bg-white/10":"bg-border"} sm:grid-cols-2 lg:grid-cols-4 ${e}`,children:n.map(o=>s.jsxs("div",{className:`${i?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[s.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${i?"text-white/45":"text-muted-foreground"}`,children:o.label}),s.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${i?"text-white":""}`,children:o.value})]},o.label))})}function Itt(t){return mr({queryKey:["commercial-microsite",t],queryFn:async()=>{const{data:e,error:r}=await Ce.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 Ptt({slug:t}){var oe,de;const{data:e,isLoading:r,error:n}=Itt(t),[i,o]=N.useState(null),[c,a]=N.useState(null),f=e==null?void 0:e.listing,m=(e==null?void 0:e.details)??void 0,y=(e==null?void 0:e.documents)??[],v=(f==null?void 0:f.photos)??[],w=f==null?void 0:f.agent,j=!!(m!=null&&m.is_confidential||m!=null&&m.hide_address),A=N.useMemo(()=>nSe(m).slice(0,8),[m]);if(N.useEffect(()=>{f!=null&&f.id&&h1(f.id,"page_view",{slug:t})},[f==null?void 0:f.id,t]),N.useEffect(()=>{if(i===null)return;const ye=we=>{we.key==="Escape"&&o(null),we.key==="ArrowRight"&&o(Le=>Le===null?Le:(Le+1)%v.length),we.key==="ArrowLeft"&&o(Le=>Le===null?Le:(Le-1+v.length)%v.length)};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},[i,v.length]),r)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(n||!f)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const C=ktt(f,m),I=Att(f,m),M=f.latitude&&f.longitude?`${f.latitude},${f.longitude}`:j?[m==null?void 0:m.submarket,f.city,f.state].filter(Boolean).join(", ")||null:[f.property_address,f.city,f.state].filter(Boolean).join(", ")||null,D=(oe=v[0])==null?void 0:oe.photo_url,F=(m==null?void 0:m.tenants)??[],z=(m==null?void 0:m.spaces)??[],q=(m==null?void 0:m.demographics)??{},H=(m==null?void 0:m.traffic_counts)??[],K=(m==null?void 0:m.investment_highlights)??[],J=(m==null?void 0:m.property_highlights)??[],Q=["radius_1","radius_3","radius_5"].some(ye=>(q==null?void 0:q[ye])&&Object.values(q[ye]).some(Boolean)),ee=(ye,we)=>{a({kind:ye,documentId:we}),h1(f.id,ye==="om_request"?"om_request":ye,{})};return s.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[s.jsxs(no,{children:[s.jsx("title",{children:`${C} | ${I}`}),s.jsx("meta",{name:"description",content:(f.description??"").slice(0,155)||`${Eie[(m==null?void 0:m.deal_type)??"sale"]} — ${I}`}),j&&s.jsx("meta",{name:"robots",content:"noindex,nofollow"}),s.jsx("meta",{property:"og:title",content:C}),s.jsx("meta",{property:"og:type",content:"website"})]}),s.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:s.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[s.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[s.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),s.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[D?s.jsx("img",{src:D,alt:C,className:"absolute inset-0 h-full w-full object-cover"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),s.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[s.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[s.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:Eie[(m==null?void 0:m.deal_type)??"sale"]}),(m==null?void 0:m.commercial_type)&&s.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:eSe[m.commercial_type]}),j&&s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[s.jsx(Wx,{className:"h-3 w-3"})," Confidential offering"]})]}),s.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:C}),s.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[s.jsx(ii,{className:"h-4 w-4"})," ",I]}),s.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(m==null?void 0:m.deal_type)==="lease"?"Lease rate":"Asking price"}),s.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:Aie(m,f.price)})]}),(m==null?void 0:m.cap_rate)!=null&&s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),s.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:tSe(m.cap_rate)})]})]}),s.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[s.jsxs(Lt,{size:"lg",className:"rounded-full px-7",onClick:()=>{var ye;return ee("om_request",((ye=y.find(we=>we.doc_kind==="om"))==null?void 0:ye.id)??null)},children:["Request Offering Memorandum ",s.jsx(ei,{className:"ml-2 h-4 w-4"})]}),s.jsx(Lt,{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:()=>ee("tour_request"),children:"Schedule a tour"})]})]})]}),A.length>0&&s.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:s.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(A.length,4)}, minmax(0, 1fr))`},children:A.map(ye=>s.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:ye.label}),s.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:ye.value})]},ye.label))})}),K.length>0&&s.jsx(Uy,{eyebrow:"The opportunity",title:"Investment highlights",children:s.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:K.map((ye,we)=>s.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[s.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(we+1).padStart(2,"0")}),s.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:ye})]},we))})}),(f.description||J.length>0)&&s.jsx(Uy,{eyebrow:"Property",title:"The asset",children:s.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[f.description&&s.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(f.description).split(/\n{2,}/).map((ye,we)=>s.jsx("p",{children:ye},we))}),J.length>0&&s.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:J.map((ye,we)=>s.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[s.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",ye]},we))})]})}),v.length>1&&s.jsx(Uy,{eyebrow:"Gallery",title:"Property imagery",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:v.slice(1,10).map((ye,we)=>s.jsx("button",{onClick:()=>{o(we+1),h1(f.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${we===0?"md:col-span-2 md:row-span-2":""}`,children:s.jsx("img",{src:ye.photo_url,alt:`${C} — image ${we+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${we===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},ye.id))})}),((m==null?void 0:m.noi)||(m==null?void 0:m.gross_income)||(m==null?void 0:m.operating_expenses)||(m==null?void 0:m.occupancy_pct)!=null)&&s.jsxs(Uy,{eyebrow:"Financials",title:"Offering snapshot",children:[s.jsx("div",{className:"grid gap-px overflow-hidden rounded-2xl border border-white/10 bg-white/10 sm:grid-cols-2 lg:grid-cols-4",children:[{l:"Net operating income",v:kf(m==null?void 0:m.noi)},{l:"Gross income",v:kf(m==null?void 0:m.gross_income)},{l:"Operating expenses",v:kf(m==null?void 0:m.operating_expenses)},{l:"Occupancy",v:(m==null?void 0:m.occupancy_pct)!=null?`${Math.round(Number(m.occupancy_pct))}%`:null},{l:"Price per SF",v:(m==null?void 0:m.price_per_sf)!=null?kf(m.price_per_sf,2):null},{l:"Price per unit",v:kf(m==null?void 0:m.price_per_unit)},{l:"Tenancy",v:m!=null&&m.tenancy?`${m.tenancy[0].toUpperCase()}${m.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(m==null?void 0:m.broker_coop_pct)!=null?`${m.broker_coop_pct}%`:null}].filter(ye=>ye.v).map(ye=>s.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:ye.l}),s.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:ye.v})]},ye.l))}),(m==null?void 0:m.call_for_offers_at)&&s.jsxs("p",{className:"mt-6 inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-300/10 px-5 py-2 text-sm text-amber-100",children:["Call for offers · ",new Date(m.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(F.length>0||z.length>0)&&s.jsx(Uy,{eyebrow:"Occupancy",title:z.length?"Space availability":"Tenant roster",children:s.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:s.jsxs("table",{className:"w-full text-left text-sm",children:[s.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-6 py-4",children:z.length?"Suite":"Tenant"}),s.jsx("th",{className:"px-6 py-4",children:"SF"}),s.jsx("th",{className:"px-6 py-4",children:z.length?"Rate":"Rent"}),s.jsx("th",{className:"px-6 py-4",children:z.length?"Availability":"Lease expiry"})]})}),s.jsx("tbody",{className:"divide-y divide-white/5",children:(z.length?z:F).map((ye,we)=>s.jsxs("tr",{className:"text-white/80",children:[s.jsx("td",{className:"px-6 py-4 font-medium text-white",children:ye.suite??ye.name??"—"}),s.jsx("td",{className:"px-6 py-4 tabular-nums",children:ye.sf?Wq(Number(ye.sf)):"—"}),s.jsx("td",{className:"px-6 py-4",children:ye.rate??ye.rent??"—"}),s.jsx("td",{className:"px-6 py-4",children:ye.availability??ye.lease_expiry??"—"})]},we))})]})})}),s.jsx(Uy,{eyebrow:"Location",title:m!=null&&m.submarket?`${m.submarket} submarket`:I,children:s.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[M?s.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:s.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(M)}&z=${f.latitude&&f.longitude?15:12}&output=embed`,onLoad:()=>h1(f.id,"map_view",{})})}):s.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:j?"Exact location released with the Offering Memorandum.":I}),s.jsxs("div",{className:"space-y-5",children:[(m==null?void 0:m.zoning)&&s.jsx(f1,{label:"Zoning",value:m.zoning}),(m==null?void 0:m.lot_acres)!=null&&s.jsx(f1,{label:"Site size",value:`${m.lot_acres} acres`}),(m==null?void 0:m.parking_spaces)!=null&&s.jsx(f1,{label:"Parking",value:`${m.parking_spaces} spaces`}),(m==null?void 0:m.opportunity_zone)&&s.jsx(f1,{label:"Opportunity Zone",value:"Qualified"}),H.filter(ye=>ye.road||ye.count).map((ye,we)=>s.jsx(f1,{label:`Traffic count — ${ye.road??"Adjacent road"}`,value:`${ye.count??"—"} VPD`},we)),!(m!=null&&m.zoning)&&(m==null?void 0:m.lot_acres)==null&&(m==null?void 0:m.parking_spaces)==null&&!(m!=null&&m.opportunity_zone)&&s.jsx(f1,{label:"Submarket",value:(m==null?void 0:m.submarket)||I})]})]})}),Q&&s.jsx(Uy,{eyebrow:"Market",title:"Demographics",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([ye,we])=>{const Le=q==null?void 0:q[ye];return!Le||!Object.values(Le).some(Boolean)?null:s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:we}),s.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",Le.population],["Households",Le.households],["Avg. income",Le.avg_income],["Daytime pop.",Le.daytime_pop]].filter(([,Se])=>Se).map(([Se,ve])=>s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("dt",{className:"text-white/50",children:Se}),s.jsx("dd",{className:"font-medium tabular-nums",children:ve})]},Se))})]},ye)})})}),y.length>0&&s.jsx(Uy,{eyebrow:"Deal room",title:"Offering documents",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:y.map(ye=>{const we=ye.gate_level==="public";return s.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-colors hover:border-white/20",children:[s.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:we?s.jsx(yc,{className:"h-5 w-5"}):ye.gate_level==="nda"?s.jsx(S3,{className:"h-5 w-5"}):s.jsx(Wx,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate font-medium",children:ye.title||jtt[ye.doc_kind||"other"]}),s.jsx("p",{className:"text-xs text-white/45",children:we?"Available to download":ye.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),s.jsx(Lt,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>ee("om_request",ye.id),children:we?"Download":"Request"})]},ye.id)})})}),w&&s.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:s.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:s.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-6",children:[w.avatar_url&&s.jsx("img",{src:w.avatar_url,alt:w.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),s.jsx("p",{className:"mt-2 font-serif text-2xl",children:w.name}),s.jsx("p",{className:"text-sm text-white/55",children:((de=w.brokerage)==null?void 0:de.name)||w.brokerage_name})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-3",children:[w.email&&s.jsxs(Lt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{h1(f.id,"contact_click",{}),window.location.href=`mailto:${w.email}`},children:[s.jsx(rs,{className:"mr-2 h-4 w-4"})," Email"]}),w.phone&&s.jsxs(Lt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{h1(f.id,"contact_click",{}),window.location.href=`tel:${w.phone}`},children:[s.jsx(Fn,{className:"mr-2 h-4 w-4"})," Call"]}),s.jsx(Lt,{className:"rounded-full",onClick:()=>ee("investor_inquiry"),children:"Request information"})]})]})})}),s.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:s.jsx("p",{children:"The information contained herein has been obtained from sources believed reliable but is not guaranteed. Prospective purchasers and tenants should conduct their own independent investigation."})}),s.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:s.jsxs("div",{className:"mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-6 py-3.5 md:px-10",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium",children:C}),s.jsxs("p",{className:"truncate text-xs text-white/50",children:[Aie(m,f.price)," · ",I]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Lt,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>ee("tour_request"),children:"Tour"}),s.jsx(Lt,{size:"sm",className:"rounded-full",onClick:()=>{var ye;return ee("om_request",((ye=y.find(we=>we.doc_kind==="om"))==null?void 0:ye.id)??null)},children:"Request OM"})]})]})}),s.jsx(Wa,{open:i!==null,onOpenChange:ye=>!ye&&o(null),children:s.jsx(La,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:i!==null&&v[i]&&s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:v[i].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),s.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>o(null),children:s.jsx(Ci,{className:"h-5 w-5"})}),s.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>o(ye=>(ye-1+v.length)%v.length),children:s.jsx(lp,{className:"h-6 w-6"})}),s.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>o(ye=>(ye+1)%v.length),children:s.jsx(Wd,{className:"h-6 w-6"})})]})})}),c&&s.jsx(Ctt,{open:!0,onOpenChange:ye=>!ye&&a(null),listingId:f.id,kind:c.kind,documentId:c.documentId,requiresNda:!!(m!=null&&m.requires_nda)||(m==null?void 0:m.om_gate_mode)==="nda",brokerName:w==null?void 0:w.name})]})}function Uy({eyebrow:t,title:e,children:r}){return s.jsx("section",{className:"border-t border-white/10",children:s.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:t}),s.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:e}),s.jsx("div",{className:"mt-12",children:r})]})})}function f1({label:t,value:e}){return s.jsxs("div",{className:"border-t border-white/10 pt-4",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:t}),s.jsx("p",{className:"mt-1 text-lg",children:e})]})}const Cie="/assets/levelup-logo-color-BeKd2k_g.png",Rtt={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"},M6={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"},Iie={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},D6=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),mk=t=>new Intl.NumberFormat("en-US").format(t);function sSe(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 kK({slugOverride:t}={}){var zi,Ir,$n,Si,oi,ia,Xr;const e=id(),r=t||e.slugOrId,[n]=y0(),{data:i,isLoading:o}=xtt(r||""),c=vtt(),a=_tt(),f=n.get("ref"),[m,y]=N.useState(""),[v,w]=N.useState(""),[j,A]=N.useState(""),[C,I]=N.useState(""),[M,D]=N.useState(""),[F,z]=N.useState(""),[q,H]=N.useState(""),[K,J]=N.useState("in_person"),[Q,ee]=N.useState("info"),[oe,de]=N.useState(!1),[ye,we]=N.useState(!1),[Le,Se]=N.useState(null),[ve,me]=N.useState(!1);N.useState(!1);const[ke,Pe]=N.useState(!1),[Ee,xe]=N.useState(20),[Ue,Ze]=N.useState(6.5),[lt,wt]=N.useState(30),yt=N.useRef(null),[gt,ft]=N.useState(!1);N.useEffect(()=>{const un=()=>ft(window.scrollY>300);return window.addEventListener("scroll",un,{passive:!0}),()=>window.removeEventListener("scroll",un)},[]),N.useEffect(()=>{f&&a.mutate(f)},[f]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const kt=(i==null?void 0:i.photos)||[],Vt=kt.find(un=>un.is_primary)||kt[0],xt=N.useMemo(()=>{if(!(i!=null&&i.price))return 0;const un=i.price*(1-Ee/100),xn=Ue/100/12,Qr=lt*12;return xn===0?un/Qr:un*xn/(1-Math.pow(1+xn,-Qr))},[i==null?void 0:i.price,Ee,Ue,lt]),or=async()=>{const un=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:un})}catch{}else await navigator.clipboard.writeText(un),$t.success("Link copied to clipboard")},Tr=async un=>{if(un.preventDefault(),!m.trim()||!j.trim()||!i)return;const xn=Q==="showing";if(xn&&!F){$t.error("Please pick a preferred date for your showing");return}de(!0);try{await c.mutateAsync({listingId:i.id,agentId:i.agent_id,firstName:m.trim(),lastName:v.trim(),email:j.trim(),phone:C.trim(),shareToken:f,leadType:xn?"showing_request":"info_request",preferredDate:xn?F:null,preferredTime:xn&&q||null,showingMode:xn?K:null,message:M.trim()||null}),we(!0),$t.success(xn?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Qr){console.error("Lead submission error:",Qr),$t.error(`Failed to submit: ${Qr.message||"Please try again"}`)}finally{de(!1)}},rn=()=>{Le!==null&&Se(Le===0?kt.length-1:Le-1)},Lr=()=>{Le!==null&&Se(Le===kt.length-1?0:Le+1)};if((i==null?void 0:i.listing_class)==="commercial")return s.jsx(Ptt,{slug:r});if(o)return s.jsx("div",{className:"min-h-screen bg-neutral-950",children:s.jsx(Al,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!i)return s.jsxs("div",{className:"min-h-screen bg-background",children:[s.jsx("header",{className:"border-b bg-card",children:s.jsx("div",{className:"container mx-auto px-4 py-4",children:s.jsx(xr,{to:"/public/listings",className:"flex items-center gap-2",children:s.jsx("img",{src:Cie,alt:"LevelUp",className:"h-8"})})})}),s.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[s.jsx(ta,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),s.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),s.jsx(Lt,{asChild:!0,children:s.jsx(xr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const $r=i.property_address?`${i.property_address} — ${i.city}, ${i.state}`:`${i.city}, ${i.state} Home for Sale`,qr=((Ir=(zi=i.agent)==null?void 0:zi.brokerage)==null?void 0:Ir.name)||(($n=i.agent)==null?void 0:$n.brokerage_name),Nn=((Si=i.agent)==null?void 0:Si.name)||"",tt=sSe(i.video_link),Tt=qr||Nn||"",Zt=M6[i.status]==="Sold"?"Just Sold":M6[i.status],ar=Zt?`${Zt}: ${$r}`:$r,Wt=[`${D6(i.price)} · ${i.city}, ${i.state}`,Nn?`Presented by ${Nn}${qr?`, ${qr}`:""}.`:""].filter(Boolean).join(" · "),Kt=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,At=i.description||"",pr=At.length>420,yn=ke||!pr?At:At.slice(0,420).trimEnd()+"…",Gn=i.page_config||{},Bn=un=>{var xn;return(((xn=Gn.sections)==null?void 0:xn[un])??!0)!==!1},Rs=Array.isArray(Gn.addons)?Gn.addons:[],sa=Gn.custom_note||"",gs=Gn.accent_color||null;return s.jsxs(s.Fragment,{children:[s.jsxs(no,{children:[s.jsx("title",{children:Tt?`${$r} | ${Tt}`:$r}),s.jsx("meta",{name:"description",content:`${D6(i.price)} · ${i.bedrooms||""}BD ${i.bathrooms||""}BA ${i.square_footage?i.square_footage.toLocaleString()+" sqft · ":""}${Iie[i.property_type]} in ${i.city}, ${i.state}. ${At.slice(0,140)}`}),s.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${i.slug||i.id}`}),s.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),s.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),s.jsx("meta",{property:"og:title",content:ar}),s.jsx("meta",{property:"og:description",content:Wt}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${i.slug||i.id}`}),Vt&&s.jsx("meta",{property:"og:image",content:Vt.photo_url}),Tt&&s.jsx("meta",{property:"og:site_name",content:Tt}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:ar}),s.jsx("meta",{name:"twitter:description",content:Wt}),Vt&&s.jsx("meta",{name:"twitter:image",content:Vt.photo_url}),s.jsx("meta",{name:"robots",content:"index, follow"}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:i.property_address||`${i.city}, ${i.state} Home`,description:At,url:`https://listings.relevelup.com/${i.slug||i.id}`,datePosted:i.created_at,image:kt.map(un=>un.photo_url),address:{"@type":"PostalAddress",streetAddress:i.property_address||void 0,addressLocality:i.city,addressRegion:i.state,addressCountry:"US"},offers:{"@type":"Offer",price:i.price,priceCurrency:"USD",availability:i.status==="sold"?"https://schema.org/SoldOut":i.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:i.bedrooms||void 0,numberOfBathroomsTotal:i.bathrooms||void 0,floorSize:i.square_footage?{"@type":"QuantitativeValue",value:i.square_footage,unitCode:"FTK"}:void 0,yearBuilt:i.year_built||void 0})}),s.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),s.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[s.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${gt?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[s.jsxs(xr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[s.jsx(Hx,{className:"h-4 w-4"}),s.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),gt&&s.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([un,xn])=>s.jsx("a",{href:`#${un}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:xn},un))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Zet,{listingId:i.id,listingAddress:i.property_address?`${i.property_address}, ${i.city}, ${i.state}`:`${i.city}, ${i.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),s.jsx("button",{onClick: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:s.jsx(NC,{className:"h-4 w-4 text-white"})}),s.jsx(Lt,{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"})]})]})}),s.jsxs("section",{ref:yt,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Vt?s.jsx("img",{src:Vt.photo_url,alt:i.property_address||`${i.city}, ${i.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),s.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[s.jsx(gi,{className:`${Rtt[i.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:M6[i.status]}),kt.length>0&&s.jsxs("button",{onClick:()=>Se(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[s.jsx(cne,{className:"h-3.5 w-3.5"}),kt.length," photos"]})]}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:s.jsxs("div",{className:"max-w-7xl mx-auto",children:[s.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[s.jsxs("div",{className:"max-w-3xl",children:[i.neighborhood&&s.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[i.neighborhood," · ",i.city,", ",i.state]}),i.property_address&&s.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:i.property_address}),!i.property_address&&s.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[i.city,", ",i.state]}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:D6(i.price)}),s.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),s.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[i.bedrooms&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:i.bedrooms})," bd"]}),i.bathrooms&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:i.bathrooms})," ba"]}),i.square_footage&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:mk(i.square_footage)})," sqft"]})]})]})]}),s.jsxs("div",{className:"hidden md:flex flex-col gap-2",children:[i.agent&&s.jsxs("div",{className:"flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[i.agent.avatar_url?s.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-12 w-12 rounded-full object-cover"}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:s.jsx(Wl,{className:"h-6 w-6 text-white"})}),s.jsxs("div",{className:"pr-2 flex-1",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),s.jsx("p",{className:"text-white font-medium leading-tight",children:i.agent.name}),qr&&s.jsx("p",{className:"text-xs text-white/60",children:qr})]}),s.jsx(Lt,{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&&s.jsxs("div",{className:"flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[i.co_agent_photo_url?s.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:s.jsx(Wl,{className:"h-6 w-6 text-white"})}),s.jsxs("div",{className:"pr-2 flex-1",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Co-Listing Agent"}),s.jsx("p",{className:"text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&s.jsx("p",{className:"text-xs text-white/60",children:i.co_agent_brokerage})]}),(i.co_agent_phone||i.co_agent_email)&&s.jsx(Lt,{asChild:!0,size:"sm",className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:s.jsx("a",{href:i.co_agent_phone?`tel:${i.co_agent_phone}`:`mailto:${i.co_agent_email}`,children:"Contact"})})]})]})]}),s.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[s.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),Bn("stats")&&s.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:s.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[i.bedrooms&&{icon:ZT,label:"Bedrooms",value:i.bedrooms},i.bathrooms&&{icon:m0,label:"Bathrooms",value:i.bathrooms},i.square_footage&&{icon:OH,label:"Interior",value:`${mk(i.square_footage)} sqft`},i.lot_size&&{icon:AC,label:"Lot Size",value:i.lot_size},i.year_built&&{icon:bo,label:"Year Built",value:i.year_built},!i.year_built&&i.square_footage&&{icon:N8,label:"Price / sqft",value:`$${mk(Math.round(i.price/i.square_footage))}`}].filter(Boolean).slice(0,5).map((un,xn)=>s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:s.jsx(un.icon,{className:"h-4 w-4 text-white/70"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:un.label}),s.jsx("p",{className:"font-display text-2xl text-white font-light",children:un.value})]})]},xn))})}),s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[s.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[Bn("story")&&At&&s.jsxs("section",{id:"story",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),s.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:s.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:yn})}),pr&&s.jsx("button",{onClick:()=>Pe(!ke),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ke?"Show less":"Read more"}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[s.jsxs(gi,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[s.jsx(to,{className:"h-3 w-3 mr-1.5"}),Iie[i.property_type]]}),i.has_hoa&&s.jsx(gi,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),i.mls_link&&s.jsx(Lt,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:i.mls_link,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(mb,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(sa||i.agent_notes&&i.agent_notes_public)&&s.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(ki,{className:"h-4 w-4 text-amber-300"}),s.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),s.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',sa||i.agent_notes,'"']})]})]}),Bn("gallery")&&kt.length>1&&s.jsxs("section",{id:"gallery",children:[s.jsxs("div",{className:"flex items-end justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),s.jsxs("button",{onClick:()=>Se(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",kt.length]})]}),s.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:kt.slice(0,7).map((un,xn)=>{const Qr=["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"],cs=xn===6&&kt.length>7;return s.jsxs("button",{onClick:()=>Se(xn),className:`${Qr[xn]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[s.jsx("img",{src:un.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"}),cs&&s.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[s.jsx(cne,{className:"h-6 w-6 mb-1"}),s.jsxs("span",{className:"font-medium",children:["+",kt.length-7," more"]})]})]},un.id)})})]}),Bn("video")&&!((oi=i.video)!=null&&oi.playback_url)&&tt&&s.jsxs("section",{id:"video",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:tt,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),Bn("video")&&((ia=i.video)==null?void 0:ia.playback_url)&&s.jsxs("section",{id:"video",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:i.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),Bn("map")&&Kt&&s.jsxs("section",{id:"map",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),s.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[i.neighborhood?i.neighborhood:i.city,", ",i.state]}),s.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:s.jsx("iframe",{src:Kt,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),s.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[s.jsx(ii,{className:"h-4 w-4"}),i.property_address?`${i.property_address}, `:"",i.city,", ",i.state]})]}),Bn("payment")&&s.jsxs("section",{id:"payment",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[s.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[s.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",mk(Math.round(xt))]}),s.jsx("p",{className:"text-white/60",children:"/ month"})]}),s.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(Br,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),s.jsxs("span",{className:"text-white font-medium",children:[Ee,"%"]})]}),s.jsx(Km,{value:[Ee],onValueChange:un=>xe(un[0]),min:0,max:50,step:1}),s.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",mk(Math.round(i.price*Ee/100))," down"]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(Br,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),s.jsxs("span",{className:"text-white font-medium",children:[Ue.toFixed(2),"%"]})]}),s.jsx(Km,{value:[Ue],onValueChange:un=>Ze(un[0]),min:2,max:10,step:.125})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(Br,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),s.jsxs("span",{className:"text-white font-medium",children:[lt," yr"]})]}),s.jsx(Km,{value:[lt],onValueChange:un=>wt(un[0]),min:10,max:30,step:5})]})]}),s.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),Rs.map(un=>{const xn=un.type,Qr=un.data||{};if(xn==="extra_video"&&Qr.url){const cs=String(Qr.url).includes("youtu")?`https://www.youtube.com/embed/${String(Qr.url).split(/[/=]/).pop()}`:Qr.url;return s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Qr.eyebrow||"Featured Video"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Qr.title||"Watch"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:cs,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Qr.title||"Video"})})]},un.id)}return xn==="3d_tour"&&Qr.url?s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Qr.title||"Step inside"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:Qr.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},un.id):xn==="floor_plan"&&Qr.image_url?s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Qr.title||"Layout"}),s.jsx("img",{src:Qr.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},un.id):xn==="testimonial"&&Qr.quote?s.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[s.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',Qr.quote,'"']}),Qr.author&&s.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Qr.author]})]},un.id):xn==="custom_cta"&&Qr.label?s.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:gs?`${gs}22`:"rgba(255,255,255,0.05)",border:`1px solid ${gs||"rgba(255,255,255,0.1)"}`},children:[Qr.title&&s.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Qr.title}),s.jsx(Lt,{asChild:!0,size:"lg",style:gs?{background:gs}:void 0,children:s.jsx("a",{href:Qr.url||"#agent",children:Qr.label})})]},un.id):null})]}),s.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[s.jsx(wtt,{listingId:i.id}),i.agent&&s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[i.agent.avatar_url?s.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):s.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:s.jsx(Wl,{className:"h-7 w-7 text-white/70"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),s.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.agent.name}),qr&&s.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:qr})]})]}),s.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.agent.phone&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`tel:${i.agent.phone}`,children:[s.jsx(Fn,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.agent.email&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`mailto:${i.agent.email}`,children:[s.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),i.co_agent_name&&s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[i.co_agent_photo_url?s.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):s.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:s.jsx(Wl,{className:"h-7 w-7 text-white/70"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),s.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&s.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:i.co_agent_brokerage})]})]}),(i.co_agent_phone||i.co_agent_email)&&s.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.co_agent_phone&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`tel:${i.co_agent_phone}`,children:[s.jsx(Fn,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.co_agent_email&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`mailto:${i.co_agent_email}`,children:[s.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),s.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:s.jsx(Pie,{submitted:ye,activeTab:Q,setActiveTab:ee,firstName:m,setFirstName:y,lastName:v,setLastName:w,email:j,setEmail:A,phone:C,setPhone:I,message:M,setMessage:D,preferredDate:F,setPreferredDate:z,preferredTime:q,setPreferredTime:H,showingMode:K,setShowingMode:J,isSubmitting:oe,onSubmit:Tr})})]})]}),s.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((Xr=i.agent)==null?void 0:Xr.phone)&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:s.jsxs("a",{href:`tel:${i.agent.phone}`,children:[s.jsx(Fn,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),s.jsxs(Lt,{onClick:()=>me(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[s.jsx(NH,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),s.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-white/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("img",{src:Cie,alt:"LevelUp",className:"h-6 opacity-80"}),s.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),s.jsx(Wa,{open:Le!==null,onOpenChange:()=>Se(null),children:s.jsxs(La,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[s.jsx(Ko,{className:"sr-only",children:s.jsx(Po,{children:"Photo Gallery"})}),s.jsx("button",{onClick:()=>Se(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:s.jsx(Ci,{className:"h-5 w-5"})}),Le!==null&&kt[Le]&&s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:kt[Le].photo_url,alt:`Photo ${Le+1}`,className:"w-full max-h-[85vh] object-contain"}),kt.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:rn,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:s.jsx(lp,{className:"h-6 w-6"})}),s.jsx("button",{onClick:Lr,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:s.jsx(Wd,{className:"h-6 w-6"})}),s.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[Le+1," / ",kt.length]})]})]})]})}),s.jsx(Wa,{open:ve,onOpenChange:me,children:s.jsxs(La,{className:"max-w-md p-0 bg-white text-neutral-900",children:[s.jsx(Ko,{className:"sr-only",children:s.jsx(Po,{children:"Contact the agent"})}),s.jsx("div",{className:"p-6",children:s.jsx(Pie,{submitted:ye,activeTab:Q,setActiveTab:ee,firstName:m,setFirstName:y,lastName:v,setLastName:w,email:j,setEmail:A,phone:C,setPhone:I,message:M,setMessage:D,preferredDate:F,setPreferredDate:z,preferredTime:q,setPreferredTime:H,showingMode:K,setShowingMode:J,isSubmitting:oe,onSubmit:Tr})})]})})]})]})}function Pie(t){const{submitted:e,activeTab:r,setActiveTab:n,firstName:i,setFirstName:o,lastName:c,setLastName:a,email:f,setEmail:m,phone:y,setPhone:v,message:w,setMessage:j,preferredDate:A,setPreferredDate:C,preferredTime:I,setPreferredTime:M,showingMode:D,setShowingMode:F,isSubmitting:z,onSubmit:q}=t;return e?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:s.jsx(pa,{className:"h-7 w-7 text-emerald-600"})}),s.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:r==="showing"?"Showing request sent!":"Thanks — you're all set!"}),s.jsx("p",{className:"text-sm text-neutral-600",children:r==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-4",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),s.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),s.jsxs(vF,{value:r,onValueChange:H=>n(H),children:[s.jsxs(JC,{className:"grid w-full grid-cols-2 mb-4",children:[s.jsxs(Of,{value:"info",className:"gap-1.5",children:[s.jsx(Ph,{className:"h-3.5 w-3.5"})," Get Info"]}),s.jsxs(Of,{value:"showing",className:"gap-1.5",children:[s.jsx(NH,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),s.jsxs("form",{onSubmit:q,className:"space-y-3",children:[s.jsxs(Bx,{value:"showing",className:"mt-0 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"preferredDate",children:"Preferred Date *"}),s.jsx(Or,{id:"preferredDate",type:"date",value:A,onChange:H=>C(H.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"preferredTime",children:"Preferred Time"}),s.jsxs(Pa,{value:I,onValueChange:M,children:[s.jsx(va,{id:"preferredTime",children:s.jsx(Ra,{placeholder:"Any time"})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"morning",children:"Morning (9am–12pm)"}),s.jsx(gn,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),s.jsx(gn,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"showingMode",children:"Tour Type"}),s.jsxs(Pa,{value:D,onValueChange:H=>F(H),children:[s.jsx(va,{id:"showingMode",children:s.jsx(Ra,{})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"in_person",children:"🏡 In-person showing"}),s.jsx(gn,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),s.jsx(gn,{value:"either",children:"Either works for me"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"firstName",children:"First Name *"}),s.jsx(Or,{id:"firstName",value:i,onChange:H=>o(H.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lastName",children:"Last Name"}),s.jsx(Or,{id:"lastName",value:c,onChange:H=>a(H.target.value)})]})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"email",children:"Email *"}),s.jsx(Or,{id:"email",type:"email",value:f,onChange:H=>m(H.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsxs(Br,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),s.jsx(Or,{id:"phone",type:"tel",value:y,onChange:H=>v(H.target.value),required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),s.jsx(qc,{id:"message",value:w,onChange:H=>j(H.target.value),rows:2})]}),s.jsx(Lt,{type:"submit",disabled:z,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:z?"Sending…":r==="showing"?"Request Showing":"Get More Info"}),s.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const Ltt=Object.freeze(Object.defineProperty({__proto__:null,default:kK,toVideoEmbedUrl:sSe},Symbol.toStringTag,{value:"Module"})),Rie="/assets/levelup-logo-white-C2RAgAoG.png",Mtt="/assets/listings-hero-noir-BHCJrhvU.jpg";var iSe={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(fc,function(){let r,n,i;function o(a,f){if(!r)r=f;else if(!n)n=f;else{const m={};r(m),i=f(m);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(a){var f=1e-6,m=typeof Float32Array<"u"?Float32Array:Array;function y(h,l){var u=l[0],p=l[1],x=l[2],b=l[3],T=u*b-x*p;return T?(h[0]=b*(T=1/T),h[1]=-p*T,h[2]=-x*T,h[3]=u*T,h):null}function v(){var h=new m(9);return m!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[5]=0,h[6]=0,h[7]=0),h[0]=1,h[4]=1,h[8]=1,h}function w(h,l){var u=l[0],p=l[1],x=l[2],b=l[3],T=l[4],k=l[5],P=l[6],O=l[7],$=l[8];return h[0]=T*$-k*O,h[1]=x*O-p*$,h[2]=p*k-x*T,h[3]=k*P-b*$,h[4]=u*$-x*P,h[5]=x*b-u*k,h[6]=b*O-T*P,h[7]=p*P-u*O,h[8]=u*T-p*b,h}function j(h,l,u){var p=l[0],x=l[1],b=l[2],T=l[3],k=l[4],P=l[5],O=l[6],$=l[7],V=l[8],G=u[0],Y=u[1],X=u[2],te=u[3],se=u[4],ae=u[5],fe=u[6],ue=u[7],Te=u[8];return h[0]=G*p+Y*T+X*O,h[1]=G*x+Y*k+X*$,h[2]=G*b+Y*P+X*V,h[3]=te*p+se*T+ae*O,h[4]=te*x+se*k+ae*$,h[5]=te*b+se*P+ae*V,h[6]=fe*p+ue*T+Te*O,h[7]=fe*x+ue*k+Te*$,h[8]=fe*b+ue*P+Te*V,h}function A(){var h=new m(16);return m!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=0,h[12]=0,h[13]=0,h[14]=0),h[0]=1,h[5]=1,h[10]=1,h[15]=1,h}function C(h){var l=new m(16);return l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],l[4]=h[4],l[5]=h[5],l[6]=h[6],l[7]=h[7],l[8]=h[8],l[9]=h[9],l[10]=h[10],l[11]=h[11],l[12]=h[12],l[13]=h[13],l[14]=h[14],l[15]=h[15],l}function I(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 M(h,l){var u=l[0],p=l[1],x=l[2],b=l[3],T=l[4],k=l[5],P=l[6],O=l[7],$=l[8],V=l[9],G=l[10],Y=l[11],X=l[12],te=l[13],se=l[14],ae=l[15],fe=u*k-p*T,ue=u*P-x*T,Te=u*O-b*T,Ae=p*P-x*k,Ie=p*O-b*k,We=x*O-b*P,ze=$*te-V*X,He=$*se-G*X,Ve=$*ae-Y*X,qe=V*se-G*te,bt=V*ae-Y*te,Et=G*ae-Y*se,It=fe*Et-ue*bt+Te*qe+Ae*Ve-Ie*He+We*ze;return It?(h[0]=(k*Et-P*bt+O*qe)*(It=1/It),h[1]=(x*bt-p*Et-b*qe)*It,h[2]=(te*We-se*Ie+ae*Ae)*It,h[3]=(G*Ie-V*We-Y*Ae)*It,h[4]=(P*Ve-T*Et-O*He)*It,h[5]=(u*Et-x*Ve+b*He)*It,h[6]=(se*Te-X*We-ae*ue)*It,h[7]=($*We-G*Te+Y*ue)*It,h[8]=(T*bt-k*Ve+O*ze)*It,h[9]=(p*Ve-u*bt-b*ze)*It,h[10]=(X*Ie-te*Te+ae*fe)*It,h[11]=(V*Te-$*Ie-Y*fe)*It,h[12]=(k*He-T*qe-P*ze)*It,h[13]=(u*qe-p*He+x*ze)*It,h[14]=(te*ue-X*Ae-se*fe)*It,h[15]=($*Ae-V*ue+G*fe)*It,h):null}function D(h,l,u){var p=l[0],x=l[1],b=l[2],T=l[3],k=l[4],P=l[5],O=l[6],$=l[7],V=l[8],G=l[9],Y=l[10],X=l[11],te=l[12],se=l[13],ae=l[14],fe=l[15],ue=u[0],Te=u[1],Ae=u[2],Ie=u[3];return h[0]=ue*p+Te*k+Ae*V+Ie*te,h[1]=ue*x+Te*P+Ae*G+Ie*se,h[2]=ue*b+Te*O+Ae*Y+Ie*ae,h[3]=ue*T+Te*$+Ae*X+Ie*fe,h[4]=(ue=u[4])*p+(Te=u[5])*k+(Ae=u[6])*V+(Ie=u[7])*te,h[5]=ue*x+Te*P+Ae*G+Ie*se,h[6]=ue*b+Te*O+Ae*Y+Ie*ae,h[7]=ue*T+Te*$+Ae*X+Ie*fe,h[8]=(ue=u[8])*p+(Te=u[9])*k+(Ae=u[10])*V+(Ie=u[11])*te,h[9]=ue*x+Te*P+Ae*G+Ie*se,h[10]=ue*b+Te*O+Ae*Y+Ie*ae,h[11]=ue*T+Te*$+Ae*X+Ie*fe,h[12]=(ue=u[12])*p+(Te=u[13])*k+(Ae=u[14])*V+(Ie=u[15])*te,h[13]=ue*x+Te*P+Ae*G+Ie*se,h[14]=ue*b+Te*O+Ae*Y+Ie*ae,h[15]=ue*T+Te*$+Ae*X+Ie*fe,h}function F(h,l,u){var p,x,b,T,k,P,O,$,V,G,Y,X,te=u[0],se=u[1],ae=u[2];return l===h?(h[12]=l[0]*te+l[4]*se+l[8]*ae+l[12],h[13]=l[1]*te+l[5]*se+l[9]*ae+l[13],h[14]=l[2]*te+l[6]*se+l[10]*ae+l[14],h[15]=l[3]*te+l[7]*se+l[11]*ae+l[15]):(x=l[1],b=l[2],T=l[3],k=l[4],P=l[5],O=l[6],$=l[7],V=l[8],G=l[9],Y=l[10],X=l[11],h[0]=p=l[0],h[1]=x,h[2]=b,h[3]=T,h[4]=k,h[5]=P,h[6]=O,h[7]=$,h[8]=V,h[9]=G,h[10]=Y,h[11]=X,h[12]=p*te+k*se+V*ae+l[12],h[13]=x*te+P*se+G*ae+l[13],h[14]=b*te+O*se+Y*ae+l[14],h[15]=T*te+$*se+X*ae+l[15]),h}function z(h,l,u){var p=u[0],x=u[1],b=u[2];return h[0]=l[0]*p,h[1]=l[1]*p,h[2]=l[2]*p,h[3]=l[3]*p,h[4]=l[4]*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 q(h,l,u){var p=Math.sin(u),x=Math.cos(u),b=l[4],T=l[5],k=l[6],P=l[7],O=l[8],$=l[9],V=l[10],G=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*p,h[5]=T*x+$*p,h[6]=k*x+V*p,h[7]=P*x+G*p,h[8]=O*x-b*p,h[9]=$*x-T*p,h[10]=V*x-k*p,h[11]=G*x-P*p,h}function H(h,l,u){var p=Math.sin(u),x=Math.cos(u),b=l[0],T=l[1],k=l[2],P=l[3],O=l[8],$=l[9],V=l[10],G=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*p,h[1]=T*x-$*p,h[2]=k*x-V*p,h[3]=P*x-G*p,h[8]=b*p+O*x,h[9]=T*p+$*x,h[10]=k*p+V*x,h[11]=P*p+G*x,h}function K(h,l,u){var p=Math.sin(u),x=Math.cos(u),b=l[0],T=l[1],k=l[2],P=l[3],O=l[4],$=l[5],V=l[6],G=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*p,h[1]=T*x+$*p,h[2]=k*x+V*p,h[3]=P*x+G*p,h[4]=O*x-b*p,h[5]=$*x-T*p,h[6]=V*x-k*p,h[7]=G*x-P*p,h}function J(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 Q(h,l,u){var p,x,b,T=u[0],k=u[1],P=u[2],O=Math.sqrt(T*T+k*k+P*P);return O0&&(b=1/Math.sqrt(b)),h[0]=l[0]*b,h[1]=l[1]*b,h[2]=l[2]*b,h}function kt(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]}function Vt(h,l,u){var p=l[0],x=l[1],b=l[2],T=u[0],k=u[1],P=u[2];return h[0]=x*P-b*k,h[1]=b*T-p*P,h[2]=p*k-x*T,h}function xt(h,l,u,p){var x=l[0],b=l[1],T=l[2];return h[0]=x+p*(u[0]-x),h[1]=b+p*(u[1]-b),h[2]=T+p*(u[2]-T),h}function or(h,l,u){var p=l[0],x=l[1],b=l[2],T=u[3]*p+u[7]*x+u[11]*b+u[15];return h[0]=(u[0]*p+u[4]*x+u[8]*b+u[12])/(T=T||1),h[1]=(u[1]*p+u[5]*x+u[9]*b+u[13])/T,h[2]=(u[2]*p+u[6]*x+u[10]*b+u[14])/T,h}function Tr(h,l,u){var p=l[0],x=l[1],b=l[2];return h[0]=p*u[0]+x*u[3]+b*u[6],h[1]=p*u[1]+x*u[4]+b*u[7],h[2]=p*u[2]+x*u[5]+b*u[8],h}function rn(h,l,u){var p=u[0],x=u[1],b=u[2],T=u[3],k=l[0],P=l[1],O=l[2],$=x*O-b*P,V=b*k-p*O,G=p*P-x*k;return h[0]=k+T*($+=$)+x*(G+=G)-b*(V+=V),h[1]=P+T*V+b*$-p*G,h[2]=O+T*G+p*V-x*$,h}function Lr(h){return h[0]=0,h[1]=0,h[2]=0,h}function $r(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]}var qr=ke,Nn=Pe,tt=Le;function Tt(){var h=new m(4);return m!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function Zt(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 ar(h,l){var u=l[0],p=l[1],x=l[2],b=l[3],T=u*u+p*p+x*x+b*b;return T>0&&(T=1/Math.sqrt(T)),h[0]=u*T,h[1]=p*T,h[2]=x*T,h[3]=b*T,h}function Wt(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]+h[3]*l[3]}function Kt(h,l,u){var p=l[0],x=l[1],b=l[2],T=l[3];return h[0]=u[0]*p+u[4]*x+u[8]*b+u[12]*T,h[1]=u[1]*p+u[5]*x+u[9]*b+u[13]*T,h[2]=u[2]*p+u[6]*x+u[10]*b+u[14]*T,h[3]=u[3]*p+u[7]*x+u[11]*b+u[15]*T,h}function At(){var h=new m(4);return m!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h[3]=1,h}function pr(h){return h[0]=0,h[1]=0,h[2]=0,h[3]=1,h}function yn(h,l,u){u*=.5;var p=l[0],x=l[1],b=l[2],T=l[3],k=Math.sin(u),P=Math.cos(u);return h[0]=p*P+T*k,h[1]=x*P+b*k,h[2]=b*P-x*k,h[3]=T*P-p*k,h}function Gn(h,l,u){u*=.5;var p=l[0],x=l[1],b=l[2],T=l[3],k=Math.sin(u),P=Math.cos(u);return h[0]=p*P-b*k,h[1]=x*P+T*k,h[2]=b*P+p*k,h[3]=T*P-x*k,h}ye(),Tt();var Bn,Rs,sa,gs=ar,zi=(Bn=ye(),Rs=Se(1,0,0),sa=Se(0,1,0),function(h,l,u){var p=kt(l,u);return p<-.999999?(Vt(Bn,Rs,l),tt(Bn)<1e-6&&Vt(Bn,sa,l),ft(Bn,Bn),function(x,b,T){T*=.5;var k=Math.sin(T);x[0]=k*b[0],x[1]=k*b[1],x[2]=k*b[2],x[3]=Math.cos(T)}(h,Bn,Math.PI),h):p>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(Vt(Bn,l,u),h[0]=Bn[0],h[1]=Bn[1],h[2]=Bn[2],h[3]=1+p,gs(h,h))});function Ir(){var h=new m(2);return m!=Float32Array&&(h[0]=0,h[1]=0),h}function $n(h,l){var u=new m(2);return u[0]=h,u[1]=l,u}function Si(h,l,u){return h[0]=l,h[1]=u,h}function oi(h,l,u){return h[0]=l[0]+u[0],h[1]=l[1]+u[1],h}function ia(h,l,u){return h[0]=l[0]-u[0],h[1]=l[1]-u[1],h}function Xr(h,l,u){return h[0]=l[0]*u,h[1]=l[1]*u,h}function un(h){var l=h[0],u=h[1];return Math.sqrt(l*l+u*u)}function xn(h,l){var u=l[0],p=l[1],x=u*u+p*p;return x>0&&(x=1/Math.sqrt(x)),h[0]=l[0]*x,h[1]=l[1]*x,h}function Qr(h,l){return h[0]*l[0]+h[1]*l[1]}At(),At(),v();var cs,nn,Ln=ia;function ri(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}Ir();var Yo=function(){if(nn)return cs;function h(l,u,p,x){this.cx=3*l,this.bx=3*(p-l)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*u,this.by=3*(x-u)-this.cy,this.ay=1-this.cy-this.by,this.p1x=l,this.p1y=u,this.p2x=p,this.p2y=x}return nn=1,cs=h,h.prototype={sampleCurveX:function(l){return((this.ax*l+this.bx)*l+this.cx)*l},sampleCurveY:function(l){return((this.ay*l+this.by)*l+this.cy)*l},sampleCurveDerivativeX:function(l){return(3*this.ax*l+2*this.bx)*l+this.cx},solveCurveX:function(l,u){if(u===void 0&&(u=1e-6),l<0)return 0;if(l>1)return 1;for(var p=l,x=0;x<8;x++){var b=this.sampleCurveX(p)-l;if(Math.abs(b)b?k=p:P=p,p=.5*(P-k)+k;return p},solve:function(l,u){return this.sampleCurveY(this.solveCurveX(l,u))}},cs}(),Us=ri(Yo);function Ft(h,l){this.x=h,this.y=l}function jo(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 dt(h,l,u,p){const x=new Us(h,l,u,p);return function(b){return x.solve(b)}}const he=dt(.25,.1,.25,1);function pe(h,l,u){return Math.min(u,Math.max(l,h))}function Fe(h,l,u){return(u=pe((u-h)/(l-h),0,1))*u*(3-2*u)}function Ye(h,l,u){const p=u-l,x=((h-l)%p+p)%p+l;return x===l?u:x}function et(h,l,u){if(!h.length)return u(null,[]);let p=h.length;const x=new Array(h.length);let b=null;h.forEach((T,k)=>{l(T,(P,O)=>{P&&(b=P),x[k]=O,--p===0&&u(b,x)})})}let nt=1;function ht(){return nt++}function it(h){return h<=1?1:Math.pow(2,Math.ceil(Math.log2(h)))}function mt(h,l){h.forEach(u=>{l[u]&&(l[u]=l[u].bind(l))})}function Gt(h,l,u){const p={};for(const x in h)p[x]=l.call(this,h[x],x,h);return p}function Mt(h,l,u){const p={};for(const x in h)l.call(this,h[x],x,h)&&(p[x]=h[x]);return p}function gr(h){return Array.isArray(h)?h.map(gr):typeof h=="object"&&h?Gt(h,gr):h}function zr(h,l){for(let u=0;u=0)return!0;return!1}const Hr={};function hr(h){Hr[h]||(typeof console<"u"&&console.warn(h),Hr[h]=!0)}function rt(h,l,u){return(u.y-h.y)*(l.x-h.x)>(l.y-h.y)*(u.x-h.x)}function qt(h){let l=0;for(let u,p,x=0,b=h.length,T=b-1;x@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(u,p,x,b)=>{const T=x||b;return l[p]=!T||T.toLowerCase(),""}),l["max-age"]){const u=parseInt(l["max-age"],10);isNaN(u)?delete l["max-age"]:l["max-age"]=u}return l}let Qn,Ns=null;function Jn(h,l){return[h[4*l],h[4*l+1],h[4*l+2],h[4*l+3]]}function ks(h,l,u,p){for(;l>1;h[x]>1;h[x]<=p?l=x+1:u=x}return l}function Un(h){return h>0?1/(1.001-h):1+h}function ni(h){return h>0?1-1/(1.001-h):-h}function hi(h,l,u){return(h-l.min)*(u.max-u.min)/(l.max-l.min)+u.min}const Vn={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(!Vn.API_URL)return null;try{const h=new URL(Vn.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 Oa(){return new URL(Vn.DRACO_URL,Vn.API_URL).href}function Lo(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Qn===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]);Qn=WebAssembly.validate(h)}return Qn}()?Vn.MESHOPT_SIMD_URL:Vn.MESHOPT_URL,Vn.API_URL).href}function Eo(){return new URL(Vn.BUILDING_GEN_URL,Vn.API_URL).href}function bc(h){return Vn.API_URL_REGEX.test(h)}function wc(h){return Vn.API_SPRITE_REGEX.test(h)}let Kd,Ll,Sc,Yd,Hc,Zd;function Iu(){return Kd==null&&(Kd=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Kd}const Zl={now:()=>Yd!==void 0?Yd:performance.now(),setNow(h){Yd=h},restoreNow(){Yd=void 0},frame(h){const l=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(l)}},getImageData(h,l=0){const{width:u,height:p}=h;Hc||(Hc=document.createElement("canvas"));const x=Hc.getContext("2d",{willReadFrequently:!0});if(!x)throw new Error("failed to create canvas 2d context");return(u>Hc.width||p>Hc.height)&&(Hc.width=u,Hc.height=p),x.clearRect(-l,-l,u+2*l,p+2*l),x.drawImage(h,0,0,u,p),x.getImageData(-l,-l,u+2*l,p+2*l)},resolveURL:h=>(Ll||(Ll=document.createElement("a")),Ll.href=h,Ll.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Sc==null&&(Sc=window.matchMedia("(prefers-reduced-motion: reduce)")),Sc.matches)},hasCanvasFingerprintNoise(){if(Zd!==void 0)return Zd;if(!Iu())return Zd=!1,!1;const h=new OffscreenCanvas(85,1),l=h.getContext("2d",{willReadFrequently:!0});let u=0;for(let x=0;x0?`?${b}`:""}`}const yp="mapbox-tiles";let jb=500,Eb=50;const Bj=["language","worldview","jobid"];let Xd;function TI(){try{return caches}catch{}}function kb(){const h=TI();h&&Xd==null&&(Xd=h.open(yp))}let $j=1/0;const Ab={supported:!1,testSupport:function(h){!zj&&Xg&&(Pu?Qg(h):xp=h)}};let xp,Xg,zj=!1,Pu=!1;const Uj=typeof self<"u"?self:{};function Qg(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,Xg),h.isContextLost())return;Ab.supported=!0}catch{}h.deleteTexture(l),zj=!0}Uj.document&&(Xg=Uj.document.createElement("img"),Xg.onload=function(){xp&&Qg(xp),xp=null,Pu=!0},Xg.onerror=function(){zj=!0,xp=null},Xg.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const D0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(D0);class Vj extends Error{constructor(l,u,p){u===401&&bc(p)&&(l+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(l),this.status=u,this.url=p}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function qj(h){return typeof h=="object"&&h!==null&&"status"in h&&h.status===404}const us=wn()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Jg=function(h,l){return/^file:/.test(u=h.url)||/^file:/.test(us())&&!/^\w+:/.test(u)?function(p,x){const b=new XMLHttpRequest;b.open(p.method||"GET",p.url,!0),p.type==="arrayBuffer"&&(b.responseType="arraybuffer");for(const T in p.headers)b.setRequestHeader(T,p.headers[T]);return p.type==="json"&&(b.responseType="text",b.setRequestHeader("Accept","application/json")),b.withCredentials=p.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 T=b.response;if(p.type==="json")try{T=JSON.parse(b.response)}catch(P){return x(P)}const k=new Headers;b.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(P=>{const O=P.split(": "),$=O.shift(),V=O.join(": ");k.append($,V)}),x(null,T,k)}else x(new Vj(b.statusText,b.status,p.url))},b.send(p.body),{cancel:()=>b.abort()}}(h,l):function(p,x){const b=new AbortController,T=new Request(p.url,{method:p.method||"GET",body:p.body,credentials:p.credentials,headers:p.headers,referrer:us(),referrerPolicy:p.referrerPolicy,signal:b.signal});let k=!1,P=!1;const O=($=T.url).indexOf("sku=")>0&&bc($);var $;p.type==="json"&&T.headers.set("Accept","application/json");const V=(Y,X,te)=>{if(P)return;if(Y&&Y.message!=="SecurityError"&&hr(Y.toString()),X&&te)return G(X);const se=Date.now();fetch(T).then(ae=>{if(ae.ok){const fe=O?ae.clone():null;return G(ae,fe,se)}return x(new Vj(ae.statusText,ae.status,p.url))}).catch(ae=>{ae.name!=="AbortError"&&x(new Error(`${ae.message} ${p.url}`))})},G=(Y,X,te)=>{(p.type==="arrayBuffer"?Y.arrayBuffer():p.type==="json"?Y.json():Y.text()).then(se=>{P||(X&&te&&function(ae,fe,ue){if(kb(),Xd==null)return;const Te=Cn(fe.headers.get("cache-control")||"");if(Te["no-store"])return;const Ae={status:fe.status,statusText:fe.statusText,headers:new Headers};fe.headers.forEach((Ve,qe)=>Ae.headers.set(qe,Ve)),Te["max-age"]&&Ae.headers.set("Expires",new Date(ue+1e3*Te["max-age"]).toUTCString());const Ie=Ae.headers.get("expires");if(!Ie||new Date(Ie).getTime()-ue<42e4)return;let We=Fj(ae.url,{persistentParams:Bj});if(fe.status===206){const Ve=ae.headers.get("Range");if(!Ve)return;Ae.status=200,We=M0(We,{range:Ve})}const ze=new Response((He=fe.status)!==200&&He!==404&&[101,103,204,205,304].includes(He)?null:fe.body,Ae);var He;kb(),Xd!=null&&Xd.then(Ve=>Ve.put(We,ze)).catch(Ve=>hr(Ve.message))}(T,X,te),k=!0,x(null,se,Y.headers))}).catch(se=>{P||x(new Error(se.message))})};return O?function(Y,X){if(kb(),Xd==null)return X(null);Xd.then(te=>{let se=Fj(Y.url,{persistentParams:Bj});const ae=Y.headers.get("Range");ae&&(se=M0(se,{range:ae})),te.match(se).then(fe=>{const ue=function(Te){if(!Te)return!1;const Ae=new Date(Te.headers.get("expires")||0),Ie=Cn(Te.headers.get("cache-control")||"");return Number(Ae)>Date.now()&&!Ie["no-cache"]}(fe);te.delete(se).catch(X),ue&&te.put(se,fe.clone()).catch(X),X(null,fe,ue)}).catch(X)}).catch(X)}(T,V):V(null,null),{cancel:()=>{P=!0,k||b.abort()}}}(h,l);var u},ey=function(h,l){return Jg(Object.assign(h,{type:"arrayBuffer"}),l)};function nB(h){const l=document.createElement("a");return l.href=h,l.protocol===location.protocol&&l.host===location.host}let Nb,Wf;Nb=[],Wf=0;const ty=function(h,l){if(Ab.supported&&(h.headers||(h.headers={}),h.headers.accept="image/webp,*/*"),Wf>=Vn.MAX_PARALLEL_IMAGE_REQUESTS){const b={requestParameters:h,callback:l,cancelled:!1,cancel(){this.cancelled=!0}};return Nb.push(b),b}Wf++;let u=!1;const p=()=>{if(!u)for(u=!0,Wf--;Nb.length&&Wf{p(),b?l(b):T&&function(P,O){const $=new Blob([new Uint8Array(P)],{type:"image/png"});createImageBitmap($).then(V=>{O(null,V)}).catch(V=>{O(new Error(`Could not load image because of ${V.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(T,(P,O)=>l(P,O,k))});return{cancel:()=>{x.cancel(),p()}}};var O0,Cb,jI,vp={exports:{}},EI={exports:{}},Gj={exports:{}},sB=function(){if(jI)return vp.exports;jI=1;var h=(O0||(O0=1,EI.exports=function(u,p){var x,b,T,k,P,O,$,V;for(b=u.length-(x=3&u.length),T=p,P=3432918353,O=461845907,V=0;V>>16)*P&65535)<<16)&4294967295)<<15|$>>>17))*O+((($>>>16)*O&65535)<<16)&4294967295)<<13|T>>>19))+((5*(T>>>16)&65535)<<16)&4294967295))+(((k>>>16)+58964&65535)<<16);switch($=0,x){case 3:$^=(255&u.charCodeAt(V+2))<<16;case 2:$^=(255&u.charCodeAt(V+1))<<8;case 1:T^=$=(65535&($=($=(65535&($^=255&u.charCodeAt(V)))*P+((($>>>16)*P&65535)<<16)&4294967295)<<15|$>>>17))*O+((($>>>16)*O&65535)<<16)&4294967295}return T^=u.length,T=2246822507*(65535&(T^=T>>>16))+((2246822507*(T>>>16)&65535)<<16)&4294967295,T=3266489909*(65535&(T^=T>>>13))+((3266489909*(T>>>16)&65535)<<16)&4294967295,(T^=T>>>16)>>>0}),EI.exports),l=(Cb||(Cb=1,Gj.exports=function(u,p){for(var x,b=u.length,T=p^b,k=0;b>=4;)x=1540483477*(65535&(x=255&u.charCodeAt(k)|(255&u.charCodeAt(++k))<<8|(255&u.charCodeAt(++k))<<16|(255&u.charCodeAt(++k))<<24))+((1540483477*(x>>>16)&65535)<<16),T=1540483477*(65535&T)+((1540483477*(T>>>16)&65535)<<16)^(x=1540483477*(65535&(x^=x>>>24))+((1540483477*(x>>>16)&65535)<<16)),b-=4,++k;switch(b){case 3:T^=(255&u.charCodeAt(k+2))<<16;case 2:T^=(255&u.charCodeAt(k+1))<<8;case 1:T=1540483477*(65535&(T^=255&u.charCodeAt(k)))+((1540483477*(T>>>16)&65535)<<16)}return T=1540483477*(65535&(T^=T>>>13))+((1540483477*(T>>>16)&65535)<<16),(T^=T>>>15)>>>0}),Gj.exports);return vp.exports=h,vp.exports.murmur3=h,vp.exports.murmur2=l,vp.exports}(),Kf=ri(sB);class ud{constructor(l,...u){Object.assign(this,u[0]||{}),this.type=l}}class ry extends ud{constructor(l,u={}){super("error",Object.assign({error:l},u))}}function Ru(h,l,u){u[h]&&u[h].indexOf(l)!==-1||(u[h]=u[h]||[],u[h].push(l))}function Ib(h,l,u){if(u&&u[h]){const p=u[h].indexOf(l);p!==-1&&u[h].splice(p,1)}}class F0{on(l,u){return this._listeners=this._listeners||{},Ru(l,u,this._listeners),this}off(l,u){return Ib(l,u,this._listeners),Ib(l,u,this._oneTimeListeners),this}once(l,u){return u?(this._oneTimeListeners=this._oneTimeListeners||{},Ru(l,u,this._oneTimeListeners),this):new Promise(p=>{this.once(l,p)})}fire(l,u){const p=typeof l=="string"?new ud(l,u):l,x=p.type;if(this.listens(x)){p.target=this;const b=this._listeners&&this._listeners[x]?this._listeners[x].slice():[];for(const P of b)P.call(this,p);const T=this._oneTimeListeners&&this._oneTimeListeners[x]?this._oneTimeListeners[x].slice():[];for(const P of T)Ib(x,P,this._oneTimeListeners),P.call(this,p);const k=this._eventedParent;if(k){const P=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(p,P),k.fire(p)}}else p instanceof ry&&console.error(p.error);return this}listens(l){return!!(this._listeners&&this._listeners[l]&&this._listeners[l].length>0||this._oneTimeListeners&&this._oneTimeListeners[l]&&this._oneTimeListeners[l].length>0||this._eventedParent&&this._eventedParent.listens(l))}setEventedParent(l,u){return this._eventedParent=l,this._eventedParentData=u,this}}class Tc{constructor(l){typeof l=="string"?this.name=l:(this.name=l.name,this.iconsetId=l.iconsetId)}static from(l){return new Tc(l)}static toString(l){return l.iconsetId?`${l.name}${l.iconsetId}`:l.name}static parse(l){const[u,p]=l.split("");return new Tc({name:u,iconsetId:p})}static isEqual(l,u){return l.name===u.name&&l.iconsetId===u.iconsetId}toString(){return Tc.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var Hj,Pb={},Wj=function(){if(Hj)return Pb;Hj=1;var h={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function l(b){return(b=Math.round(b))<0?0:b>255?255:b}function u(b){return l(b[b.length-1]==="%"?parseFloat(b)/100*255:parseInt(b))}function p(b){return(T=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:T>1?1:T;var T}function x(b,T,k){return k<0?k+=1:k>1&&(k-=1),6*k<1?b+(T-b)*k*6:2*k<1?T:3*k<2?b+(T-b)*(2/3-k)*6:b}try{Pb.parseCSSColor=function(b){var T,k=b.replace(/ /g,"").toLowerCase();if(k in h)return h[k].slice();if(k[0]==="#")return k.length===4?(T=parseInt(k.substr(1),16))>=0&&T<=4095?[(3840&T)>>4|(3840&T)>>8,240&T|(240&T)>>4,15&T|(15&T)<<4,1]:null:k.length===7&&(T=parseInt(k.substr(1),16))>=0&&T<=16777215?[(16711680&T)>>16,(65280&T)>>8,255&T,1]:null;var P=k.indexOf("("),O=k.indexOf(")");if(P!==-1&&O+1===k.length){var $=k.substr(0,P),V=k.substr(P+1,O-(P+1)).split(","),G=1;switch($){case"rgba":if(V.length!==4)return null;G=p(V.pop());case"rgb":return V.length!==3?null:[u(V[0]),u(V[1]),u(V[2]),G];case"hsla":if(V.length!==4)return null;G=p(V.pop());case"hsl":if(V.length!==3)return null;var Y=(parseFloat(V[0])%360+360)%360/360,X=p(V[1]),te=p(V[2]),se=te<=.5?te*(X+1):te+X-te*X,ae=2*te-se;return[l(255*x(ae,se,Y+1/3)),l(255*x(ae,se,Y)),l(255*x(ae,se,Y-1/3)),G];default:return null}}return null}}catch{}return Pb}();class as{constructor(l,u,p,x=1){this.r=l,this.g=u,this.b=p,this.a=x}static parse(l){if(!l)return;if(l instanceof as)return l;if(typeof l!="string")return;const u=Wj.parseCSSColor(l);return u?new as(u[0]/255,u[1]/255,u[2]/255,u[3]):void 0}toString(){const[l,u,p,x]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*l)},${Math.round(255*u)},${Math.round(255*p)},${x})`}toNonPremultipliedRenderColor(l){const{r:u,g:p,b:x,a:b}=this;return new Rb(l,u,p,x,b)}toPremultipliedRenderColor(l){const{r:u,g:p,b:x,a:b}=this;return new ny(l,u*b,p*b,x*b,b)}clone(){return new as(this.r,this.g,this.b,this.a)}}class Kj{constructor(l,u,p,x,b,T=!1){if(this.premultiplied=!1,this.premultiplied=T,l){const k=l.image.height,P=k*k;this.premultiplied?(u=b===0?0:u/b*(k-1),p=b===0?0:p/b*(k-1),x=b===0?0:x/b*(k-1)):(u*=k-1,p*=k-1,x*=k-1),u=Math.max(0,Math.min(k-1,u)),p=Math.max(0,Math.min(k-1,p)),x=Math.max(0,Math.min(k-1,x));const O=Math.floor(u),$=Math.floor(p),V=Math.floor(x),G=Math.ceil(u),Y=Math.ceil(p),X=Math.ceil(x),te=u-O,se=p-$,ae=x-V,fe=l.image.data,ue=4*(O+$*P+V*k),Te=4*(O+$*P+X*k),Ae=4*(O+Y*P+V*k),Ie=4*(O+Y*P+X*k),We=4*(G+$*P+V*k),ze=4*(G+$*P+X*k),He=4*(G+Y*P+V*k),Ve=4*(G+Y*P+X*k);this.r=sn(sn(sn(fe[ue],fe[Te],ae),sn(fe[Ae],fe[Ie],ae),se),sn(sn(fe[We],fe[ze],ae),sn(fe[He],fe[Ve],ae),se),te)/255*(this.premultiplied?b:1),this.g=sn(sn(sn(fe[ue+1],fe[Te+1],ae),sn(fe[Ae+1],fe[Ie+1],ae),se),sn(sn(fe[We+1],fe[ze+1],ae),sn(fe[He+1],fe[Ve+1],ae),se),te)/255*(this.premultiplied?b:1),this.b=sn(sn(sn(fe[ue+2],fe[Te+2],ae),sn(fe[Ae+2],fe[Ie+2],ae),se),sn(sn(fe[We+2],fe[ze+2],ae),sn(fe[He+2],fe[Ve+2],ae),se),te)/255*(this.premultiplied?b:1),this.a=b}else this.r=u,this.g=p,this.b=x,this.a=b}toArray(){const{r:l,g:u,b:p,a:x}=this;return[255*l,255*u,255*p,x]}toHslaArray(){let{r:l,g:u,b:p,a:x}=this;if(this.premultiplied){if(x===0)return[0,0,0,0];const X=1/x;l*=X,u*=X,p*=X}const b=Math.min(Math.max(l,0),1),T=Math.min(Math.max(u,0),1),k=Math.min(Math.max(p,0),1),P=Math.min(b,T,k),O=Math.max(b,T,k),$=O-P,V=.5*(P+O);if($===0)return[0,0,100*V,x];const G=V>.5?$/(2-O-P):$/(O+P);let Y;switch(O){case b:Y=60*((T-k)/$+(Tsn(p,l[x],u))}as.black=new as(0,0,0,1),as.white=new as(1,1,1,1),as.transparent=new as(0,0,0,0),as.red=new as(1,0,0,1),as.blue=new as(0,0,1,1);var Lb=Object.freeze({__proto__:null,array:dd,color:function(h,l,u){return new as(sn(h.r,l.r,u),sn(h.g,l.g,u),sn(h.b,l.b,u),sn(h.a,l.a,u))},number:sn});class Lu extends Error{constructor(l,u){super(u),this.message=u,this.key=l}}class _p{constructor(l,u=[]){this.parent=l,this.bindings={};for(const[p,x]of u)this.bindings[p]=x}concat(l){return new _p(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 zh={kind:"null"},Ur={kind:"number"},vs={kind:"string"},Ss={kind:"boolean"},Ml={kind:"color"},Yf={kind:"object"},Ts={kind:"value"},bp={kind:"collator"},B0={kind:"formatted"},$0={kind:"resolvedImage"};function fl(h,l){return{kind:"array",itemType:h,N:l}}function ba(h){if(h.kind==="array"){const l=ba(h.itemType);return typeof h.N=="number"?`array<${l}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${l}>`}return h.kind}const iB=[zh,Ur,vs,Ss,Ml,B0,Yf,fl(Ts),$0];function z0(h,l){if(l.kind==="error")return null;if(h.kind==="array"){if(l.kind==="array"&&(l.N===0&&l.itemType.kind==="value"||!z0(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 iB)if(!z0(u,l))return null}}return`Expected ${ba(h)} but found ${ba(l)} instead.`}function Yj(h,l){return l.some(u=>u.kind===h.kind)}function sy(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 Uh(h,l){return h.kind==="array"&&l.kind==="array"?h.N===l.N&&Uh(h.itemType,l.itemType):h.kind===l.kind}class Zj{constructor(l,u,p){this.sensitivity=l?u?"variant":"case":u?"accent":"base",this.locale=p,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(l,u){return this.collator.compare(l,u)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class U0{constructor(l,u,p,x,b){this.text=l.normalize?l.normalize():l,this.image=u,this.scale=p,this.fontStack=x,this.textColor=b}}class Zo{constructor(l){this.sections=l}static fromString(l){return new Zo([new U0(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 Zo?l:Zo.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 p={};u.fontStack&&(p["text-font"]=["literal",u.fontStack.split(",")]),u.scale&&(p["font-scale"]=u.scale),u.textColor&&(p["text-color"]=["rgba"].concat(u.textColor.toNonPremultipliedRenderColor(null).toArray())),l.push(p)}return l}}class Mu{constructor(l,u={}){this.id=Tc.from(l),this.params=u.params,this.sx=u.sx||1,this.sy=u.sy||1}toString(){return JSON.stringify(this)}static parse(l){let u,p,x,b;try{({id:u,params:p,sx:x,sy:b}=JSON.parse(l)||{})}catch{return null}return u?new Mu(u,{params:p,sx:x,sy:b}):null}scaleSelf(l,u=l){return this.sx*=l,this.sy*=u,this}}class Xl{constructor(l,u,p,x,b=!1){this.primaryId=Tc.from(l),this.primaryOptions=u,p&&(this.secondaryId=Tc.from(p)),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 Mu(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Mu(this.secondaryId,this.secondaryOptions):null}static from(l){return typeof l=="string"?Xl.build({name:l}):l}static build(l,u,p,x){return!l||typeof l=="object"&&!("name"in l)?null:new Xl(l,p,u,x)}}function kI(h,l,u,p){return typeof h=="number"&&h>=0&&h<=255&&typeof l=="number"&&l>=0&&l<=255&&typeof u=="number"&&u>=0&&u<=255?p===void 0||typeof p=="number"&&p>=0&&p<=1?null:`Invalid rgba value [${[h,l,u,p].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof p=="number"?[h,l,u,p]:[h,l,u]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function iy(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof as||h instanceof Zj||h instanceof Zo||h instanceof Xl)return!0;if(Array.isArray(h)){for(const l of h)if(!iy(l))return!1;return!0}if(typeof h=="object"){for(const l in h)if(!iy(h[l]))return!1;return!0}return!1}function Vi(h){if(h===null)return zh;if(typeof h=="string")return vs;if(typeof h=="boolean")return Ss;if(typeof h=="number")return Ur;if(h instanceof as)return Ml;if(h instanceof Zj)return bp;if(h instanceof Zo)return B0;if(h instanceof Xl)return $0;if(Array.isArray(h)){const l=h.length;let u;for(const p of h){const x=Vi(p);if(u){if(u===x)continue;u=Ts;break}u=x}return fl(u||Ts,l)}return Yf}function tn(h){const l=typeof h;return h===null?"":l==="string"||l==="number"||l==="boolean"?String(h):h instanceof Zo||h instanceof Xl||h instanceof as?h.toString():JSON.stringify(h)}class Mr{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(!iy(l[1]))return u.error("invalid value");const p=l[1];let x=Vi(p);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 Mr(x,p)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof as?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Zo?this.value.serialize():this.value}}class da{constructor(l){this.name="ExpressionEvaluationError",this.message=l}toJSON(){return this.message}}const an={string:vs,number:Ur,boolean:Ss,object:Yf};class Wc{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");let p,x=1;const b=l[0];if(b==="array"){let k,P;if(l.length>2){const O=l[1];if(typeof O!="string"||!(O in an)||O==="object")return u.error('The item type argument of "array" must be one of string, number, boolean',1);k=an[O],x++}else k=Ts;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);P=l[2],x++}p=fl(k,P)}else p=an[b];const T=[];for(;xl.outputDefined())}serialize(){const l=this.type,u=[l.kind];if(l.kind==="array"){const p=l.itemType;if(p.kind==="string"||p.kind==="number"||p.kind==="boolean"){u.push(p.kind);const x=l.N;(typeof x=="number"||this.args.length>1)&&u.push(x)}}return u.concat(this.args.map(p=>p.serialize()))}}class wp{constructor(l){this.type=B0,this.sections=l}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const p=l[1];if(!Array.isArray(p)&&typeof p=="object")return u.error("First argument must be an image or text section.");const x=[];let b=!1;for(let T=1;T<=l.length-1;++T){const k=l[T];if(b&&typeof k=="object"&&!Array.isArray(k)){b=!1;let P=null;if(k["font-scale"]&&(P=u.parseObjectValue(k["font-scale"],T,"font-scale",Ur),!P))return null;let O=null;if(k["text-font"]&&(O=u.parseObjectValue(k["text-font"],T,"text-font",fl(vs)),!O))return null;let $=null;if(k["text-color"]&&($=u.parseObjectValue(k["text-color"],T,"text-color",Ml),!$))return null;const V=x[x.length-1];V.scale=P,V.font=O,V.textColor=$}else{const P=u.parse(l[T],T,Ts);if(!P)return null;const O=P.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:P,scale:null,font:null,textColor:null})}}return new wp(x)}evaluate(l){return new Zo(this.sections.map(u=>{const p=u.content.evaluate(l);return Uh(Vi(p),$0)?new U0("",p,null,null,null):new U0(tn(p),null,u.scale?u.scale.evaluate(l):null,u.font?u.font.evaluate(l).join(","):null,u.textColor?u.textColor.evaluate(l):null)}))}eachChild(l){for(const u of this.sections)l(u.content),u.scale&&l(u.scale),u.font&&l(u.font),u.textColor&&l(u.textColor)}outputDefined(){return!1}serialize(){const l=["format"];for(const u of this.sections){l.push(u.content.serialize());const p={};u.scale&&(p["font-scale"]=u.scale.serialize()),u.font&&(p["text-font"]=u.font.serialize()),u.textColor&&(p["text-color"]=u.textColor.serialize()),l.push(p)}return l}}class Zr{constructor(l,u,p,x){this._imageWarnHistory={},this.type=$0,this.namePrimary=l,this.nameSecondary=u,p&&(this.paramsPrimary=p.params,this.iconsetIdPrimary=p.iconset?p.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 p=1;const x=[];function b(){if(pTc.isEqual(T,b)),x.available){const T=x.getSecondary()?x.getSecondary().id:null;T&&(x.available=l.availableImages.some(k=>Tc.isEqual(k,T)))}}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 p={};if(u&&(p.iconset={id:u}),l){p.params={};for(const x in l)l[x]&&(p.params[x]=l[x].serialize())}return Object.keys(p).length>0?p:void 0}serialize(){const l=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const u=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);u&&l.push(u)}if(this.nameSecondary&&(l.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const u=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);u&&l.push(u)}return l}}function V0(h){return Db(h)?"string":q0(h)?"number":G0(h)?"boolean":Array.isArray(h)?"array":h===null?"null":Mb(h)?"object":typeof h}function Mb(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function Db(h){return typeof h=="string"||h instanceof String}function q0(h){return typeof h=="number"||h instanceof Number}function G0(h){return typeof h=="boolean"||h instanceof Boolean}const aB={"to-boolean":Ss,"to-color":Ml,"to-number":Ur,"to-string":vs};class hd{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const p=l[0],x=[];let b=zh;if(p==="to-array"){if(!Array.isArray(l[1]))return null;const T=l[1].length;if(u.expectedType){if(u.expectedType.kind!=="array")return u.error(`Expected ${u.expectedType.kind} but found array.`);b=fl(u.expectedType.itemType,T)}else{if(!(T>0&&iy(l[1][0])))return null;b=fl(Vi(l[1][0]),T)}for(let k=0;k4?`Invalid rbga value ${JSON.stringify(u)}: expected an array containing either three or four numeric values.`:kI(u[0],u[1],u[2],u[3]),!p))return new as(u[0]/255,u[1]/255,u[2]/255,u[3])}throw new da(p||`Could not parse color from value '${typeof u=="string"?u:String(JSON.stringify(u))}'`)}if(this.type.kind==="number"){let u=null;for(const p of this.args){if(u=p.evaluate(l),u===null)return 0;const x=Number(u);if(!isNaN(x))return x}throw new da(`Could not convert ${JSON.stringify(u)} to number.`)}return this.type.kind==="formatted"?Zo.fromString(tn(this.args[0].evaluate(l))):this.type.kind==="resolvedImage"?Xl.build(tn(this.args[0].evaluate(l))):this.type.kind==="array"?this.args.map(u=>u.evaluate(l)):tn(this.args[0].evaluate(l))}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){if(this.type.kind==="formatted")return new wp([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Zr(this.args[0]).serialize();const l=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(u=>{l.push(u.serialize())}),l}}const Sp=["Unknown","Point","LineString","Polygon"];class H0{constructor(l,u,p){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=l,this.options=u,this.iconImageUseTheme=p}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Sp[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(l){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const l=this.featureDistanceData.center,u=this.featureDistanceData.scale,{x:p,y:x}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(p*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]=as.parse(l)),u}getConfig(l){return this.options?this.options.get(l):null}}class Ya{constructor(l,u,p,x,b){this.name=l,this.type=u,this._evaluate=p,this.args=x,this._overloadIndex=b}evaluate(l){if(!this._evaluate){const u=Ya.definitions[this.name];this._evaluate=Array.isArray(u)?u[2]:u.overloads[this._overloadIndex][1]}return this._evaluate(l,this.args)}eachChild(l){this.args.forEach(l)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(l=>l.serialize()))}static parse(l,u){const p=l[0],x=Ya.definitions[p];if(!x)return u.error(`Unknown expression "${p}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(x)?x[0]:x.type,T=Array.isArray(x)?[[x[1],x[2]]]:x.overloads,k=[];let P=null,O=-1;for(const[$,V]of T){if(Array.isArray($)&&$.length!==l.length-1)continue;k.push($),O++,P=new qb(u.registry,u.path,null,u.scope,void 0,u._scope,u.options,u.iconImageUseTheme);const G=[];let Y=!1;for(let X=1;XG)).map(Zf).join(" | "),V=[];for(let G=1;Gu;){if(p-u>600){const P=p-u+1,O=l-u+1,$=Math.log(P),V=.5*Math.exp(2*$/3),G=.5*Math.sqrt($*V*(P-V)/P)*(O-P/2<0?-1:1);AI(h,l,Math.max(u,Math.floor(l-O*V/P+G)),Math.min(p,Math.floor(l+(P-O)*V/P+G)),x)}const b=h[l];let T=u,k=p;for(W0(h,u,l),x(h[p],b)>0&&W0(h,u,p);T0;)k--}x(h[u],b)===0?W0(h,u,k):(k++,W0(h,k,p)),k<=l&&(u=k+1),l<=k&&(p=k-1)}}function W0(h,l,u){const p=h[l];h[l]=h[u],h[u]=p}function Fb(h,l){return hl?1:0}function NI(h){let l=0;for(let u,p,x=0,b=h.length,T=b-1;x=l[2]||h[1]<=l[1]||h[3]>=l[3])}function oB(h,l,u){const p=h[0]-l[0],x=h[1]-l[1],b=h[0]-u[0],T=h[1]-u[1];return p*T-b*x===0&&p*b<=0&&x*T<=0}function Xj(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 ay(h,l,u=!1){let p=!1;for(let x=0,b=l.length;x0&&k<0||T<0&&k>0}function Y0(h,l,u,p){return(x=[p[0]-u[0],p[1]-u[1]])[0]*(b=[l[0]-h[0],l[1]-h[1]])[1]-x[1]*b[0]!==0&&!(!CI(h,l,u,p)||!CI(u,p,h,l));var x,b}function Qj(h){const l=new Ft(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),u=new Ft(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const p of h[0])l.x>p.x&&(l.x=p.x),l.y>p.y&&(l.y=p.y),u.xu[2]){const x=.5*p;let b=h[0]-u[0]>x?-p:u[0]-h[0]>x?p:0;b===0&&(b=h[0]-u[2]>x?-p:u[2]-h[0]>x?p:0),h[0]+=b}fd(l,h)}function tE(h,l,u,p){const x=Math.pow(2,p.z)*Xf,b=[p.x*Xf,p.y*Xf],T=[];if(!h)return T;for(const k of h)for(const P of k){const O=[P.x+b[0],P.y+b[1]];Du(O,l,u,x),T.push(O)}return T}function rE(h,l,u,p){const x=Math.pow(2,p.z)*Xf,b=[p.x*Xf,p.y*Xf],T=[];if(!h)return T;for(const P of h){const O=[];for(const $ of P){const V=[$.x+b[0],$.y+b[1]];fd(l,V),O.push(V)}T.push(O)}if(l[2]-l[0]<=x/2){(k=l)[0]=k[1]=1/0,k[2]=k[3]=-1/0;for(const P of T)for(const O of P)Du(O,l,u,x)}var k;return T}class Qf{constructor(l,u){this.type=Ss,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(iy(l[1])){const p=l[1];if(p.type==="FeatureCollection")for(let x=0;xu)return $b(b,T,(u-(p-k))/k)}return l[l.length-1]}pointToSegmentDistance(l,u,p){let[x,b]=u,T=Kc(p[0]-x)*this.kx,k=(p[1]-b)*this.ky;if(T!==0||k!==0){const P=(Kc(l[0]-x)*this.kx*T+(l[1]-b)*this.ky*k)/(T*T+k*k);P>1?(x=p[0],b=p[1]):P>0&&(x+=T/this.kx*P,b+=k/this.ky*P)}return T=Kc(l[0]-x)*this.kx,k=(l[1]-b)*this.ky,Math.sqrt(T*T+k*k)}pointOnLine(l,u){let p=1/0,x=l[0][0],b=l[0][1],T=0,k=0;for(let P=0;P1?(O=l[P+1][0],$=l[P+1][1]):Y>0&&(O+=V/this.kx*Y,$+=G/this.ky*Y)),V=Kc(u[0]-O)*this.kx,G=(u[1]-$)*this.ky;const X=V*V+G*G;Xb.index||x.index===b.index&&x.t>b.t){const O=x;x=b,b=O}const T=[x.point],k=x.index+1,P=b.index;!iE(p[k],T[0])&&k<=P&&T.push(p[k]);for(let O=k+1;O<=P;O++)T.push(p[O]);return iE(p[P],b.point)||T.push(b.point),T}lineSliceAlong(l,u,p){let x=0;const b=[];for(let T=0;Tl&&b.length===0&&b.push($b(k,P,(l-(x-O))/O)),x>=u)return b.push($b(k,P,(u-(x-O))/O)),b;x>l&&b.push(P)}return b}bufferPoint(l,u){const p=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-p,l[0]+x,l[1]+p]}bufferBBox(l,u){const p=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-p,l[2]+x,l[3]+p]}insideBBox(l,u){return Kc(l[0]-u[0])>=0&&Kc(l[0]-u[2])<=0&&l[1]>=u[1]&&l[1]<=u[3]}}function iE(h,l){return h[0]===l[0]&&h[1]===l[1]}function $b(h,l,u){const p=Kc(l[0]-h[0]);return[h[0]+p*u,h[1]+(l[1]-h[1])*u]}function Kc(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}class X0{constructor(l=[],u=(p,x)=>px?1:0){if(this.data=l,this.length=this.data.length,this.compare=u,this.length>0)for(let p=(this.length>>1)-1;p>=0;p--)this._down(p)}push(l){this.data.push(l),this._up(this.length++)}pop(){if(this.length===0)return;const l=this.data[0],u=this.data.pop();return--this.length>0&&(this.data[0]=u,this._down(0)),l}peek(){return this.data[0]}_up(l){const{data:u,compare:p}=this,x=u[l];for(;l>0;){const b=l-1>>1,T=u[b];if(p(x,T)>=0)break;u[l]=T,l=b}u[l]=x}_down(l){const{data:u,compare:p}=this,x=this.length>>1,b=u[l];for(;l=0)break;u[l]=u[T],l=T}u[l]=b}}var fr=8192;function PI(h,l){return l.dist-h.dist}function RI(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=jp(h);if(l){if(u===2)return[h,null];const p=Math.floor(u/2);return[[h[0],h[0]+p],[h[0]+p,h[1]]]}{if(u===1)return[h,null];const p=Math.floor(u/2)-1;return[[h[0],h[0]+p],[h[0]+p+1,h[1]]]}}function Jf(h,l){const u=[1/0,1/0,-1/0,-1/0];if(!md(l,h.length))return u;for(let p=l[0];p<=l[1];++p)fd(u,h[p]);return u}function Q0(h){const l=[1/0,1/0,-1/0,-1/0];for(let u=0;ul[2]&&(p=h[0]-l[2]),h[1]>l[3]&&(x=h[1]-l[3]),h[3]=p)return p;if(K0(x,b)){if(FI(h,l))return 0}else if(FI(l,h))return 0;let T=p;for(const k of h)for(let P=0,O=k.length,$=O-1;P=b)continue;const $=O.range1;if(jp($)<=k){if(!md($,h.length))return NaN;if(l){const V=xi(h,$,u,p);if((b=Math.min(b,V))===0)return b}else for(let V=$[0];V<=$[1];++V){const G=hB(h[V],u,p);if((b=Math.min(b,G))===0)return b}}else{const V=cy($,l);if(V[0]!==null){const G=uy(Jf(h,V[0]),P,p);G=T)continue;const V=$.range1,G=$.range2;if(jp(V)<=P&&jp(G)<=O){if(!md(V,h.length)||!md(G,u.length))return NaN;if(l&&p?T=Math.min(T,dB(h,V,u,G,x)):l||p?l&&!p?T=Math.min(T,DI(u,G,h,V,x)):!l&&p&&(T=Math.min(T,DI(h,V,u,G,x))):T=Math.min(T,OI(h,V,u,G,x)),T===0)return T}else{const Y=cy(V,l),X=cy(G,p);zb(k,T,x,h,u,Y[0],X[0]),zb(k,T,x,h,u,Y[0],X[1]),zb(k,T,x,h,u,Y[1],X[0]),zb(k,T,x,h,u,Y[1],X[1])}}return T}function oE(h,l,u,p,x=1/0){let b=x;const T=Jf(h,[0,h.length-1]);for(const k of u)if(!(b!==1/0&&uy(T,Jf(k,[0,k.length-1]),p)>=b)&&(b=Math.min(b,BI(h,l,k,!0,p,b)),b===0))return b;return b}function Ub(h,l,u,p,x=1/0){let b=x;const T=Jf(h,[0,h.length-1]);for(const k of u){if(b!==1/0&&uy(T,Q0(k),p)>=b)continue;const P=mB(h,l,k,p,b);if(isNaN(P))return P;if((b=Math.min(b,P))===0)return b}return b}function lE(h){return h==="Point"||h==="MultiPoint"||h==="LineString"||h==="MultiLineString"||h==="Polygon"||h==="MultiPolygon"}class Ep{constructor(l,u){this.type=Ur,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(iy(l[1])){const p=l[1];if(p.type==="FeatureCollection"){for(let x=0;x{l&&!kp(u)&&(l=!1)}),l}function dy(h){if(h instanceof Ya&&h.name==="feature-state")return!1;let l=!0;return h.eachChild(u=>{l&&!dy(u)&&(l=!1)}),l}function Qd(h,l){if(h instanceof Ya&&l.indexOf(h.name)>=0)return!1;let u=!0;return h.eachChild(p=>{u&&!Qd(p,l)&&(u=!1)}),u}function $I(h,l,u){return[h,l,u].filter(Boolean).join("")}function cE(h,l){switch(h){case"string":return tn(l);case"number":return+l;case"boolean":return!!l;case"color":return as.parse(l);case"formatted":return Zo.fromString(tn(l));case"resolvedImage":return Xl.build(tn(l))}return l}function zI(h,l,u,p){return p!==void 0&&(h=p*Math.round(h/p)),l!==void 0&&hu&&(h=u),h}class hy{constructor(l,u,p,x=!1){this.type=l,this.key=u,this.scope=p,this.featureConstant=x}static parse(l,u){let p=u.expectedType;if(p==null&&(p=Ts),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 Mr))return u.error("Key name of 'config' expression must be a string literal.");let b,T=!0;const k=tn(x.value);if(l.length>=3){const P=u.parse(l[2],2);if(!(P instanceof Mr))return u.error("Scope of 'config' expression must be a string literal.");b=tn(P.value)}if(u.options){const P=$I(k,b,u._scope),O=u.options.get(P);O&&(T=kp(O.value||O.default))}return new hy(p,k,b,T)}evaluate(l){const u=$I(this.key,this.scope,l.scope),p=l.getConfig(u);if(!p)return null;const{type:x,value:b,values:T,minValue:k,maxValue:P,stepValue:O}=p,$=p.default.evaluate(l);let V=$;if(b){const G=l.scope;l.scope=(G||"").split("").slice(1).join(""),V=b.evaluate(l),l.scope=G}return x&&(V=cE(x,V)),V===void 0||k===void 0&&P===void 0&&O===void 0||(typeof V=="number"?V=zI(V,k,P,O):Array.isArray(V)&&(V=V.map(G=>typeof G=="number"?zI(G,k,P,O):G))),b!==void 0&&V!==void 0&&T&&!T.includes(V)&&(V=$,x&&(V=cE(x,V))),(x&&x!==this.type||V!==void 0&&!Uh(Vi(V),this.type))&&(V=cE(this.type.kind,V)),V}eachChild(){}outputDefined(){return!1}serialize(){const l=["config",this.key];return this.scope&&l.concat(this.scope),l}}class Vb{constructor(l,u){this.type=u.type,this.name=l,this.boundExpression=u}static parse(l,u){if(l.length!==2||typeof l[1]!="string")return u.error("'var' expression requires exactly one string literal argument.");const p=l[1];return u.scope.has(p)?new Vb(p,u.scope.get(p)):u.error(`Unknown variable "${p}". Make sure "${p}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(l){return this.boundExpression.evaluate(l)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class qb{constructor(l,u=[],p,x=new _p,b=[],T,k,P){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=p,this._scope=T,this.options=k,this.iconImageUseTheme=P}parse(l,u,p,x,b={}){return u||p?this.concat(u,null,p,x)._parse(l,b):this._parse(l,b)}parseObjectValue(l,u,p,x,b,T={}){return this.concat(u,p,x,b)._parse(l,T)}_parse(l,u){function p(x,b,T){return T==="assert"?new Wc(b,[x]):T==="coerce"?new hd(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 T=this.expectedType,k=b.type;if(T.kind!=="string"&&T.kind!=="number"&&T.kind!=="boolean"&&T.kind!=="object"&&T.kind!=="array"||k.kind!=="value")if(T.kind!=="color"&&T.kind!=="formatted"&&T.kind!=="resolvedImage"||k.kind!=="value"&&k.kind!=="string"){if(this.checkSubtype(T,k))return null}else b=p(b,T,u.typeAnnotation||"coerce");else b=p(b,T,u.typeAnnotation||"assert")}if(!(b instanceof Mr)&&b.type.kind!=="resolvedImage"&&uE(b)){const T=new H0(this._scope,this.options,this.iconImageUseTheme);try{b=new Mr(b.type,b.evaluate(T))}catch(k){return this.error(k.message),null}}return b}return hd.parse(["to-array",l],this)}return this.error(l===void 0?"'undefined' value invalid. Use null instead.":typeof l=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof l} instead.`)}concat(l,u,p,x){let b=typeof l=="number"?this.path.concat(l):this.path;b=typeof u=="string"?b.concat(u):b;const T=x?this.scope.concat(x):this.scope;return new qb(this.registry,b,p||null,T,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(l,...u){const p=`${this.key}${u.map(x=>`[${x}]`).join("")}`;this.errors.push(new Lu(p,l))}checkSubtype(l,u){const p=z0(l,u);return p&&this.error(p),p}}function uE(h){if(h instanceof Vb)return uE(h.boundExpression);if(h instanceof Ya&&h.name==="error"||h instanceof Ob||h instanceof Qf||h instanceof Ep||h instanceof hy)return!1;const l=h instanceof hd||h instanceof Wc;let u=!0;return h.eachChild(p=>{u=l?u&&uE(p):u&&p instanceof Mr}),!!u&&kp(h)&&Qd(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 Gb(h,l){const u=h.length-1;let p,x,b=0,T=u,k=0;for(;b<=T;)if(k=Math.floor((b+T)/2),p=h[k],x=h[k+1],p<=l){if(k===u||ll))throw new da("Input is not a number.");T=k-1}return 0}class J0{constructor(l,u,p){this.type=l,this.input=u,this.labels=[],this.outputs=[];for(const[x,b]of p)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 p=u.parse(l[1],1,Ur);if(!p)return null;const x=[];let b=null;u.expectedType&&u.expectedType.kind!=="value"&&(b=u.expectedType);for(let T=1;T=k)return u.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',O);const V=u.parse(P,$,b);if(!V)return null;b=b||V.type,x.push([k,V])}return new J0(b,p,x)}evaluate(l){const u=this.labels,p=this.outputs;if(u.length===1)return p[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return p[0].evaluate(l);const b=u.length;return x>=u[b-1]?p[b-1].evaluate(l):p[Gb(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 UI=.95047,VI=1.08883,qI=4/29,fy=6/29,GI=3*fy*fy,pB=fy*fy*fy,gB=Math.PI/180,yB=180/Math.PI;function dE(h){return h>pB?Math.pow(h,1/3):h/GI+qI}function hE(h){return h>fy?h*h*h:GI*(h-qI)}function ev(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function my(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function fE(h){const l=my(h.r),u=my(h.g),p=my(h.b),x=dE((.4124564*l+.3575761*u+.1804375*p)/UI),b=dE((.2126729*l+.7151522*u+.072175*p)/1);return{l:116*b-16,a:500*(x-b),b:200*(b-dE((.0193339*l+.119192*u+.9503041*p)/VI)),alpha:h.a}}function HI(h){let l=(h.l+16)/116,u=isNaN(h.a)?l:l+h.a/500,p=isNaN(h.b)?l:l-h.b/200;return l=1*hE(l),u=UI*hE(u),p=VI*hE(p),new as(ev(3.2404542*u-1.5371385*l-.4985314*p),ev(-.969266*u+1.8760108*l+.041556*p),ev(.0556434*u-.2040259*l+1.0572252*p),h.alpha)}function xB(h,l,u){const p=l-h;return h+u*(p>180||p<-180?p-360*Math.round(p/360):p)}const tv={forward:fE,reverse:HI,interpolate:function(h,l,u){return{l:sn(h.l,l.l,u),a:sn(h.a,l.a,u),b:sn(h.b,l.b,u),alpha:sn(h.alpha,l.alpha,u)}}},py={forward:function(h){const{l,a:u,b:p}=fE(h),x=Math.atan2(p,u)*yB;return{h:x<0?x+360:x,c:Math.sqrt(u*u+p*p),l,alpha:h.a}},reverse:function(h){const l=h.h*gB,u=h.c;return HI({l:h.l,a:Math.cos(l)*u,b:Math.sin(l)*u,alpha:h.alpha})},interpolate:function(h,l,u){return{h:xB(h.h,l.h,u),c:sn(h.c,l.c,u),l:sn(h.l,l.l,u),alpha:sn(h.alpha,l.alpha,u)}}};var mE=Object.freeze({__proto__:null,hcl:py,lab:tv});class Xo{constructor(l,u,p,x,b){this.type=l,this.operator=u,this.interpolation=p,this.input=x,this.labels=[],this.outputs=[];for(const[T,k]of b)this.labels.push(T),this.outputs.push(k)}static interpolationFactor(l,u,p,x){let b=0;if(l.name==="exponential")b=Hb(u,l.base,p,x);else if(l.name==="linear")b=Hb(u,1,p,x);else if(l.name==="cubic-bezier"){const T=l.controlPoints;b=new Us(T[0],T[1],T[2],T[3]).solve(Hb(u,1,p,x))}return b}static parse(l,u){let[p,x,b,...T]=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($=>typeof $!="number"||$<0||$>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,Ur),!b)return null;const k=[];let P=null;p==="interpolate-hcl"||p==="interpolate-lab"?P=Ml:u.expectedType&&u.expectedType.kind!=="value"&&(P=u.expectedType);for(let O=0;O=$)return u.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',G);const X=u.parse(V,Y,P);if(!X)return null;P=P||X.type,k.push([$,X])}return P.kind==="number"||P.kind==="color"||P.kind==="array"&&P.itemType.kind==="number"&&typeof P.N=="number"?new Xo(P,p,x,b,k):u.error(`Type ${ba(P)} is not interpolatable.`)}evaluate(l){const u=this.labels,p=this.outputs;if(u.length===1)return p[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return p[0].evaluate(l);const b=u.length;if(x>=u[b-1])return p[b-1].evaluate(l);const T=Gb(u,x),k=Xo.interpolationFactor(this.interpolation,x,u[T],u[T+1]),P=p[T].evaluate(l),O=p[T+1].evaluate(l);return this.operator==="interpolate"?Lb[this.type.kind.toLowerCase()](P,O,k):this.operator==="interpolate-hcl"?py.reverse(py.interpolate(py.forward(P),py.forward(O),k)):tv.reverse(tv.interpolate(tv.forward(P),tv.forward(O),k))}eachChild(l){l(this.input);for(const u of this.outputs)l(u)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){let l;l=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const u=[this.operator,l,this.input.serialize()];for(let p=0;pz0(x,k.type));return new rv(T?Ts:p,b)}evaluate(l){let u,p=null,x=0;for(const b of this.args){if(x++,p=b.evaluate(l),p&&p instanceof Xl&&!p.available&&(u||(u=p),p=null,x===this.args.length))return u;if(p!==null)break}return p}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){const l=["coalesce"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class Wb{constructor(l,u){this.type=u.type,this.bindings=[].concat(l),this.result=u}evaluate(l){return this.result.evaluate(l)}eachChild(l){for(const u of this.bindings)l(u[1]);l(this.result)}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found ${l.length-1} instead.`);const p=[];for(let b=1;b=p.length)throw new da("Array index out of bounds: index exceeds array size");if(u!==Math.floor(u))throw new da("Array index must be an integer. Use at-interpolated for fractional indices");return p[u]}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class sv{constructor(l,u,p){this.type=l,this.index=u,this.input=p}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=u.parse(l[1],1,Ur),x=u.parse(l[2],2,fl(u.expectedType||Ts));return p&&x?new sv(x.type.itemType,p,x):null}evaluate(l){const u=this.index.evaluate(l),p=this.input.evaluate(l);if(u<0)throw new da(`Array index out of bounds: ${u} < 0.`);if(u>p.length-1)throw new da(`Array index out of bounds: ${u} > ${p.length-1}.`);if(u===Math.floor(u))return p[u];const x=Math.floor(u),b=Math.ceil(u),T=p[x],k=p[b];if(typeof T!="number"||typeof k!="number")throw new da(`Cannot interpolate between non-number values at index ${u}.`);const P=u-x;return T*(1-P)+k*P}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class iv{constructor(l,u){this.type=Ss,this.needle=l,this.haystack=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1,Ts),x=u.parse(l[2],2,Ts);return p&&x?Yj(p.type,[Ss,vs,Ur,zh,Ts])?new iv(p,x):(u.error(`Expected first argument to be of type boolean, string, number or null, but found ${ba(p.type)} instead`),null):null}evaluate(l){const u=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(p==null)return!1;if(!sy(u,["boolean","string","number","null"]))throw new da(`Expected first argument to be of type boolean, string, number or null, but found ${ba(Vi(u))} instead.`);if(!sy(p,["string","array"]))throw new da(`Expected second argument to be of type array or string, but found ${ba(Vi(p))} instead.`);return p.indexOf(u)>=0}eachChild(l){l(this.needle),l(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Kb{constructor(l,u,p){this.type=Ur,this.needle=l,this.haystack=u,this.fromIndex=p}static parse(l,u){if(l.length<=2||l.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1,Ts),x=u.parse(l[2],2,Ts);if(!p||!x)return null;if(!Yj(p.type,[Ss,vs,Ur,zh,Ts]))return u.error(`Expected first argument to be of type boolean, string, number or null, but found ${ba(p.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Ur);return b?new Kb(p,x,b):null}return new Kb(p,x)}evaluate(l){const u=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(!sy(u,["boolean","string","number","null"]))throw new da(`Expected first argument to be of type boolean, string, number or null, but found ${ba(Vi(u))} instead.`);if(!sy(p,["string","array"]))throw new da(`Expected second argument to be of type array or string, but found ${ba(Vi(p))} instead.`);if(this.fromIndex){const x=this.fromIndex.evaluate(l);return p.indexOf(u,x)}return p.indexOf(u)}eachChild(l){l(this.needle),l(this.haystack),this.fromIndex&&l(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const l=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),l]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class pE{constructor(l,u,p,x,b,T){this.inputType=l,this.type=u,this.input=p,this.cases=x,this.outputs=b,this.otherwise=T}static parse(l,u){if(l.length<5)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length%2!=1)return u.error("Expected an even number of arguments.");let p,x;u.expectedType&&u.expectedType.kind!=="value"&&(x=u.expectedType);const b={},T=[];for(let O=2;ONumber.MAX_SAFE_INTEGER)return G.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof X=="number"&&Math.floor(X)!==X)return G.error("Numeric branch labels must be integer values.");if(p){if(G.checkSubtype(p,Vi(X)))return null}else p=Vi(X);if(b[String(X)]!==void 0)return G.error("Branch labels must be unique.");b[String(X)]=T.length}const Y=u.parse(V,O,x);if(!Y)return null;x=x||Y.type,T.push(Y)}const k=u.parse(l[1],1,Ts);if(!k)return null;const P=u.parse(l[l.length-1],l.length-1,x);return P?k.type.kind!=="value"&&u.concat(1).checkSubtype(p,k.type)?null:new pE(p,x,k,b,T,P):null}evaluate(l){const u=this.input.evaluate(l);return(Uh(Vi(u),this.inputType)&&this.outputs[this.cases[u]]||this.otherwise).evaluate(l)}eachChild(l){l(this.input),this.outputs.forEach(l),l(this.otherwise)}outputDefined(){return this.outputs.every(l=>l.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["match",this.input.serialize()],u=Object.keys(this.cases).sort(),p=[],x={};for(const T of u){const k=x[this.cases[T]];k===void 0?(x[this.cases[T]]=p.length,p.push([this.cases[T],[T]])):p[k][1].push(T)}const b=T=>this.inputType.kind==="number"?Number(T):T;for(const[T,k]of p)l.push(k.length===1?b(k[0]):k.map(b)),l.push(this.outputs[T].serialize());return l.push(this.otherwise.serialize()),l}}class Yb{constructor(l,u,p){this.type=l,this.branches=u,this.otherwise=p}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found only ${l.length-1}.`),null;if(l.length%2!=0)return u.error("Expected an odd number of arguments."),null;let p;u.expectedType&&u.expectedType.kind!=="value"&&(p=u.expectedType);const x=[];for(let T=1;Tu.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["case"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class av{constructor(l,u,p,x){this.type=l,this.input=u,this.beginIndex=p,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 p=u.parse(l[1],1,Ts),x=u.parse(l[2],2,Ur);if(!p||!x)return null;if(!Yj(p.type,[fl(Ts),vs,Ts]))return u.error(`Expected first argument to be of type array or string, but found ${ba(p.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Ur);return b?new av(p.type,p,x,b):null}return new av(p.type,p,x)}evaluate(l){const u=this.input.evaluate(l),p=this.beginIndex.evaluate(l);if(!sy(u,["string","array"]))throw new da(`Expected first argument to be of type array or string, but found ${ba(Vi(u))} instead.`);if(this.endIndex){const x=this.endIndex.evaluate(l);return u.slice(p,x)}return u.slice(p)}eachChild(l){l(this.input),l(this.beginIndex),this.endIndex&&l(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const l=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),l]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class gE{constructor(l,u){this.type=fl(vs),this.str=l,this.delimiter=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=u.parse(l[1],1,vs),x=u.parse(l[2],2,vs);return p&&x?new gE(p,x):void 0}evaluate(l){const u=this.str.evaluate(l),p=this.delimiter.evaluate(l);return u.split(p)}eachChild(l){l(this.str),l(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function WI(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 KI(h,l,u,p){return p.compare(l,u)===0}function Ap(h,l,u){const p=h!=="=="&&h!=="!=";return class aSe{constructor(b,T,k){this.type=Ss,this.lhs=b,this.rhs=T,this.collator=k,this.hasUntypedArgument=b.type.kind==="value"||T.type.kind==="value"}static parse(b,T){if(b.length!==3&&b.length!==4)return T.error("Expected two or three arguments.");const k=b[0];let P=T.parse(b[1],1,Ts);if(!P)return null;if(!WI(k,P.type))return T.concat(1).error(`"${k}" comparisons are not supported for type '${ba(P.type)}'.`);let O=T.parse(b[2],2,Ts);if(!O)return null;if(!WI(k,O.type))return T.concat(2).error(`"${k}" comparisons are not supported for type '${ba(O.type)}'.`);if(P.type.kind!==O.type.kind&&P.type.kind!=="value"&&O.type.kind!=="value")return T.error(`Cannot compare types '${ba(P.type)}' and '${ba(O.type)}'.`);p&&(P.type.kind==="value"&&O.type.kind!=="value"?P=new Wc(O.type,[P]):P.type.kind!=="value"&&O.type.kind==="value"&&(O=new Wc(P.type,[O])));let $=null;if(b.length===4){if(P.type.kind!=="string"&&O.type.kind!=="string"&&P.type.kind!=="value"&&O.type.kind!=="value")return T.error("Cannot use collator to compare non-string types.");if($=T.parse(b[3],3,bp),!$)return null}return new aSe(P,O,$)}evaluate(b){const T=this.lhs.evaluate(b),k=this.rhs.evaluate(b);if(p&&this.hasUntypedArgument){const P=Vi(T),O=Vi(k);if(P.kind!==O.kind||P.kind!=="string"&&P.kind!=="number")throw new da(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${P.kind}, ${O.kind}) instead.`)}if(this.collator&&!p&&this.hasUntypedArgument){const P=Vi(T),O=Vi(k);if(P.kind!=="string"||O.kind!=="string")return l(b,T,k)}return this.collator?u(b,T,k,this.collator.evaluate(b)):l(b,T,k)}eachChild(b){b(this.lhs),b(this.rhs),this.collator&&b(this.collator)}outputDefined(){return!0}serialize(){const b=[h];return this.eachChild(T=>{b.push(T.serialize())}),b}}}const YI=Ap("==",function(h,l,u){return l===u},KI),Zb=Ap("!=",function(h,l,u){return l!==u},function(h,l,u,p){return!KI(0,l,u,p)}),vB=Ap("<",function(h,l,u){return l",function(h,l,u){return l>u},function(h,l,u,p){return p.compare(l,u)>0}),_B=Ap("<=",function(h,l,u){return l<=u},function(h,l,u,p){return p.compare(l,u)<=0}),bB=Ap(">=",function(h,l,u){return l>=u},function(h,l,u,p){return p.compare(l,u)>=0});class Xb{constructor(l,u,p,x,b,T){this.type=vs,this.number=l,this.locale=u,this.currency=p,this.unit=x,this.minFractionDigits=b,this.maxFractionDigits=T}static parse(l,u){if(l.length!==3)return u.error("Expected two arguments.");const p=u.parse(l[1],1,Ur);if(!p)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",vs),!b))return null;let T=null;if(x.currency&&(T=u.parseObjectValue(x.currency,2,"currency",vs),!T))return null;let k=null;if(x.unit&&(k=u.parseObjectValue(x.unit,2,"unit",vs),!k))return null;let P=null;if(x["min-fraction-digits"]&&(P=u.parseObjectValue(x["min-fraction-digits"],2,"min-fraction-digits",Ur),!P))return null;let O=null;return x["max-fraction-digits"]&&(O=u.parseObjectValue(x["max-fraction-digits"],2,"max-fraction-digits",Ur),!O)?null:new Xb(p,b,T,k,P,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 Qb{constructor(l){this.type=Ur,this.input=l}static parse(l,u){if(l.length!==2)return u.error(`Expected 1 argument, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1);return p?p.type.kind!=="array"&&p.type.kind!=="string"&&p.type.kind!=="value"?(u.error(`Expected argument of type string or array, but found ${ba(p.type)} instead.`),null):new Qb(p):null}evaluate(l){const u=this.input.evaluate(l);if(typeof u=="string"||Array.isArray(u))return u.length;throw new da(`Expected value to be of type string or array, but found ${ba(Vi(u))} instead.`)}eachChild(l){l(this.input)}outputDefined(){return!1}serialize(){const l=["length"];return this.eachChild(u=>{l.push(u.serialize())}),l}}function XI(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 gy={"==":YI,"!=":Zb,">":ZI,"<":vB,">=":bB,"<=":_B,array:Wc,at:nv,"at-interpolated":sv,boolean:Wc,case:Yb,coalesce:rv,collator:Ob,format:wp,image:Zr,in:iv,"index-of":Kb,interpolate:Xo,"interpolate-hcl":Xo,"interpolate-lab":Xo,length:Qb,let:Wb,literal:Mr,match:pE,number:Wc,"number-format":Xb,object:Wc,slice:av,step:J0,string:Wc,"to-boolean":hd,"to-color":hd,"to-number":hd,"to-string":hd,var:Vb,within:Qf,distance:Ep,config:hy,split:gE};function QI(h,[l,u,p,x]){l=l.evaluate(h),u=u.evaluate(h),p=p.evaluate(h);const b=x?x.evaluate(h):1,T=kI(l,u,p,b);if(T)throw new da(T);return new as(l/255,u/255,p/255,b)}function JI(h,[l,u,p,x]){l=l.evaluate(h),u=u.evaluate(h),p=p.evaluate(h);const b=x?x.evaluate(h):1,T=function(O,$,V,G){return typeof O=="number"&&O>=0&&O<=360?typeof $=="number"&&$>=0&&$<=100&&typeof V=="number"&&V>=0&&V<=100?G===void 0||typeof G=="number"&&G>=0&&G<=1?null:`Invalid hsla value [${[O,$,V,G].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof G=="number"?[O,$,V,G]:[O,$,V]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof G=="number"?[O,$,V,G]:[O,$,V]).join(", ")}]: 'h' must be between 0 and 360.`}(l,u,p,b);if(T)throw new da(T);const k=`hsla(${l}, ${u}%, ${p}%, ${b})`,P=as.parse(k);if(!P)throw new da(`Failed to parse HSLA color: ${k}`);return P}function ov(h,l){return h in l}function Jb(h,l){const u=l[h];return u===void 0?null:u}function em(h){return{type:h}}function ew(h){if(h instanceof hy)return new Set([h.key]);let l=new Set;return h.eachChild(u=>{l=new Set([...l,...ew(u)])}),l}function tw(h){if(h instanceof Ya&&h.name==="is-active-floor")return!0;let l=!1;return h.eachChild(u=>{!l&&tw(u)&&(l=!0)}),l}function eP(h){return{result:"success",value:h}}function tm(h){return{result:"error",value:h}}function lv(h,l){return!!h&&!!h.parameters&&h.parameters.indexOf(l)>-1}function rw(h){return h["property-type"]==="data-driven"}function tP(h){return lv(h.expression,"measure-light")}function yE(h){return lv(h.expression,"zoom")}function nw(h){return!!h.expression&&h.expression.interpolated}function xE(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function rP(h){return h}function nP(h,l){const u=l.type==="color",p=h.stops&&typeof h.stops[0][0]=="object",x=p||!(p||h.property!==void 0),b=h.type||(nw(l)?"exponential":"interval");if(u&&((h=Object.assign({},h)).stops&&(h.stops=h.stops.map(O=>[O[0],as.parse(O[1])])),h.default=as.parse(h.default?h.default:l.default)),h.colorSpace&&h.colorSpace!=="rgb"&&!mE[h.colorSpace])throw new Error(`Unknown color space: ${h.colorSpace}`);let T,k,P;if(b==="exponential")T=sP;else if(b==="interval")T=SB;else if(b==="categorical"){T=wB,k=Object.create(null);for(const O of h.stops)k[O[0]]=O[1];P=typeof h.stops[0][0]}else{if(b!=="identity")throw new Error(`Unknown function type "${b}"`);T=iP}if(p){const O={},$=[];for(let Y=0;YY[0]),evaluate:({zoom:Y},X)=>sP({stops:V,base:h.base},l,Y).evaluate(Y,X)}}if(x){const O=b==="exponential"?{name:"exponential",base:h.base!==void 0?h.base:1}:null;return{kind:"camera",interpolationType:O,interpolationFactor:Xo.interpolationFactor.bind(void 0,O),zoomStops:h.stops.map($=>$[0]),evaluate:({zoom:$})=>T(h,l,$,k,P)}}return{kind:"source",evaluate(O,$){const V=$&&$.properties?$.properties[h.property]:void 0;return V===void 0?Jd(h.default,l.default):T(h,l,V,k,P)}}}function Jd(h,l,u){return h!==void 0?h:l!==void 0?l:u!==void 0?u:void 0}function wB(h,l,u,p,x){return Jd(typeof u===x?p[u]:void 0,h.default,l.default)}function SB(h,l,u){if(!q0(u))return Jd(h.default,l.default);const p=h.stops.length;if(p===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[p-1][0])return h.stops[p-1][1];const x=Gb(h.stops.map(b=>b[0]),u);return h.stops[x][1]}function sP(h,l,u){const p=h.base!==void 0?h.base:1;if(!q0(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=Gb(h.stops.map($=>$[0]),u),T=function($,V,G,Y){const X=Y-G,te=$-G;return X===0?0:V===1?te/X:(Math.pow(V,te)-1)/(Math.pow(V,X)-1)}(u,p,h.stops[b][0],h.stops[b+1][0]),k=h.stops[b][1],P=h.stops[b+1][1];let O=Lb[l.type]||rP;if(h.colorSpace&&h.colorSpace!=="rgb"){const $=mE[h.colorSpace];O=(V,G)=>$.reverse($.interpolate($.forward(V),$.forward(G),T))}return typeof k.evaluate=="function"?{evaluate(...$){const V=k.evaluate.apply(void 0,$),G=P.evaluate.apply(void 0,$);if(V!==void 0&&G!==void 0)return O(V,G,T)}}:O(k,P,T)}function iP(h,l,u){return l.type==="color"?u=as.parse(u):l.type==="formatted"?u=Zo.fromString(u.toString()):l.type==="resolvedImage"?u=Xl.build(u.toString()):V0(u)===l.type||l.type==="enum"&&l.values[u]||(u=void 0),Jd(u,h.default,l.default)}Ya.register(gy,{error:[{kind:"error"},[vs],(h,[l])=>{throw new da(l.evaluate(h))}],typeof:[vs,[Ts],(h,[l])=>ba(Vi(l.evaluate(h)))],"to-rgba":[fl(Ur,4),[Ml],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[fl(Ur,4),[Ml],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Ml,[Ur,Ur,Ur],QI],rgba:[Ml,[Ur,Ur,Ur,Ur],QI],hsl:[Ml,[Ur,Ur,Ur],JI],hsla:[Ml,[Ur,Ur,Ur,Ur],JI],has:{type:Ss,overloads:[[[vs],(h,[l])=>ov(l.evaluate(h),h.properties())],[[vs,Yf],(h,[l,u])=>ov(l.evaluate(h),u.evaluate(h))]]},get:{type:Ts,overloads:[[[vs],(h,[l])=>Jb(l.evaluate(h),h.properties())],[[vs,Yf],(h,[l,u])=>Jb(l.evaluate(h),u.evaluate(h))]]},"feature-state":[Ts,[vs],(h,[l])=>Jb(l.evaluate(h),h.featureState||{})],properties:[Yf,[],h=>h.properties()],"geometry-type":[vs,[],h=>h.geometryType()],worldview:[vs,[],h=>h.globals.worldview||""],"is-active-floor":[Ss,em(vs),(h,l)=>{if(!(h.globals&&h.globals.activeFloors&&h.globals.activeFloors.size>0))return!1;if(l.length===0)return!0;const u=h.globals.activeFloors;return l.some(p=>{const x=p.evaluate(h);return u.has(x)})}],id:[Ts,[],h=>h.id()],zoom:[Ur,[],h=>h.globals.zoom],pitch:[Ur,[],h=>h.globals.pitch||0],"distance-from-center":[Ur,[],h=>h.distanceFromCenter()],"measure-light":[Ur,[vs],(h,[l])=>h.measureLight(l.evaluate(h))],"heatmap-density":[Ur,[],h=>h.globals.heatmapDensity||0],"line-progress":[Ur,[],h=>h.globals.lineProgress||0],"raster-value":[Ur,[],h=>h.globals.rasterValue||0],"raster-particle-speed":[Ur,[],h=>h.globals.rasterParticleSpeed||0],"sky-radial-progress":[Ur,[],h=>h.globals.skyRadialProgress||0],accumulated:[Ts,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Ur,em(Ur),(h,l)=>{let u=0;for(const p of l)u+=p.evaluate(h);return u}],"*":[Ur,em(Ur),(h,l)=>{let u=1;for(const p of l)u*=p.evaluate(h);return u}],"-":{type:Ur,overloads:[[[Ur,Ur],(h,[l,u])=>l.evaluate(h)-u.evaluate(h)],[[Ur],(h,[l])=>-l.evaluate(h)]]},"/":[Ur,[Ur,Ur],(h,[l,u])=>l.evaluate(h)/u.evaluate(h)],"%":[Ur,[Ur,Ur],(h,[l,u])=>l.evaluate(h)%u.evaluate(h)],ln2:[Ur,[],()=>Math.LN2],pi:[Ur,[],()=>Math.PI],e:[Ur,[],()=>Math.E],"^":[Ur,[Ur,Ur],(h,[l,u])=>Math.pow(l.evaluate(h),u.evaluate(h))],sqrt:[Ur,[Ur],(h,[l])=>Math.sqrt(l.evaluate(h))],log10:[Ur,[Ur],(h,[l])=>Math.log(l.evaluate(h))/Math.LN10],ln:[Ur,[Ur],(h,[l])=>Math.log(l.evaluate(h))],log2:[Ur,[Ur],(h,[l])=>Math.log2(l.evaluate(h))],sin:[Ur,[Ur],(h,[l])=>Math.sin(l.evaluate(h))],cos:[Ur,[Ur],(h,[l])=>Math.cos(l.evaluate(h))],tan:[Ur,[Ur],(h,[l])=>Math.tan(l.evaluate(h))],asin:[Ur,[Ur],(h,[l])=>Math.asin(l.evaluate(h))],acos:[Ur,[Ur],(h,[l])=>Math.acos(l.evaluate(h))],atan:[Ur,[Ur],(h,[l])=>Math.atan(l.evaluate(h))],min:[Ur,em(Ur),(h,l)=>Math.min(...l.map(u=>u.evaluate(h)))],max:[Ur,em(Ur),(h,l)=>Math.max(...l.map(u=>u.evaluate(h)))],abs:[Ur,[Ur],(h,[l])=>Math.abs(l.evaluate(h))],round:[Ur,[Ur],(h,[l])=>{const u=l.evaluate(h);return u<0?-Math.round(-u):Math.round(u)}],floor:[Ur,[Ur],(h,[l])=>Math.floor(l.evaluate(h))],ceil:[Ur,[Ur],(h,[l])=>Math.ceil(l.evaluate(h))],"filter-==":[Ss,[vs,Ts],(h,[l,u])=>h.properties()[l.value]===u.value],"filter-id-==":[Ss,[Ts],(h,[l])=>h.id()===l.value],"filter-type-==":[Ss,[vs],(h,[l])=>h.geometryType()===l.value],"filter-<":[Ss,[vs,Ts],(h,[l,u])=>{const p=h.properties()[l.value],x=u.value;return typeof p==typeof x&&p{const u=h.id(),p=l.value;return typeof u==typeof p&&u":[Ss,[vs,Ts],(h,[l,u])=>{const p=h.properties()[l.value],x=u.value;return typeof p==typeof x&&p>x}],"filter-id->":[Ss,[Ts],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u>p}],"filter-<=":[Ss,[vs,Ts],(h,[l,u])=>{const p=h.properties()[l.value],x=u.value;return typeof p==typeof x&&p<=x}],"filter-id-<=":[Ss,[Ts],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u<=p}],"filter->=":[Ss,[vs,Ts],(h,[l,u])=>{const p=h.properties()[l.value],x=u.value;return typeof p==typeof x&&p>=x}],"filter-id->=":[Ss,[Ts],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u>=p}],"filter-has":[Ss,[Ts],(h,[l])=>l.value in h.properties()],"filter-has-id":[Ss,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[Ss,[fl(vs)],(h,[l])=>l.value.indexOf(h.geometryType())>=0],"filter-id-in":[Ss,[fl(Ts)],(h,[l])=>l.value.indexOf(h.id())>=0],"filter-in-small":[Ss,[vs,fl(Ts)],(h,[l,u])=>u.value.indexOf(h.properties()[l.value])>=0],"filter-in-large":[Ss,[vs,fl(Ts)],(h,[l,u])=>function(p,x,b,T){for(;b<=T;){const k=b+T>>1;if(x[k]===p)return!0;x[k]>p?T=k-1:b=k+1}return!1}(h.properties()[l.value],u.value,0,u.value.length-1)],all:{type:Ss,overloads:[[[Ss,Ss],(h,[l,u])=>l.evaluate(h)&&u.evaluate(h)],[em(Ss),(h,l)=>{for(const u of l)if(!u.evaluate(h))return!1;return!0}]]},any:{type:Ss,overloads:[[[Ss,Ss],(h,[l,u])=>l.evaluate(h)||u.evaluate(h)],[em(Ss),(h,l)=>{for(const u of l)if(u.evaluate(h))return!0;return!1}]]},"!":[Ss,[Ss],(h,[l])=>!l.evaluate(h)],"is-supported-script":[Ss,[vs],(h,[l])=>{const u=h.globals&&h.globals.isSupportedScript;return!u||u(l.evaluate(h))}],upcase:[vs,[vs],(h,[l])=>l.evaluate(h).toUpperCase()],downcase:[vs,[vs],(h,[l])=>l.evaluate(h).toLowerCase()],concat:[vs,em(Ts),(h,l)=>l.map(u=>tn(u.evaluate(h))).join("")],"resolved-locale":[vs,[bp],(h,[l])=>l.evaluate(h).resolvedLocale()],random:[Ur,[Ur,Ur,Ts],(h,l)=>{const[u,p,x]=l.map(T=>T.evaluate(h));if(u>p||u===p)return u;let b;if(typeof x=="string")b=function(T){let k=0;if(T.length===0)return k;for(let P=0;PJSON.stringify(V)).join(", ")}, but found ${JSON.stringify($)} instead.`);return $}catch($){const V=$;return this._warningHistory[V.message]||(this._warningHistory[V.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${V.message}`)),this._defaultValue}}}function cv(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&h[0]in gy}function rm(h,l,u,p,x){const b=new qb(gy,[],l?function(k){const P={color:Ml,string:vs,number:Ur,enum:vs,boolean:Ss,formatted:B0,resolvedImage:$0};return k.type==="array"?fl(P[k.value]||Ts,k.length):P[k.type]}(l):void 0,void 0,void 0,u,p,x),T=b.parse(h,void 0,void 0,void 0,l&&l.type==="string"?{typeAnnotation:"coerce"}:void 0);return T?eP(new sw(T,l,u,p,x)):tm(b.errors)}class yy{constructor(l,u,p,x){this.kind=l,this._styleExpression=u,this.isLightConstant=p,this.isLineProgressConstant=x,this.isStateDependent=l!=="constant"&&!dy(u.expression),this.configDependencies=ew(u.expression),this.isIndoorDependent=tw(u.expression)}evaluateWithoutErrorHandling(l,u,p,x,b,T){return this._styleExpression.evaluateWithoutErrorHandling(l,u,p,x,b,T)}evaluate(l,u,p,x,b,T,k){return this._styleExpression.evaluate(l,u,p,x,b,T,void 0,void 0,k)}}class Np{constructor(l,u,p,x,b,T){this.kind=l,this.zoomStops=p,this._styleExpression=u,this.isStateDependent=l!=="camera"&&!dy(u.expression),this.isIndoorDependent=tw(u.expression),this.isLightConstant=b,this.isLineProgressConstant=T,this.configDependencies=ew(u.expression),this.interpolationType=x}evaluateWithoutErrorHandling(l,u,p,x,b,T){return this._styleExpression.evaluateWithoutErrorHandling(l,u,p,x,b,T)}evaluate(l,u,p,x,b,T){return this._styleExpression.evaluate(l,u,p,x,b,T)}interpolationFactor(l,u,p){return this.interpolationType?Xo.interpolationFactor(this.interpolationType,l,u,p):0}}function vE(h,l,u,p,x){if((h=rm(h,l,u,p,x)).result==="error")return h;const b=h.value.expression,T=kp(b);if(!T&&!rw(l))return tm([new Lu("","data expressions not supported")]);const k=Qd(b,["zoom","pitch","distance-from-center"]);if(!k&&!yE(l))return tm([new Lu("","zoom expressions not supported")]);const P=Qd(b,["measure-light"]);if(!P&&!tP(l))return tm([new Lu("","measure-light expression not supported")]);const O=Qd(b,["line-progress"]);if(!O&&!function(G){return lv(G.expression,"line-progress")}(l))return tm([new Lu("","line-progress expression not supported")]);const $=l.expression&&l.expression.relaxZoomRestriction,V=pd(b);return V||k||$?V instanceof Lu?tm([V]):V instanceof Xo&&!nw(l)?tm([new Lu("",'"interpolate" expressions cannot be used with this property')]):eP(V?new Np(T&&O?"camera":"composite",h.value,V.labels,V instanceof Xo?V.interpolation:void 0,P,O):new yy(T&&O?"constant":"source",h.value,P,O)):tm([new Lu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class iw{constructor(l,u){this._parameters=l,this._specification=u,Object.assign(this,nP(this._parameters,this._specification))}static deserialize(l){return new iw(l._parameters,l._specification)}static serialize(l){return{_parameters:l._parameters,_specification:l._specification}}}function pd(h){let l=null;if(h instanceof Wb)l=pd(h.result);else if(h instanceof rv){for(const u of h.args)if(l=pd(u),l)break}else(h instanceof J0||h instanceof Xo)&&h.input instanceof Ya&&h.input.name==="zoom"&&(l=h);return l instanceof Lu||h.eachChild(u=>{const p=pd(u);p instanceof Lu?l=p:l&&p&&l!==p&&(l=new Lu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),l}var _E,aP,uv=function(){if(aP)return _E;aP=1,_E=l;var h=3;function l(u,p,x){var b=this.cells=[];if(u instanceof ArrayBuffer){this.arrayBuffer=u;var T=new Int32Array(this.arrayBuffer);u=T[0],this.d=(p=T[1])+2*(x=T[2]);for(var k=0;k=G[te+0]&&b>=G[te+1])?(P[X]=!0,k.push(V[X])):P[X]=!1}}},l.prototype._forEachCell=function(u,p,x,b,T,k,P,O){for(var $=this._convertToCellCoord(u),V=this._convertToCellCoord(p),G=this._convertToCellCoord(x),Y=this._convertToCellCoord(b),X=$;X<=G;X++)for(var te=V;te<=Y;te++){var se=this.d*te+X;if((!O||O(this._convertFromCellCoord(X),this._convertFromCellCoord(te),this._convertFromCellCoord(X+1),this._convertFromCellCoord(te+1)))&&T.call(this,u,p,x,b,se,k,P,O))return}},l.prototype._convertFromCellCoord=function(u){return(u-this.padding)/this.scale},l.prototype._convertToCellCoord=function(u){return Math.max(0,Math.min(this.d-1,Math.floor(u*this.scale)+this.padding))},l.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var u=this.cells,p=h+this.cells.length+1+1,x=0,b=0;b=0||(x[b]=qh(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 p!=="Object"&&(x.$name=p),x}throw new Error("can't serialize object of type "+typeof h)}function nm(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||dv(h)||h instanceof ImageBitmap||ArrayBuffer.isView(h)||h instanceof ImageData)return h;if(Array.isArray(h))return h.map(nm);if(typeof h=="object"){const l=h.$name||"Object";if(l==="Map"){const x=h.entries||[],b=new Map;for(let T=0;Th>=1536&&h<=1791,aw=h=>h>=1872&&h<=1919,ow=h=>h>=2208&&h<=2303,lw=h=>h>=11904&&h<=12031,Gh=h=>h>=12032&&h<=12255,bE=h=>h>=12272&&h<=12287,hv=h=>h>=12288&&h<=12351,fv=h=>h>=12352&&h<=12447,Ip=h=>h>=12448&&h<=12543,wE=h=>h>=12544&&h<=12591,cw=h=>h>=12704&&h<=12735,eh=h=>h>=12736&&h<=12783,lP=h=>h>=12784&&h<=12799,cP=h=>h>=12800&&h<=13055,uP=h=>h>=13056&&h<=13311,SE=h=>h>=13312&&h<=19903,uw=h=>h>=19968&&h<=40959,mv=h=>h>=40960&&h<=42127,TE=h=>h>=42128&&h<=42191,jE=h=>h>=44032&&h<=55215,dw=h=>h>=63744&&h<=64255,EE=h=>h>=64336&&h<=65023,dP=h=>h>=65040&&h<=65055,kE=h=>h>=65072&&h<=65103,hP=h=>h>=65104&&h<=65135,AE=h=>h>=65136&&h<=65279,NE=h=>h>=65280&&h<=65519;function CE(h){for(const l of h)if(IE(l.charCodeAt(0)))return!0;return!1}function TB(h){for(const l of h)if(!jB(l.charCodeAt(0)))return!1;return!0}function jB(h){return!(oP(h)||aw(h)||ow(h)||EE(h)||AE(h))}function EB(h){return!(h<11904||!(cw(h)||wE(h)||kE(h)||dw(h)||uP(h)||lw(h)||eh(h)||hv(h)||SE(h)||uw(h)||cP(h)||NE(h)||fv(h)||bE(h)||Gh(h)||lP(h)||Ip(h)||dP(h)||TE(h)||mv(h)))}function IE(h){return!(h!==746&&h!==747&&(h<4352||!(cw(h)||wE(h)||kE(h)&&!(h>=65097&&h<=65103)||dw(h)||uP(h)||lw(h)||eh(h)||!(!hv(h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||SE(h)||uw(h)||cP(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)||jE(h)||fv(h)||bE(h)||(l=>l>=12688&&l<=12703)(h)||Gh(h)||lP(h)||Ip(h)&&h!==12540||!(!NE(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)||!(!hP(h)||h>=65112&&h<=65118||h>=65123&&h<=65126)||(l=>l>=5120&&l<=5759)(h)||(l=>l>=6320&&l<=6399)(h)||dP(h)||(l=>l>=19904&&l<=19967)(h)||mv(h)||TE(h))))}function fP(h){return h===12312||h===12313||h===12316||h===12540||h===12448}function Pp(h){return!(IE(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)||hv(l)||Ip(l)||(u=>u>=57344&&u<=63743)(l)||kE(l)||hP(l)||NE(l)||l===8734||l===8756||l===8757||l>=9984&&l<=10087||l>=10102&&l<=10131||l===65532||l===65533)}(h))}function mP(h){return oP(h)||aw(h)||ow(h)||EE(h)||AE(h)}function PE(h){return h>=1424&&h<=2303||EE(h)||AE(h)}function hw(h,l){return!(!l&&PE(h)||h>=2304&&h<=3583||h>=3840&&h<=4255||(u=>u>=6016&&u<=6143)(h))}function kB(h){for(const l of h)if(PE(l.charCodeAt(0)))return!0;return!1}const jc={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let th=null,ml=jc.unavailable,Yc=null;const pP=function(h){h&&typeof h=="string"&&h.indexOf("NetworkError")>-1&&(ml=jc.error),th&&th(h)};function RE(){LE.fire(new ud("pluginStateChange",{pluginStatus:ml,pluginURL:Yc}))}const LE=new F0,ME=function(){return ml},gP=function(){if(ml!==jc.deferred||!Yc)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");ml=jc.loading,RE(),Yc&&ey({url:Yc},h=>{h?pP(h):(ml=jc.loaded,RE())})},Hh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>ml===jc.loaded||Hh.applyArabicShaping!=null,isLoading:()=>ml===jc.loading,setState(h){ml=h.pluginStatus,Yc=h.pluginURL},isParsing:()=>ml===jc.parsing,isParsed:()=>ml===jc.parsed,getPluginURL:()=>Yc},yP=function(){Hh.isLoading()||Hh.isLoaded()||ME()!=="deferred"||gP()};class fs{constructor(l,u){this.zoom=l,u?(this.now=u.now,this.fadeDuration=u.fadeDuration,this.transition=u.transition,this.pitch=u.pitch,this.brightness=u.brightness,this.worldview=u.worldview,this.activeFloors=u.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(l){return function(u,p){for(const x of u)if(!hw(x.charCodeAt(0),p))return!1;return!0}(l,Hh.isLoaded())}}class vy{constructor(l,u,p,x,b){this.property=l,this.value=u,this.expression=function(T,k,P,O,$){if(xE(T))return new iw(T,k);if(cv(T)||Array.isArray(T)&&T.length>0){const V=vE(T,k,P,O,$);if(V.result==="error")throw new Error(V.value.map(G=>`${G.key}: ${G.message}`).join(", "));return V.value}{let V=T;return typeof T=="string"&&k.type==="color"&&(V=as.parse(T)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>V}}}(u===void 0?l.specification.default:u,l.specification,p,x,b)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(l,u,p,x){return this.property.possiblyEvaluate(this,l,u,p,x)}}class fw{constructor(l,u,p,x){this.property=l,this.value=new vy(l,void 0,u,p,x)}transitioned(l,u){return new _y(this.property,this.value,u,Object.assign({},l.transition,this.transition),l.now)}untransitioned(){return new _y(this.property,this.value,null,{},0)}}class mw{constructor(l,u,p,x){this._properties=l,this._values=Object.create(l.defaultTransitionablePropertyValues),this._scope=u,this._options=p,this._iconImageUseTheme=x,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(l){return gr(this._values[l].value.value)}setValue(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new fw(this._values[l].property,this._scope,this._options,this._iconImageUseTheme)),this._values[l].value=new vy(this._values[l].property,u===null?void 0:gr(u),this._scope,this._options,this._iconImageUseTheme),this._values[l].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[l].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[l].value.isIndoorDependent())}setTransitionOrValue(l,u){u&&(this._options=u);const p=this._properties.properties;if(l)for(const x in l){const b=l[x];if(x.endsWith("-transition")){const T=x.slice(0,-11);p[T]&&this.setTransition(T,b)}else p.hasOwnProperty(x)&&this.setValue(x,b)}}getTransition(l){return gr(this._values[l].transition)}setTransition(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new fw(this._values[l].property)),this._values[l].transition=gr(u)||void 0}serialize(){const l={};for(const u of Object.keys(this._values)){const p=this.getValue(u);p!==void 0&&(l[u]=p);const x=this.getTransition(u);x!==void 0&&(l[`${u}-transition`]=x)}return l}transitioned(l,u){const p=new DE(this._properties);for(const x of Object.keys(this._values))p._values[x]=this._values[x].transitioned(l,u._values[x]);return p}untransitioned(){const l=new DE(this._properties);for(const u of Object.keys(this._values))l._values[u]=this._values[u].untransitioned();return l}isIndoorDependent(){return this._isIndoorDependent}}class _y{constructor(l,u,p,x,b){const T=x.delay||0,k=x.duration||0;b=b||0,this.property=l,this.value=u,this.begin=b+T,this.end=this.begin+k,l.specification.transition&&(x.delay||x.duration)&&(this.prior=p)}possiblyEvaluate(l,u,p){const x=l.now||0,b=this.value.possiblyEvaluate(l,u,p),T=this.prior;if(T){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 xP(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function pw(h){if(Array.isArray(h))return h.map(pw);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const l={};for(const u in h)l[u]=pw(h[u]);return l}return xP(h)}function FE(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(!FE(l)&&typeof l!="boolean")return!1;return!0;default:return!0}}function gw(h,l="",u=null,p="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};FE(h)||(h=yw(h));const x=h;let b=!0;try{b=function($){if(!wy($))return $;let V=pw($);return _P(V),V=vP(V),V}(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 T=null,k=null;if(p!=="background"&&p!=="sky"&&p!=="slot"){k=at[`filter_${p}`];const $=rm(b,k,l,u);if($.result==="error")throw new Error($.value.map(V=>`${V.key}: ${V.message}`).join(", "));T=(V,G,Y)=>$.value.evaluate(V,G,{},Y)}let P=null,O=null;if(b!==x){const $=rm(x,k,l,u);if($.result==="error")throw new Error($.value.map(V=>`${V.key}: ${V.message}`).join(", "));P=(V,G,Y,X,te)=>$.value.evaluate(V,G,{},Y,void 0,void 0,X,te),O=!kp($.value.expression)}return{filter:T,dynamicFilter:P||void 0,needGeometry:wP(b),needFeature:!!O}}function vP(h){if(!Array.isArray(h))return h;const l=function(u){if(bP.has(u[0])){for(let p=1;pvP(u))}function _P(h){let l=!1;const u=[];if(h[0]==="case"){for(let p=1;p",">=","<","<=","to-boolean"]);function AB(h,l){return hl?1:0}function wP(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let l=1;l"||l==="<="||l===">="?xw(h[1],h[2],l):l==="any"?(u=h.slice(1),["any"].concat(u.map(yw))):l==="all"?["all"].concat(h.slice(1).map(yw)):l==="none"?["all"].concat(h.slice(1).map(yw).map(pv)):l==="in"?BE(h[1],h.slice(2)):l==="!in"?pv(BE(h[1],h.slice(2))):l==="has"?Kh(h[1]):l!=="!has"||pv(Kh(h[1]));var u}function xw(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 BE(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(AB)]]:["filter-in-small",h,["literal",l]]}}function Kh(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function pv(h){return["!",h]}const gv="";function Lp(h,l){return l?`${h}${gv}${l}`:h}function SP(h){const l=h.indexOf(gv);return l>=0?h.slice(l+1):""}let TP;const $E=()=>TP||(TP=new fi({"icon-size":new Qt(at.layout_symbol["icon-size"]),"icon-image":new Qt(at.layout_symbol["icon-image"]),"icon-rotate":new Qt(at.layout_symbol["icon-rotate"]),"icon-offset":new Qt(at.layout_symbol["icon-offset"]),"text-size":new Qt(at.layout_symbol["text-size"]),"text-rotate":new Qt(at.layout_symbol["text-rotate"]),"text-offset":new Qt(at.layout_symbol["text-offset"])}));let zE;const UE=()=>zE||(zE=new fi({"icon-opacity":new Qt(at.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qt(at.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qt(at.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qt(at.paint_symbol["text-emissive-strength"]),"icon-color":new Qt(at.paint_symbol["icon-color"]),"icon-halo-color":new Qt(at.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qt(at.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qt(at.paint_symbol["icon-halo-blur"]),"icon-translate":new Qt(at.paint_symbol["icon-translate"]),"text-opacity":new Qt(at.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qt(at.paint_symbol["text-occlusion-opacity"]),"text-color":new Qt(at.paint_symbol["text-color"],{runtimeType:Ml,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new Qt(at.paint_symbol["text-halo-color"]),"text-halo-width":new Qt(at.paint_symbol["text-halo-width"]),"text-halo-blur":new Qt(at.paint_symbol["text-halo-blur"]),"text-translate":new Qt(at.paint_symbol["text-translate"]),"symbol-z-offset":new Qt(at.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 NB{constructor(l,u,p,x,b,T){this._conditionSpec=l,this._propertiesSpec=p;const k=rm(l,at.appearance.condition);if(k.result==="success"&&(this.condition=k.value),this.name=u,p){this.layoutProperties=new Wh($E()),this.unevaluatedLayout=new OE($E(),x,b,T),this.paintProperties=new Wh(UE()),this.unevaluatedPaint=new OE(UE(),x,b,"");for(const P in p)P in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(P,p[P]):P in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(P,p[P])}}isActive(l){return!(this.condition||!l.isHidden||this.name!=="hidden")||this.condition.evaluate(l.globals,l.feature,l.featureState,l.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(l){return this.layoutProperties.get(l)}getPaintProperty(l){return this.paintProperties.get(l)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(l){return this.unevaluatedLayout._values[l]}getUnevaluatedPaintProperty(l){return this.unevaluatedPaint._values[l]}recalculate(l,u,p){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(l,void 0,u,p)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(l,void 0,u,""))}serialize(){const l={};l.condition=this.condition.expression.serialize(),this.name&&(l.name=this.name);const u=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},p=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},x=Object.assign({},u,p);return Object.keys(x).length>0&&(l.properties=x),l}hasIconLayoutProperties(){const l=this.hasLayoutProperty("icon-image"),u=this.hasLayoutProperty("icon-size"),p=this.hasLayoutProperty("icon-offset"),x=this.hasLayoutProperty("icon-rotate");return l||u||p||x}hasTextLayoutProperties(){const l=this.hasLayoutProperty("text-size"),u=this.hasLayoutProperty("text-offset"),p=this.hasLayoutProperty("text-rotate");return l||u||p}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("icon-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("text-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasLayoutProperty(l){return this.unevaluatedLayout&&this.unevaluatedLayout._values[l].value!==void 0}hasPaintProperty(l){return this.unevaluatedPaint&&this.unevaluatedPaint._values[l].value!==void 0}}const VE="-transition",CB=new Set(["fill","line","background","hillshade","raster"]);class pl extends F0{constructor(l,u,p,x,b,T){if(super(),this.id=l.id,this.fqid=Lp(this.id,p),this.type=l.type,this.scope=p,this.lut=x,this.options=b,this.iconImageUseTheme=T,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},l.type!=="custom"){if(this.metadata=l.metadata,this.minzoom=l.minzoom,this.maxzoom=l.maxzoom,l.type&&l.type!=="background"&&l.type!=="sky"&&l.type!=="slot"){this.source=l.source,this.sourceLayer=l["source-layer"],this.filter=l.filter;const k=rm(this.filter,at[`filter_${l.type}`]);k.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.value.isIndoorDependent)}if(l.slot&&(this.slot=l.slot),l.appearances&&this.setAppearances(l.appearances),u.layout&&(this._unevaluatedLayout=new OE(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 mw(u.paint,this.scope,b);for(const k in l.paint)this.setPaintProperty(k,l.paint[k]);for(const k in l.layout)this.setLayoutProperty(k,l.layout[k]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Wh(u.paint)}}}onAdd(l){}onRemove(l){}isDraped(l){return!this.is3D(!0)&&CB.has(this.type)}getLayoutProperty(l){return l==="visibility"?this.visibility:this._unevaluatedLayout.getValue(l)}setLayoutProperty(l,u){if(this.type==="custom"&&l==="visibility")return void(this.visibility=u);const p=this._unevaluatedLayout;p._properties.properties[l]&&(p.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),l==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(l){this.appearances=[],l.forEach(u=>{this.appearances.push(new NB(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 p=this._transitionablePaint,x=p._properties.properties;if(l.endsWith(VE)){const V=l.slice(0,-11);return x[V]&&p.setTransition(V,u||void 0),!1}if(!x[l])return!1;const b=p._values[l],T=b.value.isDataDriven(),k=b.value;p.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(l);const P=p._values[l].value,O=P.isDataDriven(),$=l.endsWith("pattern")||l==="line-dasharray";return O||T||$||this._handleOverridablePaintPropertyUpdate(l,k,P)}_handleSpecialPaintPropertyUpdate(l){}getProgramIds(){return null}getDefaultProgramParams(l,u,p){return null}_handleOverridablePaintPropertyUpdate(l,u,p){return!1}isHidden(l){return!!(this.minzoom&&l=this.maxzoom)||this.visibility==="none"}updateTransitions(l){this._transitioningPaint=this._transitionablePaint.transitioned(l,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(l,u){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(l,void 0,u,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(l,void 0,u)}serialize(){const l={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(l.appearances=this.appearances.map(u=>u.serialize())),Mt(l,(u,p)=>!(u===void 0||p==="layout"&&!Object.keys(u).length||p==="paint"&&!Object.keys(u).length))}is3D(l){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const l in this.paint._values){const u=this.paint.get(l);if(u instanceof Rp&&rw(u.property.specification)&&(u.value.kind==="source"||u.value.kind==="composite")&&u.value.isStateDependent)return!0}for(const l of this.appearances)if(!dy(l.condition.expression))return!0;return!1}compileFilter(l){this._filterCompiled||(this._featureFilter=gw(this.filter,this.scope,l),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(l){this._stats&&(l.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(l,u,p){return{}}queryRadius(l){}queryIntersectsFeature(l,u,p,x,b,T,k,P,O,$){}}const vw={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class yv{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 IB=new ArrayBuffer(0);class Xs{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=IB),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 On(h,l=1){let u=0,p=0;return{members:h.map(x=>{const b=vw[x.type].BYTES_PER_ELEMENT,T=u=jP(u,Math.max(l,b)),k=x.components||1;return p=Math.max(p,b),u+=b*k,{name:x.name,type:x.type,components:k,offset:T}}),size:jP(u,Math.max(p,l)),alignment:l}}function jP(h,l){return Math.ceil(h/l)*l}class Ec extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const x=2*l;return this.int16[x+0]=u,this.int16[x+1]=p,l}}Ec.prototype.bytesPerElement=4,jr(Ec,"StructArrayLayout2i4");class rh extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,p)}emplace(l,u,p,x){const b=3*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.int16[b+2]=x,l}}rh.prototype.bytesPerElement=6,jr(rh,"StructArrayLayout3i6");class Mo extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,x)}emplace(l,u,p,x,b){const T=4*l;return this.int16[T+0]=u,this.int16[T+1]=p,this.uint16[T+2]=x,this.uint16[T+3]=b,l}}Mo.prototype.bytesPerElement=8,jr(Mo,"StructArrayLayout2i2ui8");class Zc extends Xs{_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}}Zc.prototype.bytesPerElement=4,jr(Zc,"StructArrayLayout1f4");class qE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,p)}emplace(l,u,p,x){const b=4*l,T=2*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.float32[T+1]=x,l}}qE.prototype.bytesPerElement=8,jr(qE,"StructArrayLayout2i1f8");class GE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,p)}emplace(l,u,p,x){const b=4*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.int16[b+2]=x,l}}GE.prototype.bytesPerElement=8,jr(GE,"StructArrayLayout3i8");class HE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,x)}emplace(l,u,p,x,b){const T=4*l;return this.int16[T+0]=u,this.int16[T+1]=p,this.int16[T+2]=x,this.int16[T+3]=b,l}}HE.prototype.bytesPerElement=8,jr(HE,"StructArrayLayout4i8");class WE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b){const T=this.length;return this.resize(T+1),this.emplace(T,l,u,p,x,b)}emplace(l,u,p,x,b,T){const k=5*l;return this.int16[k+0]=u,this.int16[k+1]=p,this.int16[k+2]=x,this.int16[k+3]=b,this.int16[k+4]=T,l}}WE.prototype.bytesPerElement=10,jr(WE,"StructArrayLayout5i10");class xv extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k){const P=this.length;return this.resize(P+1),this.emplace(P,l,u,p,x,b,T,k)}emplace(l,u,p,x,b,T,k,P){const O=6*l,$=12*l,V=3*l;return this.int16[O+0]=u,this.int16[O+1]=p,this.uint8[$+4]=x,this.uint8[$+5]=b,this.uint8[$+6]=T,this.uint8[$+7]=k,this.float32[V+2]=P,l}}xv.prototype.bytesPerElement=12,jr(xv,"StructArrayLayout2i4ub1f12");class Ou extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,p)}emplace(l,u,p,x){const b=3*l;return this.float32[b+0]=u,this.float32[b+1]=p,this.float32[b+2]=x,l}}Ou.prototype.bytesPerElement=12,jr(Ou,"StructArrayLayout3f12");class nh extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b){const T=this.length;return this.resize(T+1),this.emplace(T,l,u,p,x,b)}emplace(l,u,p,x,b,T){const k=6*l,P=3*l;return this.uint16[k+0]=u,this.uint16[k+1]=p,this.uint16[k+2]=x,this.uint16[k+3]=b,this.float32[P+2]=T,l}}nh.prototype.bytesPerElement=12,jr(nh,"StructArrayLayout4ui1f12");class Sy extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,x)}emplace(l,u,p,x,b){const T=4*l;return this.uint16[T+0]=u,this.uint16[T+1]=p,this.uint16[T+2]=x,this.uint16[T+3]=b,l}}Sy.prototype.bytesPerElement=8,jr(Sy,"StructArrayLayout4ui8");class _w extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,x,b,T)}emplace(l,u,p,x,b,T,k){const P=6*l;return this.int16[P+0]=u,this.int16[P+1]=p,this.int16[P+2]=x,this.int16[P+3]=b,this.int16[P+4]=T,this.int16[P+5]=k,l}}_w.prototype.bytesPerElement=12,jr(_w,"StructArrayLayout6i12");class KE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V,G){const Y=this.length;return this.resize(Y+1),this.emplace(Y,l,u,p,x,b,T,k,P,O,$,V,G)}emplace(l,u,p,x,b,T,k,P,O,$,V,G,Y){const X=12*l;return this.int16[X+0]=u,this.int16[X+1]=p,this.int16[X+2]=x,this.int16[X+3]=b,this.uint16[X+4]=T,this.uint16[X+5]=k,this.uint16[X+6]=P,this.uint16[X+7]=O,this.int16[X+8]=$,this.int16[X+9]=V,this.int16[X+10]=G,this.int16[X+11]=Y,l}}KE.prototype.bytesPerElement=24,jr(KE,"StructArrayLayout4i4ui4i24");class YE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,x,b,T)}emplace(l,u,p,x,b,T,k){const P=10*l,O=5*l;return this.int16[P+0]=u,this.int16[P+1]=p,this.int16[P+2]=x,this.float32[O+2]=b,this.float32[O+3]=T,this.float32[O+4]=k,l}}YE.prototype.bytesPerElement=20,jr(YE,"StructArrayLayout3i3f20");class Yh extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,x)}emplace(l,u,p,x,b){const T=4*l;return this.float32[T+0]=u,this.float32[T+1]=p,this.float32[T+2]=x,this.float32[T+3]=b,l}}Yh.prototype.bytesPerElement=16,jr(Yh,"StructArrayLayout4f16");class vv extends Xs{_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}}vv.prototype.bytesPerElement=4,jr(vv,"StructArrayLayout1ul4");class Fu extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const x=2*l;return this.uint16[x+0]=u,this.uint16[x+1]=p,l}}Fu.prototype.bytesPerElement=4,jr(Fu,"StructArrayLayout2ui4");class bw extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V,G,Y){const X=this.length;return this.resize(X+1),this.emplace(X,l,u,p,x,b,T,k,P,O,$,V,G,Y)}emplace(l,u,p,x,b,T,k,P,O,$,V,G,Y,X){const te=20*l,se=10*l;return this.int16[te+0]=u,this.int16[te+1]=p,this.int16[te+2]=x,this.int16[te+3]=b,this.int16[te+4]=T,this.float32[se+3]=k,this.float32[se+4]=P,this.float32[se+5]=O,this.float32[se+6]=$,this.int16[te+14]=V,this.uint32[se+8]=G,this.uint16[te+18]=Y,this.uint16[te+19]=X,l}}bw.prototype.bytesPerElement=40,jr(bw,"StructArrayLayout5i4f1i1ul2ui40");class _v extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k){const P=this.length;return this.resize(P+1),this.emplace(P,l,u,p,x,b,T,k)}emplace(l,u,p,x,b,T,k,P){const O=8*l;return this.int16[O+0]=u,this.int16[O+1]=p,this.int16[O+2]=x,this.int16[O+4]=b,this.int16[O+5]=T,this.int16[O+6]=k,this.int16[O+7]=P,l}}_v.prototype.bytesPerElement=16,jr(_v,"StructArrayLayout3i2i2i16");class ZE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b){const T=this.length;return this.resize(T+1),this.emplace(T,l,u,p,x,b)}emplace(l,u,p,x,b,T){const k=4*l,P=8*l;return this.float32[k+0]=u,this.float32[k+1]=p,this.float32[k+2]=x,this.int16[P+6]=b,this.int16[P+7]=T,l}}ZE.prototype.bytesPerElement=16,jr(ZE,"StructArrayLayout2f1f2i16");class bv extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,x,b,T)}emplace(l,u,p,x,b,T,k){const P=20*l,O=5*l;return this.uint8[P+0]=u,this.uint8[P+1]=p,this.float32[O+1]=x,this.float32[O+2]=b,this.float32[O+3]=T,this.float32[O+4]=k,l}}bv.prototype.bytesPerElement=20,jr(bv,"StructArrayLayout2ub4f20");class Pi extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,p)}emplace(l,u,p,x){const b=3*l;return this.uint16[b+0]=u,this.uint16[b+1]=p,this.uint16[b+2]=x,l}}Pi.prototype.bytesPerElement=6,jr(Pi,"StructArrayLayout3ui6");class ww extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae){const Ie=this.length;return this.resize(Ie+1),this.emplace(Ie,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae)}emplace(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae,Ie){const We=30*l,ze=15*l,He=60*l;return this.int16[We+0]=u,this.int16[We+1]=p,this.int16[We+2]=x,this.float32[ze+2]=b,this.float32[ze+3]=T,this.uint16[We+8]=k,this.uint16[We+9]=P,this.uint32[ze+5]=O,this.uint32[ze+6]=$,this.uint32[ze+7]=V,this.uint16[We+16]=G,this.uint16[We+17]=Y,this.uint16[We+18]=X,this.float32[ze+10]=te,this.float32[ze+11]=se,this.uint8[He+48]=ae,this.uint8[He+49]=fe,this.uint8[He+50]=ue,this.uint32[ze+13]=Te,this.int16[We+28]=Ae,this.uint8[He+58]=Ie,l}}ww.prototype.bytesPerElement=60,jr(ww,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class XE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae,Ie,We,ze,He,Ve,qe,bt,Et,It,Dt,Pt,Ht){const vt=this.length;return this.resize(vt+1),this.emplace(vt,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae,Ie,We,ze,He,Ve,qe,bt,Et,It,Dt,Pt,Ht)}emplace(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae,Ie,We,ze,He,Ve,qe,bt,Et,It,Dt,Pt,Ht,vt){const Rt=20*l,Bt=40*l,Yt=80*l;return this.float32[Rt+0]=u,this.float32[Rt+1]=p,this.int16[Bt+4]=x,this.int16[Bt+5]=b,this.int16[Bt+6]=T,this.int16[Bt+7]=k,this.int16[Bt+8]=P,this.int16[Bt+9]=O,this.int16[Bt+10]=$,this.int16[Bt+11]=V,this.int16[Bt+12]=G,this.uint16[Bt+13]=Y,this.uint16[Bt+14]=X,this.uint16[Bt+15]=te,this.uint16[Bt+16]=se,this.uint16[Bt+17]=ae,this.uint16[Bt+18]=fe,this.uint16[Bt+19]=ue,this.uint16[Bt+20]=Te,this.uint16[Bt+21]=Ae,this.uint16[Bt+22]=Ie,this.uint16[Bt+23]=We,this.uint16[Bt+24]=ze,this.uint16[Bt+25]=He,this.uint16[Bt+26]=Ve,this.uint16[Bt+27]=qe,this.uint32[Rt+14]=bt,this.float32[Rt+15]=Et,this.float32[Rt+16]=It,this.float32[Rt+17]=Dt,this.float32[Rt+18]=Pt,this.uint8[Yt+76]=Ht,this.uint16[Bt+39]=vt,l}}XE.prototype.bytesPerElement=80,jr(XE,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Sw extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,x,b,T)}emplace(l,u,p,x,b,T,k){const P=6*l;return this.float32[P+0]=u,this.float32[P+1]=p,this.float32[P+2]=x,this.float32[P+3]=b,this.float32[P+4]=T,this.float32[P+5]=k,l}}Sw.prototype.bytesPerElement=24,jr(Sw,"StructArrayLayout6f24");class Mp extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b){const T=this.length;return this.resize(T+1),this.emplace(T,l,u,p,x,b)}emplace(l,u,p,x,b,T){const k=5*l;return this.float32[k+0]=u,this.float32[k+1]=p,this.float32[k+2]=x,this.float32[k+3]=b,this.float32[k+4]=T,l}}Mp.prototype.bytesPerElement=20,jr(Mp,"StructArrayLayout5f20");class wv extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k){const P=this.length;return this.resize(P+1),this.emplace(P,l,u,p,x,b,T,k)}emplace(l,u,p,x,b,T,k,P){const O=7*l;return this.float32[O+0]=u,this.float32[O+1]=p,this.float32[O+2]=x,this.float32[O+3]=b,this.float32[O+4]=T,this.float32[O+5]=k,this.float32[O+6]=P,l}}wv.prototype.bytesPerElement=28,jr(wv,"StructArrayLayout7f28");class QE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V){const G=this.length;return this.resize(G+1),this.emplace(G,l,u,p,x,b,T,k,P,O,$,V)}emplace(l,u,p,x,b,T,k,P,O,$,V,G){const Y=11*l;return this.float32[Y+0]=u,this.float32[Y+1]=p,this.float32[Y+2]=x,this.float32[Y+3]=b,this.float32[Y+4]=T,this.float32[Y+5]=k,this.float32[Y+6]=P,this.float32[Y+7]=O,this.float32[Y+8]=$,this.float32[Y+9]=V,this.float32[Y+10]=G,l}}QE.prototype.bytesPerElement=44,jr(QE,"StructArrayLayout11f44");class JE extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O){const $=this.length;return this.resize($+1),this.emplace($,l,u,p,x,b,T,k,P,O)}emplace(l,u,p,x,b,T,k,P,O,$){const V=9*l;return this.float32[V+0]=u,this.float32[V+1]=p,this.float32[V+2]=x,this.float32[V+3]=b,this.float32[V+4]=T,this.float32[V+5]=k,this.float32[V+6]=P,this.float32[V+7]=O,this.float32[V+8]=$,l}}JE.prototype.bytesPerElement=36,jr(JE,"StructArrayLayout9f36");class Dp extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const x=2*l;return this.float32[x+0]=u,this.float32[x+1]=p,l}}Dp.prototype.bytesPerElement=8,jr(Dp,"StructArrayLayout2f8");class e2 extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,x)}emplace(l,u,p,x,b){const T=6*l;return this.uint32[3*l+0]=u,this.uint16[T+2]=p,this.uint16[T+3]=x,this.uint16[T+4]=b,l}}e2.prototype.bytesPerElement=12,jr(e2,"StructArrayLayout1ul3ui12");class Op extends Xs{_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}}Op.prototype.bytesPerElement=2,jr(Op,"StructArrayLayout1ui2");class t2 extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se){const ae=this.length;return this.resize(ae+1),this.emplace(ae,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se)}emplace(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae){const fe=16*l;return this.float32[fe+0]=u,this.float32[fe+1]=p,this.float32[fe+2]=x,this.float32[fe+3]=b,this.float32[fe+4]=T,this.float32[fe+5]=k,this.float32[fe+6]=P,this.float32[fe+7]=O,this.float32[fe+8]=$,this.float32[fe+9]=V,this.float32[fe+10]=G,this.float32[fe+11]=Y,this.float32[fe+12]=X,this.float32[fe+13]=te,this.float32[fe+14]=se,this.float32[fe+15]=ae,l}}t2.prototype.bytesPerElement=64,jr(t2,"StructArrayLayout16f64");class Tw extends Xs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,x,b,T,k){const P=this.length;return this.resize(P+1),this.emplace(P,l,u,p,x,b,T,k)}emplace(l,u,p,x,b,T,k,P){const O=10*l,$=5*l;return this.uint16[O+0]=u,this.uint16[O+1]=p,this.uint16[O+2]=x,this.uint16[O+3]=b,this.float32[$+2]=T,this.float32[$+3]=k,this.float32[$+4]=P,l}}Tw.prototype.bytesPerElement=20,jr(Tw,"StructArrayLayout4ui3f20");class jw extends Xs{_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}}jw.prototype.bytesPerElement=2,jr(jw,"StructArrayLayout1i2");class Ew extends Xs{_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}}Ew.prototype.bytesPerElement=1,jr(Ew,"StructArrayLayout1ub1");class EP extends yv{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]}}EP.prototype.size=40;class r2 extends bw{get(l){return new EP(this,l)}}jr(r2,"CollisionBoxArray");class kP extends yv{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}}kP.prototype.size=60;class AP extends ww{get(l){return new kP(this,l)}}jr(AP,"PlacedSymbolArray");class Sv extends yv{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]}}Sv.prototype.size=80;class NP extends XE{get(l){return new Sv(this,l)}}jr(NP,"SymbolInstanceArray");class CP extends Zc{getoffsetX(l){return this.float32[1*l+0]}}jr(CP,"GlyphOffsetArray");class Tv extends Ec{getx(l){return this.int16[2*l+0]}gety(l){return this.int16[2*l+1]}}jr(Tv,"SymbolLineVertexArray");class IP extends yv{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]}}IP.prototype.size=12;class n2 extends e2{get(l){return new IP(this,l)}}jr(n2,"FeatureIndexArray");class PP extends Fu{geta_centroid_pos0(l){return this.uint16[2*l+0]}geta_centroid_pos1(l){return this.uint16[2*l+1]}}jr(PP,"FillExtrusionCentroidArray");class s2 extends yv{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]}}s2.prototype.size=6;class i2 extends rh{get(l){return new s2(this,l)}}jr(i2,"FillExtrusionWallArray");const RP=On([{name:"a_pos",components:2,type:"Int16"}],4),PB=On([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),RB=On([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Os{constructor(l=[]){this.segments=l}_prepareSegment(l,u,p,x,b){let T=this.segments[this.segments.length-1];return l>Os.MAX_VERTEX_ARRAY_LENGTH&&hr(`Max vertices per segment is ${Os.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${l}`),(!T||T.vertexLength+l>Os.MAX_VERTEX_ARRAY_LENGTH||T.sortKey!==x||b!==void 0&&T&&T.batchIndex!==void 0&&T.batchIndex!==b)&&(T={vertexOffset:u,primitiveOffset:p,vertexLength:0,primitiveLength:0},x!==void 0&&(T.sortKey=x),b!==void 0&&(T.batchIndex=b),this.segments.push(T)),T}prepareSegment(l,u,p,x,b){return this._prepareSegment(l,u.length,p.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,p,x){return new Os([{vertexOffset:l,primitiveOffset:u,vertexLength:p,primitiveLength:x,vaos:{},sortKey:0}])}}function kw(h,l){return 256*(h=pe(Math.floor(h),0,255))+pe(Math.floor(l),0,255)}Os.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,jr(Os,"SegmentVector");const LB=On([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),MB=On([{name:"a_pattern_b",components:4,type:"Uint16"}]),DB=On([{name:"a_dash",components:4,type:"Uint16"}]);class jv{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(l,u,p,x){this.ids.push(a2(l)),this.positions.push(u,p,x)}eachPosition(l,u){const p=a2(l);let x=0,b=this.ids.length-1;for(;x>1;this.ids[T]>=p?b=T:x=T+1}for(;this.ids[x]===p;)u(this.positions[3*x],this.positions[3*x+1],this.positions[3*x+2]),x++}static serialize(l,u){const p=new Float64Array(l.ids),x=new Uint32Array(l.positions);return Ev(p,x,0,p.length-1),u&&(u.add(p.buffer),u.add(x.buffer)),{ids:p,positions:x}}static deserialize(l){const u=new jv;let p;u.ids=l.ids,u.positions=l.positions;for(const x of u.ids)x!==p&&u.uniqueIds.push(x),p=x;return u.indexed=!0,u}}function a2(h){const l=+h;return Number.isSafeInteger(l)?l:Kf(String(h))}function Ev(h,l,u,p){for(;u>1];let b=u-1,T=p+1;for(;;){do b++;while(h[b]x);if(b>=T)break;Xc(h,b,T),Xc(l,3*b,3*T),Xc(l,3*b+1,3*T+1),Xc(l,3*b+2,3*T+2)}T-u`u_${b}`),this.type=p,this.context=x}setUniform(l,u,p,x,b){const T=x.constantOr(this.value);u.set(l,b,T instanceof as?T.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):T)}getBinding(l,u){return this.type==="color"?new FB(l):new wa(l)}}class U{constructor(l,u){this.uniformNames=u.map(p=>`u_${p}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(l,u){this.pixelRatio=l.pixelRatio||1,this.pattern=l.tl.concat(l.br),this.patternTransition=u?u.tl.concat(u.br):this.pattern}setUniform(l,u,p,x,b){let T=null;b!=="u_pattern"&&b!=="u_dash"||(T=this.pattern),b==="u_pattern_b"&&(T=this.patternTransition),b==="u_pixel_ratio"&&(T=this.pixelRatio),T&&u.set(l,b,T)}getBinding(l,u){return u==="u_pattern"||u==="u_pattern_b"||u==="u_dash"?new OB(l):new wa(l)}}class W{constructor(l,u,p,x){this.expression=l,this.type=p,this.maxValue=0,this.paintVertexAttributes=u.map(b=>({name:`a_${b}`,type:"Float32",components:p==="color"?2:1,offset:0})),this.paintVertexArray=new x}populatePaintArray(l,u,p,x,b,T,k,P){const O=this.paintVertexArray.length,$=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new fs(0,{brightness:T,worldview:P}),u,{},b,x,k):this.expression.kind==="constant"&&this.expression.value,V=L(this.lutExpression,u,{},x,b,T,k,P);this.paintVertexArray.resize(l),this._setPaintValue(O,l,$,V?null:this.context.lut)}updatePaintArray(l,u,p,x,b,T,k,P){const O=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:k,worldview:P},p,x,void 0,b):this.expression.kind==="constant"&&this.expression.value,$=L(this.lutExpression,p,x,b,void 0,k,void 0,P);this._setPaintValue(l,u,O,$?null:this.context.lut)}_setPaintValue(l,u,p,x){if(this.type==="color"){const b=R(p.toPremultipliedRenderColor(x));for(let T=l;T`u_${k}_t`),this.type=p,this.useIntegerZoom=x,this.context=b,this.maxValue=0,this.paintVertexAttributes=u.map(k=>({name:`a_${k}`,type:"Float32",components:p==="color"?4:2,offset:0})),this.paintVertexArray=new T}populatePaintArray(l,u,p,x,b,T,k,P){const O=this.expression.evaluate(new fs(this.context.zoom,{brightness:T,worldview:P}),u,{},b,x,k),$=this.expression.evaluate(new fs(this.context.zoom+1,{brightness:T,worldview:P}),u,{},b,x,k),V=L(this.lutExpression,u,{},x,b,T,k,P),G=this.paintVertexArray.length;this.paintVertexArray.resize(l),this._setPaintValue(G,l,O,$,V?null:this.context.lut)}updatePaintArray(l,u,p,x,b,T,k,P){const O=this.expression.evaluate({zoom:this.context.zoom,brightness:k,worldview:P},p,x,void 0,b),$=this.expression.evaluate({zoom:this.context.zoom+1,brightness:k,worldview:P},p,x,void 0,b),V=L(this.lutExpression,p,x,b,void 0,k,void 0,P);this._setPaintValue(l,u,O,$,V?null:this.context.lut)}_setPaintValue(l,u,p,x,b){if(this.type==="color"){const T=R(p.toPremultipliedRenderColor(b)),k=R(x.toPremultipliedRenderColor(b));for(let P=l;P!0){this.binders={},this._buffers=[],this.context=u;const x=[],b=l;for(const T in l.paint._values){const k=b.paint.get(T);if(T.endsWith("-use-theme")||!p(T)||!(k instanceof Rp&&rw(k.property.specification)))continue;const P=le(T,l.type),O=k.value,$=k.property.specification.type,V=!!k.property.useIntegerZoom,G=T==="line-dasharray"||T.endsWith("pattern"),Y=b.paint.get(`${T}-use-theme`),X=T==="line-dasharray"&&b.layout.get("line-cap").value.kind!=="constant"||Y&&Y.value.kind!=="constant";if(O.kind!=="constant"||X)if(O.kind==="source"||X||G){const te=Re(T,$,"source");this.binders[T]=G?new ne(O,P,$,te,l.id):new W(O,P,$,te),x.push(`/a_${T}`)}else{const te=Re(T,$,"composite");this.binders[T]=new Z(O,P,$,V,u,te),x.push(`/z_${T}`)}else this.binders[T]=G?new U(O.value,P):new B(O.value,P,$,u),x.push(`/u_${T}`);Y&&(this.binders[T].lutExpression=Y.value)}this.cacheKey=x.sort().join("")}getMaxValue(l){const u=this.binders[l];return u instanceof W||u instanceof Z?u.maxValue:0}populatePaintArrays(l,u,p,x,b,T,k,P){for(const O in this.binders){const $=this.binders[O];$.context=this.context,($ instanceof W||$ instanceof Z||$ instanceof ne)&&$.populatePaintArray(l,u,p,x,b,T,k,P)}}setConstantPatternPositions(l,u){for(const p in this.binders){const x=this.binders[p];x instanceof U&&x.setConstantPatternPositions(l,u)}}getPatternTransitionVertexBuffer(l){const u=this.binders[l];return u instanceof ne?u.paintTransitionVertexBuffer:null}updatePaintArrays(l,u,p,x,b,T,k,P,O,$){let V=!1;const G=Object.keys(l),Y=G.length!==0&&!P,X=Y?G:u.uniqueIds;this.context.lut=b.lut;for(const te in this.binders){const se=this.binders[te];if(se.context=this.context,(se instanceof W||se instanceof Z||se instanceof ne)&&se.expression&&se.expression.kind&&se.expression.kind!=="constant"&&(se.expression.isStateDependent===!0||se.expression.isLightConstant===!1)){const ae=b.paint.get(te);se.expression=ae.value;for(const fe of X){const ue=l[fe.toString()];u.eachPosition(fe,(Te,Ae,Ie)=>{const We=x.feature(Te);se.updatePaintArray(Ae,Ie,We,ue,T,k,O,$)})}if(!Y)for(const fe of p.uniqueIds){const ue=l[fe.toString()];p.eachPosition(fe,(Te,Ae,Ie)=>{const We=x.feature(Te);se.updatePaintArray(Ae,Ie,We,ue,T,k,O,$)})}V=!0}}return V}defines(){const l=[];for(const u in this.binders){const p=this.binders[u];(p instanceof B||p instanceof U)&&l.push(...p.uniformNames.map(x=>`#define HAS_UNIFORM_${x}`))}return l}getPaintVertexBuffers(){return this._buffers}getUniforms(l){const u=[];for(const p in this.binders){const x=this.binders[p];if(x instanceof B||x instanceof U||x instanceof Z)for(const b of x.uniformNames)u.push({name:b,property:p,binding:x.getBinding(l,b)})}return u}setUniforms(l,u,p,x,b){for(const{name:T,property:k,binding:P}of p)this.binders[k].setUniform(l,P,b,x.get(k),T)}updatePaintBuffers(){this._buffers=[];for(const l in this.binders){const u=this.binders[l];(u instanceof W||u instanceof Z||u instanceof ne)&&u.paintVertexBuffer&&this._buffers.push(u.paintVertexBuffer),u instanceof ne&&u.paintTransitionVertexBuffer&&this._buffers.push(u.paintTransitionVertexBuffer)}}upload(l){for(const u in this.binders){const p=this.binders[u];(p instanceof W||p instanceof Z||p instanceof ne)&&p.upload(l)}this.updatePaintBuffers()}destroy(){for(const l in this.binders){const u=this.binders[l];(u instanceof W||u instanceof Z||u instanceof ne)&&u.destroy()}}}class ie{constructor(l,u,p=()=>!0){this.programConfigurations={};for(const x of l)this.programConfigurations[x.id]=new re(x,u,p);this.needsUpload=!1,this._featureMap=new jv,this._featureMapWithoutIds=new jv,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(l,u,p,x,b,T,k,P,O){for(const $ in this.programConfigurations)this.programConfigurations[$].populatePaintArrays(l,u,x,b,T,k,P,O);u.id!==void 0?this._featureMap.add(u.id,p,this._bufferOffset,l):(this._featureMapWithoutIds.add(this._idlessCounter,p,this._bufferOffset,l),this._idlessCounter+=1),this._bufferOffset=l,this.needsUpload=!0}updatePaintArrays(l,u,p,x,b,T,k,P){for(const O of p)this.needsUpload=this.programConfigurations[O.id].updatePaintArrays(l,this._featureMap,this._featureMapWithoutIds,u,O,x,b,T,k||0,P)||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 ce={"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 le(h,l){return ce[h]||[h.replace(`${l}-`,"").replace(/-/g,"_")]}const be={"line-pattern":{source:nh,composite:nh},"fill-pattern":{source:nh,composite:nh},"fill-extrusion-pattern":{source:nh,composite:nh},"line-dasharray":{source:Sy,composite:Sy}},_e={color:{source:Dp,composite:Yh},number:{source:Zc,composite:Dp}};function Re(h,l,u){const p=be[h];return p&&p[u]||_e[l][u]}jr(B,"ConstantBinder"),jr(U,"PatternConstantBinder"),jr(W,"SourceExpressionBinder"),jr(ne,"PatternCompositeBinder"),jr(Z,"CompositeExpressionBinder"),jr(re,"ProgramConfiguration",{omit:["_buffers"]}),jr(ie,"ProgramConfigurationSet");const Me=fr/Math.PI/2,je=64,Xe=[je,32,16],$e=-Me,Ke=Me;function De(h,l,u,p=Me){return u=Xn(u),[h*Math.sin(u)*p,-l*p,h*Math.cos(u)*p]}function Be(h,l,u){return De(Math.cos(Xn(h)),Math.sin(Xn(h)),l,u)}const Ge=63710088e-1,ot=2*Math.PI*Ge;class Je{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 Je(Ye(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(l){const u=Math.PI/180,p=this.lat*u,x=l.lat*u,b=Math.sin(p)*Math.sin(x)+Math.cos(p)*Math.cos(x)*Math.cos((l.lng-this.lng)*u);return Ge*Math.acos(Math.min(b,1))}toBounds(l=0){const u=360*l/40075017,p=u/Math.cos(Math.PI/180*this.lat);return new St({lng:this.lng-p,lat:this.lat-u},{lng:this.lng+p,lat:this.lat+u})}toEcef(l){return Be(this.lat,this.lng,Me+l*Me/Ge)}static convert(l){if(l instanceof Je)return l;if(Array.isArray(l)&&(l.length===2||l.length===3))return new Je(Number(l[0]),Number(l[1]));if(!Array.isArray(l)&&typeof l=="object"&&l!==null)return new Je(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 St{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 Je?new Je(l.lng,l.lat):Je.convert(l),this}setSouthWest(l){return this._sw=l instanceof Je?new Je(l.lng,l.lat):Je.convert(l),this}extend(l){const u=this._sw,p=this._ne;let x,b;if(l instanceof Je)x=l,b=l;else{if(!(l instanceof St))return Array.isArray(l)?l.length===4||l.every(Array.isArray)?this.extend(St.convert(l)):this.extend(Je.convert(l)):typeof l=="object"&&l!==null&&l.hasOwnProperty("lat")&&(l.hasOwnProperty("lon")||l.hasOwnProperty("lng"))?this.extend(Je.convert(l)):this;if(x=l._sw,b=l._ne,!x||!b)return this}return u||p?(u.lng=Math.min(x.lng,u.lng),u.lat=Math.min(x.lat,u.lat),p.lng=Math.max(b.lng,p.lng),p.lat=Math.max(b.lat,p.lat)):(this._sw=new Je(x.lng,x.lat),this._ne=new Je(b.lng,b.lat)),this}getCenter(){return new Je((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 Je(this.getWest(),this.getNorth())}getSouthEast(){return new Je(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(l){const{lng:u,lat:p}=Je.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<=p&&p<=this._ne.lat&&x}static convert(l){if(l)return l instanceof St?l:new St(l)}}function pt(h){return ot*Math.cos(h*Math.PI/180)}function Ot(h){return(180+h)/360}function Ut(h){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+h*Math.PI/360)))/360}function ut(h,l){return h/pt(l)}function st(h){return 360*h-180}function _t(h){return 360/Math.PI*Math.atan(Math.exp((180-360*h)*Math.PI/180))-90}function jt(h,l){return h*pt(_t(l))}const Nt=85.051129;function lr(h){return Math.cos(Xn(pe(h,-85.051129,Nt)))}function Jt(h,l){const u=pe(l,0,25.5),p=Math.pow(2,u);return lr(h)*ot/(512*p)}function er(h){return 1/Math.cos(h*Math.PI/180)}function zt(h,l=0){const u=Math.exp(Math.PI*(1-(h.y+l/fr)/(1<=P?(Fr(h,l,u,O,$,b,V,k,P),Fr(h,O,$,p,x,V,T,k,P)):h.push(T)}function br(h,l,u){let p=h[0],x=p.x,b=p.y;l(p);const T=[p];for(let k=1;kh.x+1||ph.y+1)&&hr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function Kr(h,l,u){const p=h.loadGeometry(),x=h.extent,b=fr/x;if(l&&u&&u.projection.isReprojectedInTileSpace){const T=1<{const Y=st((l.x+G.x/x)/T),X=_t((l.y+G.y/x)/T),te=$.project(Y,X);G.x=(te.x*k-P)*x,G.y=(te.y*k-O)*x};for(let G=0;G=x||X.y<0||X.y>=x||(V(X),Y.push(X));p[G]=Y}}for(const T of p)for(const k of T)Tn(k,b);return p}function jn(h,l){return{type:h.type,id:h.id,properties:h.properties,geometry:l?Kr(h):[]}}class ln{constructor(l,u,p,x,b){this.properties={},this.extent=p,this.type=0,this.id=void 0,this._pbf=l,this._geometry=-1,this._keys=x,this._values=b,l.readFields(ts,this,u)}loadGeometry(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos,p=[];let x,b=1,T=0,k=0,P=0;for(;l.pos>3}if(T--,b===1||b===2)k+=l.readSVarint(),P+=l.readSVarint(),b===1&&(x&&p.push(x),x=[]),x&&x.push(new Ft(k,P));else{if(b!==7)throw new Error(`unknown command ${b}`);x&&x.push(x[0].clone())}}return x&&p.push(x),p}bbox(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos;let p=1,x=0,b=0,T=0,k=1/0,P=-1/0,O=1/0,$=-1/0;for(;l.pos>3}if(x--,p===1||p===2)b+=l.readSVarint(),T+=l.readSVarint(),bP&&(P=b),T$&&($=T);else if(p!==7)throw new Error(`unknown command ${p}`)}return[k,O,P,$]}toGeoJSON(l,u,p){const x=this.extent*Math.pow(2,p),b=this.extent*l,T=this.extent*u,k=this.loadGeometry();function P(G){return[360*(G.x+b)/x-180,360/Math.PI*Math.atan(Math.exp((1-2*(G.y+T)/x)*Math.PI))-90]}function O(G){return G.map(P)}let $;if(this.type===1){const G=[];for(const X of k)G.push(X[0]);const Y=O(G);$=G.length===1?{type:"Point",coordinates:Y[0]}:{type:"MultiPoint",coordinates:Y}}else if(this.type===2){const G=k.map(O);$=G.length===1?{type:"LineString",coordinates:G[0]}:{type:"MultiLineString",coordinates:G}}else{if(this.type!==3)throw new Error("unknown feature type");{const G=function(X){const te=X.length;if(te<=1)return[X];const se=[];let ae,fe;for(let ue=0;ue=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 ln(this._pbf,u,this.extent,this._keys,this._values)}}function Fs(h,l,u){h===15?l.version=u.readVarint():h===1?l.name=u.readString():h===5?l.extent=u.readVarint():h===2?l._features.push(u.pos):h===3?l._keys.push(u.readString()):h===4&&l._values.push(function(p){let x=null;const b=p.readVarint()+p.pos;for(;p.pos>3;x=T===1?p.readString():T===2?p.readFloat():T===3?p.readDouble():T===4?p.readVarint64():T===5?p.readVarint():T===6?p.readSVarint():T===7?p.readBoolean():null}if(x==null)throw new Error("unknown feature value");return x}(u))}class ds{constructor(l,u){this.layers=l.readFields(_n,{},u)}}function _n(h,l,u){if(h===3){const p=new li(u,u.readVarint()+u.pos);p.length&&(l[p.name]=p)}}const bn="3d_elevation_id",Bs="level";class mi{constructor(){this._valid=!1}reset(l){return this.feature=l,this._valid=!0,this._geometry=l.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(l,u){return this._valid&&l(u(this._geometry)),this}require(l,u,p){return this.get(l,!0,u,p)}optional(l,u,p){return this.get(l,!1,u,p)}success(){return this._valid}get(l,u,p,x){const b=this.feature.properties.hasOwnProperty(l)?+this.feature.properties[l]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?p(x?x(b):b):u&&(this._valid=!1),this}}class hs{constructor(l,u){this.featureFunc=l,this.vertexFunc=u}parseFeature(l,u,p){return this.featureFunc(l,u,p)}parseVertex(l,u,p){return this.vertexFunc(l,u,p)}}const hn=new hs((h,l,u)=>h.reset(l).require(bn,p=>{u.id=p}).optional("fixed_height_relative",p=>{u.constantHeight=p},Is.decodeRelativeHeight).geometry(p=>{u.bounds=p},Qj).success(),(h,l,u)=>h.reset(l).require(bn,p=>{u.id=p}).require("elevation_idx",p=>{u.idx=p}).require("extent",p=>{u.extent=p}).require("height_relative",p=>{u.height=p},Is.decodeRelativeHeight).geometry(p=>{u.position=p},Is.getPoint).success()),si=new hs((h,l,u)=>h.reset(l).require(bn,p=>{u.id=p}).optional("fixed_height",p=>{u.constantHeight=p},Is.decodeMetricHeight).geometry(p=>{u.bounds=p},Qj).success(),(h,l,u)=>h.reset(l).require(bn,p=>{u.id=p}).require("elevation_idx",p=>{u.idx=p}).require("extent",p=>{u.extent=p}).require("height",p=>{u.height=p},Is.decodeMetricHeight).geometry(p=>{u.position=p},Is.getPoint).success());class Is{static getPoint(l){return $n(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"?si:void 0:hn}static parse(l){const u=[],p=[],x=l.length,b=new mi;for(let T=0;T=0);if(b===0)return 0;b!==l.length&&(u=!1)}return u?2:1}function Sa(h,l){for(const u of h.projections){const p=ha(l,h.points[0],u.axis);if(u.projection[1]p[1])return 0}return 1}function io(h,l){let u=0;const p=[0,0,0,0];for(let x=0;x=0&&u++;return u}class kc{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=ys.fromPoints(this.points),this.projections=[],this.frustumEdges=[qr([],this.points[2],this.points[3]),qr([],this.points[0],this.points[3]),qr([],this.points[4],this.points[0]),qr([],this.points[5],this.points[1]),qr([],this.points[6],this.points[2]),qr([],this.points[7],this.points[3])];for(const p of this.frustumEdges){const x=[0,-p[2],p[1]],b=[p[2],0,-p[0]];this.projections.push({axis:x,projection:ha(this.points,this.points[0],x)}),this.projections.push({axis:b,projection:ha(this.points,this.points[0],b)})}}static fromInvProjectionMatrix(l,u,p,x){const b=Math.pow(2,p),T=[[-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 $=Kt([],O,l),V=1/$[3]/u*b;return(G=$)[0]=(Y=$)[0]*(X=[V,V,x?1/$[3]:V,V])[0],G[1]=Y[1]*X[1],G[2]=Y[2]*X[2],G[3]=Y[3]*X[3],G;var G,Y,X}),k=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(O=>{const $=ft([],Vt([],qr([],T[O[0]],T[O[1]]),qr([],T[O[2]],T[O[1]]))),V=-kt($,T[O[1]]);return $.concat(V)}),P=[];for(let O=0;OO[1]||O[0]>P[1])return 0}return 1}containsPoint(l){for(const u of this.planes){const p=u[3];if(kt([u[0],u[1],u[2]],l)+p<0)return!1}return!0}}class ys{static fromPoints(l){const u=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0];for(const x of l)Ee(u,u,x),xe(p,p,x);return new ys(u,p)}static fromTileIdAndHeight(l,u,p){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])]}}jr(ys,"Aabb");class Qc{constructor(l,u){this.feature=l,this.metersToTile=u,this.index=0}get(){const l=this.feature.vertices[this.index],u=this.feature.vertexProps[this.index].dir,p=u[1],x=-u[0],b=(l.extent+1)*this.metersToTile;return[new Ft(Math.trunc(l.position[0]+p*b),Math.trunc(l.position[1]+x*b)),new Ft(Math.trunc(l.position[0]-p*b),Math.trunc(l.position[1]-x*b))]}next(){this.index++}valid(){return this.index{return k.a0?Ue(P,P,1/O):ve(P,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(l){if(this.edges.length===0)return;let u=0,p=Number.POSITIVE_INFINITY,x=0;const[b,T,k,P,O,$,V]=this._tmpVec2;Si(V,l.x,l.y);const G=new Yi(V,null);for(let Y=0;Y0?Qr(P,k)/Te:0,Ie=pe(Ae,0,1),We=Math.abs((Ae-Ie)*this.edgeProps[Y].len);ia(O,V,se),Si($,te[1],-te[0]);const ze=We+Math.abs(Qr(O,$));ze=0;--T){const k=this.edges[T].a,P=this.edges[T].b,{position:O,height:$,extent:V}=this.vertices[k],{position:G,height:Y,extent:X}=this.vertices[P],te=this.vertexProps[k].dir,se=this.vertexProps[P].dir;if(ve(u,O[0]/l,O[1]/l,$),ve(p,G[0]/l,G[1]/l,Y),ve(x,te[1],-te[0],0),Ue(x,x,V),ve(b,se[1],-se[0],0),Ue(b,b,X),this.distSqLines(Se(u[0]+.5*x[0],u[1]+.5*x[1],u[2]+.5*x[2]),Se(p[0]-.5*b[0],p[1]-.5*b[1],p[2]-.5*b[2]),Se(u[0]-.5*x[0],u[1]-.5*x[1],u[2]-.5*x[2]),Se(p[0]+.5*b[0],p[1]+.5*b[1],p[2]+.5*b[2]))<=.0025000000000000005)continue;const ae=this.vertices.length,fe=oi(Ir(),O,G);this.vertices.push({position:Xr(fe,fe,.5),height:.5*($+Y),extent:.5*(V+X)});const ue=oi(Ir(),te,se);this.vertexProps.push({dir:xn(ue,ue)}),this.edges.splice(T,1),this.edgeProps.splice(T,1),this.edges.push({a:k,b:ae}),this.edges.push({a:ae,b:P});const Te=ia(Ir(),this.vertices[ae].position,O),Ae=un(Te),Ie={vec:Te,dir:Xr(Ir(),Te,1/Ae),len:Ae};this.edgeProps.push(Ie),this.edgeProps.push(Ie)}}distSqLines(l,u,p,x){const b=ke(ye(),u,l),T=ke(ye(),x,p),k=ke(ye(),l,p),P=kt(b,b),O=kt(b,T),$=kt(b,k),V=kt(T,T),G=kt(T,k),Y=P*V-O*O;if(Y===0)return wt(xt(b,p,x,kt(k,T)/kt(T,T)),l);const X=(P*G-O*$)/Y;return wt(xt(b,l,u,(O*G-$*V)/Y),xt(T,p,x,X))}}class Vs{static parseFrom(l,u){const p=Is.parse(l);if(!p)return[];let{vertices:x,features:b}=p;const T=1/zt(u);b.sort(($,V)=>$.id-V.id),x.sort(($,V)=>$.id-V.id||$.idx-V.idx),x=x.filter(($,V,G)=>V===G.findIndex(Y=>Y.id===$.id&&Y.idx===$.idx));const k=new Array;let P=0;const O=x.length;for(const $ of b){if($.constantHeight){k.push(new Jc($.id,$.bounds,$.constantHeight));continue}for(;P!==O&&x[P].id<$.id;)P++;if(P===O||x[P].id!==$.id)continue;const V=new Array,G=new Array,Y=P;for(;P!==O&&x[P].id===$.id;){const X=x[P];if(V.push({position:X.position,height:X.height,extent:X.extent}),P!==Y&&x[P-1].idx===X.idx-1){const te=P-Y;G.push({a:te-1,b:te})}P++}k.push(new Jc($.id,$.bounds,void 0,V,G,T))}return k}static getElevationFeature(l,u){if(!u)return;const p=+l.properties[bn];return Number.isNaN(p)?void 0:u.find(x=>x.id===p)}}class Ys{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)*fr,this.yOffset=(l.y*this.zScale-u.y)*fr)}constantElevation(l,u){if(l.constantHeight!=null)return this.computeBiasedHeight(l.constantHeight,u)}pointElevation(l,u,p){const x=this.constantElevation(u,p);return x??(l.x=l.x*this.zScale+this.xOffset,l.y=l.y*this.zScale+this.yOffset,this.computeBiasedHeight(u.pointElevation(l),p))}computeBiasedHeight(l,u){return u<=0?l:l+u*Fe(0,u,l>=0?l:Math.abs(.5*l))}}jr(Jc,"ElevationFeature");class js{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 Ec,this.indexArray=new Pi,this.segments=new Os,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 Zc),this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){const b=this.layers[0],T=[];let k=null;b.type==="circle"&&(k=b.layout.get("circle-sort-key"));for(const{feature:O,id:$,index:V,sourceLayerIndex:G}of l){const Y=this.layers[0]._featureFilter.needGeometry,X=jn(O,Y);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),X,p))continue;const te=k?k.evaluate(X,{},p):void 0,se={id:$,properties:O.properties,type:O.type,sourceLayerIndex:G,index:V,geometry:Y?X.geometry:Kr(O,p,x),patterns:{},sortKey:te};T.push(se)}k&&T.sort((O,$)=>O.sortKey-$.sortKey);let P=null;x.projection.name==="globe"&&(this.globeExtVertexArray=new _w,P=x.projection);for(const O of T){const{geometry:$,index:V,sourceLayerIndex:G}=O,Y=l[V].feature;this.addFeature(O,$,V,u.availableImages,p,P,u.brightness,u.elevationFeatures),u.featureIndex.insert(Y,$,V,G,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(l,u,p,x,b,T,k){this.programConfigurations.updatePaintArrays(l,u,b,p,x,T,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,RP.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,RB.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,PB.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(l,u,p,x,b,T,k,P){let O;this.elevationMode!=="none"&&(O=Vs.getElevationFeature(l,P));for(const $ of u)for(const V of $){const G=V.x,Y=V.y;if(G<0||G>=fr||Y<0||Y>=fr)continue;if(T){const se=T.projectTilePoint(G,Y,b),ae=T.upVector(b,G,Y);this.addGlobeExtVertex(se,ae),this.addGlobeExtVertex(se,ae),this.addGlobeExtVertex(se,ae),this.addGlobeExtVertex(se,ae)}const X=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,l.sortKey),te=X.vertexLength;if(this.addCircleVertex(G,Y,-1,-1),this.addCircleVertex(G,Y,1,-1),this.addCircleVertex(G,Y,1,1),this.addCircleVertex(G,Y,-1,1),this.elevationMode!=="none"){const se=O?O.pointElevation(new Ft(G,Y)):0;this.hasElevation=this.hasElevation||se!==0;for(let ae=0;ae<4;ae++)this.elevatedLayoutVertexArray.emplaceBack(se)}this.indexArray.emplaceBack(te,te+1,te+2),this.indexArray.emplaceBack(te,te+2,te+3),X.vertexLength+=4,X.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,{},x,b,k,void 0,this.worldview)}addCircleVertex(l,u,p,x){this.layoutVertexArray.emplaceBack(2*l+(p+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 qi(h,l){for(let u=0;u1){if(sm(h,l))return!0;for(let p=0;p1?u:u.sub(l)._mult(x)._add(l))}function jy(h,l){let u,p,x,b=!1;for(let T=0;Tl.y!=x.y>l.y&&l.x<(x.x-p.x)*(l.y-p.y)/(x.y-p.y)+p.x&&(b=!b)}return b}function Ql(h,l){let u=!1;for(let p=0,x=h.length-1;pl.y!=T.y>l.y&&l.x<(T.x-b.x)*(l.y-b.y)/(T.y-b.y)+b.x&&(u=!u)}return u}function im(h,l,u,p,x){for(const T of h)if(l<=T.x&&u<=T.y&&p>=T.x&&x>=T.y)return!0;const b=[new Ft(l,u),new Ft(l,x),new Ft(p,x),new Ft(p,u)];if(h.length>2){for(const T of b)if(Ql(h,T))return!0}for(let T=0;Tx.x&&l.x>x.x||h.yx.y&&l.y>x.y)return!1;const b=rt(h,l,u[0]);return b!==rt(h,l,u[1])||b!==rt(h,l,u[2])||b!==rt(h,l,u[3])}function om(h,l,u,p,x,b){let T=l.y-h.y,k=h.x-l.x;if(b=b||0){const P=T*T+k*k;if(P===0)return!0;const O=Math.sqrt(P);T/=O,k/=O}return!((u.x-h.x)*T+(u.y-h.y)*k-b<0||(p.x-h.x)*T+(p.y-h.y)*k-b<0||(x.x-h.x)*T+(x.y-h.y)*k-b<0)}function Nw(h,l,u,p,x,b,T){return!(om(h,l,p,x,b,T)||om(l,u,p,x,b,T)||om(u,h,p,x,b,T)||om(p,x,h,l,u,T)||om(x,b,h,l,u,T)||om(b,p,h,l,u,T))}function Ey(h,l,u){const p=l.paint.get(h).value;return p.kind==="constant"?p.value:u.programConfigurations.get(l.id).getMaxValue(h)}function LP(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function IX(h,l,u,p,x){if(!l[0]&&!l[1])return h;const b=Ft.convert(l)._mult(x);u==="viewport"&&b._rotate(-p);const T=[];for(let k=0;k>u&&l.y===this.y>>u}url(l,u){const p=function(b,T,k){const P=2**k,O=2*Math.PI*6378137,$=O*(b/P-.5),V=O*(.5-(T+1)/P);return`${$},${V},${$+O/P},${V+O/P}`}(this.x,this.y,this.z),x=function(b,T,k){let P,O="";for(let $=b;$>0;$--)P=1<<$-1,O+=(T&P?1:0)+(k&P?2:0);return O}(this.z,this.x,this.y);return l[(this.x+this.y)%l.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace(/{z}/g,String(this.z)).replace(/{x}/g,String(this.x)).replace(/{y}/g,String(u==="tms"?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",x).replace("{bbox-epsg-3857}",p)}toString(){return`${this.z}/${this.x}/${this.y}`}}class MX{constructor(l,u){this.wrap=l,this.canonical=u,this.key=Cw(l,u.z,u.z,u.x,u.y)}}class Dl{constructor(l,u,p,x,b){this.overscaledZ=l,this.wrap=u,this.canonical=new Nv(p,+x,+b),this.key=u===0&&l===p?this.canonical.key:Cw(u,l,p,x,b)}equals(l){return this.overscaledZ===l.overscaledZ&&this.wrap===l.wrap&&this.canonical.equals(l.canonical)}scaledTo(l){const u=this.canonical.z-l;return l>this.canonical.z?new Dl(l,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Dl(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 Cw(this.wrap*+u,l,this.canonical.z,this.canonical.x,this.canonical.y);{const p=this.canonical.z-l;return Cw(this.wrap*+u,l,l,this.canonical.x>>p,this.canonical.y>>p)}}isChildOf(l){if(l.wrap!==this.wrap)return!1;const u=this.canonical.z-l.canonical.z;return l.overscaledZ===0||l.overscaledZ>u&&l.canonical.y===this.canonical.y>>u}children(l){if(this.overscaledZ>=l)return[new Dl(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const u=this.canonical.z+1,p=2*this.canonical.x,x=2*this.canonical.y;return[new Dl(u,this.wrap,u,p,x),new Dl(u,this.wrap,u,p+1,x),new Dl(u,this.wrap,u,p,x+1),new Dl(u,this.wrap,u,p+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 Dl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new Dl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<1?null:function(p,x,b,T){const k=Math.sin(b);return p*(Math.sin((1-T)*b)/k)+x*(Math.sin(T*b)/k)}(h.a[l],h.b[l],h.angle,pe(u,0,1))+h.center[l]}function lm(h){if(h.z<=1)return tPe[h.z+2*h.y+h.x];const l=$B(OP(h));return ys.fromPoints(l)}function $p(h,l,u){return Ue(h,h,1-u),Ze(h,h,l,u)}function FX(h,l){const u=zp(l.zoom);if(u===0)return lm(h);const p=OP(h),x=$B(p),b=Ot(p.getWest())*l.worldSize,T=Ot(p.getEast())*l.worldSize,k=Ut(p.getNorth())*l.worldSize,P=Ut(p.getSouth())*l.worldSize,O=[b,k,0],$=[T,k,0],V=[b,P,0],G=[T,P,0],Y=M([],l.globeMatrix);return or(O,O,Y),or($,$,Y),or(V,V,Y),or(G,G,Y),x[0]=$p(x[0],V,u),x[1]=$p(x[1],G,u),x[2]=$p(x[2],$,u),x[3]=$p(x[3],O,u),ys.fromPoints(x)}function BX(h,l,u){for(const p of h)or(p,p,l),Ue(p,p,u)}function $X(h,l,u,p){const x=l/h.worldSize,b=h.globeMatrix;if(u.z<=1){const He=lm(u).getCorners();return BX(He,b,x),ys.fromPoints(He)}const T=OP(u,p),k=$B(T,Me+DP(h._tileCoverLift));BX(k,b,x);const P=Number.MAX_VALUE,O=[-P,-P,-P],$=[P,P,P];if(T.contains(h.center)){for(const qe of k)Ee($,$,qe),xe(O,O,qe);O[2]=0;const He=h.point,Ve=[He.x*x,He.y*x,0];return Ee($,$,Ve),xe(O,O,Ve),new ys($,O)}if(h._tileCoverLift>0){for(const He of k)Ee($,$,He),xe(O,O,He);return new ys($,O)}const V=[b[12]*x,b[13]*x,b[14]*x],G=T.getCenter(),Y=pe(h.center.lat,-85.051129,Nt),X=pe(G.lat,-85.051129,Nt),te=Ot(h.center.lng),se=Ut(Y);let ae=te-Ot(G.lng);const fe=se-Ut(X);ae>.5?ae-=1:ae<-.5&&(ae+=1);let ue=0;Math.abs(ae)>Math.abs(fe)?ue=ae>=0?1:3:(ue=fe>=0?0:2,Ze(V,V,[b[4]*x,b[5]*x,b[6]*x],-Math.sin(Xn(fe>=0?T.getSouth():T.getNorth()))*Me));const Te=k[ue],Ae=k[(ue+1)%4],Ie=new rPe(Te,Ae,V),We=[BB(Ie,0)||Te[0],BB(Ie,1)||Te[1],BB(Ie,2)||Te[2]],ze=zp(h.zoom);if(ze>0){const He=function({x:qe,y:bt,z:Et},It,Dt,Pt,Ht){const vt=1/(1<.5?wr=-1:ur<-.5&&(wr=1),Rt=((Rt+wr)*It-(Pt*=It))*Dt+Pt,Bt=((Bt+wr)*It-Pt)*Dt+Pt,Yt=(Yt*It-(Ht*=It))*Dt+Ht,tr=(tr*It-Ht)*Dt+Ht,[[Rt,tr,0],[Bt,tr,0],[Bt,Yt,0],[Rt,Yt,0]]}(u,l,h._pixelsPerMercatorPixel,te,se);for(let qe=0;qeMath.PI/2*1.01}const GX=Xn(85),nPe=Math.cos(GX),sPe=Math.sin(GX),iPe=A(),HX=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 WX(h,l,u,p,x,b,T,k,P){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(P*=h.pixelToTileUnitsFactor);const O=h.tileID.canonical,$=u.projection.upVectorScale(O,u.center.lat,u.worldSize).metersToTile;for(const V of l)for(const G of V){const Y=G.add(k),X=x&&u.elevation?u.elevation.exaggeration()*x.getElevationAt(Y.x,Y.y,!0):0,te=u.projection.projectTilePoint(Y.x,Y.y,O);if(X>0){const ue=u.projection.upVector(O,Y.x,Y.y);te.x+=ue[0]*$*X,te.y+=ue[1]*$*X,te.z+=ue[2]*$*X}const se=b?Y:aPe(te.x,te.y,te.z,p),ae=b?h.tilespaceRays.map(ue=>lPe(ue,X)):h.queryGeometry.screenGeometry,fe=Kt([],[te.x,te.y,te.z,1],p);if(!T&&b?P*=fe[3]/u.cameraToCenterDistance:T&&!b&&(P*=u.cameraToCenterDistance/fe[3]),b){const ue=_t((G.y/fr+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||p.x>l.width-x.width||p.y>l.height-x.height)throw new RangeError("out of range destination coordinates for image copy");const P=h.data,O=l.data,$=b===4&&k;for(let V=0;V{l[h.evaluationKey]=P;const O=h.expression.evaluate(l),$=O?O.toNonPremultipliedRenderColor(null):null;$&&(x.data[T+k+0]=Math.floor(255*$.r),x.data[T+k+1]=Math.floor(255*$.g),x.data[T+k+2]=Math.floor(255*$.b),x.data[T+k+3]=Math.floor(255*$.a))};if(h.clips)for(let T=0,k=0;T80*u){k=h[0],P=h[1];let $=k,V=P;for(let G=u;G$&&($=Y),X>V&&(V=X)}O=Math.max($-k,V-P),O=O!==0?32767/O:0}return d2(b,T,u,k,P,O,0),T}function nQ(h,l,u,p,x){let b;if(x===function(T,k,P,O){let $=0;for(let V=k,G=P-O;V0)for(let T=l;T=l;T-=p)b=oQ(T/p|0,h[T],h[T+1],b);return b&&Pw(b,b.next)&&(m2(b),b=b.next),b}function Cv(h,l){if(!h)return h;l||(l=h);let u,p=h;do if(u=!1,p.steiner||!Pw(p,p.next)&&ao(p.prev,p,p.next)!==0)p=p.next;else{if(m2(p),p=l=p.prev,p===p.next)break;u=!0}while(u||p!==l);return l}function d2(h,l,u,p,x,b,T){if(!h)return;!T&&b&&function(P,O,$,V){let G=P;do G.z===0&&(G.z=GB(G.x,G.y,O,$,V)),G.prevZ=G.prev,G.nextZ=G.next,G=G.next;while(G!==P);G.prevZ.nextZ=null,G.prevZ=null,function(Y){let X,te=1;do{let se,ae=Y;Y=null;let fe=null;for(X=0;ae;){X++;let ue=ae,Te=0;for(let Ie=0;Ie0||Ae>0&&ue;)Te!==0&&(Ae===0||!ue||ae.z<=ue.z)?(se=ae,ae=ae.nextZ,Te--):(se=ue,ue=ue.nextZ,Ae--),fe?fe.nextZ=se:Y=se,se.prevZ=fe,fe=se;ae=ue}fe.nextZ=null,te*=2}while(X>1)}(G)}(h,p,x,b);let k=h;for(;h.prev!==h.next;){const P=h.prev,O=h.next;if(b?mPe(h,p,x,b):fPe(h))l.push(P.i,h.i,O.i),m2(h),h=O.next,k=O.next;else if((h=O)===k){T?T===1?d2(h=pPe(Cv(h),l),l,u,p,x,b,2):T===2&&gPe(h,l,u,p,x,b):d2(Cv(h),l,u,p,x,b,1);break}}}function fPe(h){const l=h.prev,u=h,p=h.next;if(ao(l,u,p)>=0)return!1;const x=l.x,b=u.x,T=p.x,k=l.y,P=u.y,O=p.y,$=Math.min(x,b,T),V=Math.min(k,P,O),G=Math.max(x,b,T),Y=Math.max(k,P,O);let X=p.next;for(;X!==l;){if(X.x>=$&&X.x<=G&&X.y>=V&&X.y<=Y&&h2(x,k,b,P,T,O,X.x,X.y)&&ao(X.prev,X,X.next)>=0)return!1;X=X.next}return!0}function mPe(h,l,u,p){const x=h.prev,b=h,T=h.next;if(ao(x,b,T)>=0)return!1;const k=x.x,P=b.x,O=T.x,$=x.y,V=b.y,G=T.y,Y=Math.min(k,P,O),X=Math.min($,V,G),te=Math.max(k,P,O),se=Math.max($,V,G),ae=GB(Y,X,l,u,p),fe=GB(te,se,l,u,p);let ue=h.prevZ,Te=h.nextZ;for(;ue&&ue.z>=ae&&Te&&Te.z<=fe;){if(ue.x>=Y&&ue.x<=te&&ue.y>=X&&ue.y<=se&&ue!==x&&ue!==T&&h2(k,$,P,V,O,G,ue.x,ue.y)&&ao(ue.prev,ue,ue.next)>=0||(ue=ue.prevZ,Te.x>=Y&&Te.x<=te&&Te.y>=X&&Te.y<=se&&Te!==x&&Te!==T&&h2(k,$,P,V,O,G,Te.x,Te.y)&&ao(Te.prev,Te,Te.next)>=0))return!1;Te=Te.nextZ}for(;ue&&ue.z>=ae;){if(ue.x>=Y&&ue.x<=te&&ue.y>=X&&ue.y<=se&&ue!==x&&ue!==T&&h2(k,$,P,V,O,G,ue.x,ue.y)&&ao(ue.prev,ue,ue.next)>=0)return!1;ue=ue.prevZ}for(;Te&&Te.z<=fe;){if(Te.x>=Y&&Te.x<=te&&Te.y>=X&&Te.y<=se&&Te!==x&&Te!==T&&h2(k,$,P,V,O,G,Te.x,Te.y)&&ao(Te.prev,Te,Te.next)>=0)return!1;Te=Te.nextZ}return!0}function pPe(h,l){let u=h;do{const p=u.prev,x=u.next.next;!Pw(p,x)&&iQ(p,u,u.next,x)&&f2(p,x)&&f2(x,p)&&(l.push(p.i,u.i,x.i),m2(u),m2(u.next),u=h=x),u=u.next}while(u!==h);return Cv(u)}function gPe(h,l,u,p,x,b){let T=h;do{let k=T.next.next;for(;k!==T.prev;){if(T.i!==k.i&&bPe(T,k)){let P=aQ(T,k);return T=Cv(T,T.next),P=Cv(P,P.next),d2(T,l,u,p,x,b,0),void d2(P,l,u,p,x,b,0)}k=k.next}T=T.next}while(T!==h)}function yPe(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 xPe(h,l){const u=function(x,b){let T=b;const k=x.x,P=x.y;let O,$=-1/0;if(Pw(x,T))return T;do{if(Pw(x,T.next))return T.next;if(P<=T.y&&P>=T.next.y&&T.next.y!==T.y){const te=T.x+(P-T.y)*(T.next.x-T.x)/(T.next.y-T.y);if(te<=k&&te>$&&($=te,O=T.x=T.x&&T.x>=G&&k!==T.x&&sQ(PO.x||T.x===O.x&&vPe(O,T)))&&(O=T,X=te)}T=T.next}while(T!==V);return O}(h,l);if(!u)return l;const p=aQ(u,h);return Cv(p,p.next),Cv(u,u.next)}function vPe(h,l){return ao(h.prev,h,l.prev)<0&&ao(l.next,h,h.next)<0}function GB(h,l,u,p,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-p)*x|0)|l<<8))|l<<4))|l<<2))|l<<1))<<1}function _Pe(h){let l=h,u=h;do(l.x=(h-T)*(b-k)&&(h-T)*(p-k)>=(u-T)*(l-k)&&(u-T)*(b-k)>=(x-T)*(p-k)}function h2(h,l,u,p,x,b,T,k){return!(h===T&&l===k)&&sQ(h,l,u,p,x,b,T,k)}function bPe(h,l){return h.next.i!==l.i&&h.prev.i!==l.i&&!function(u,p){let x=u;do{if(x.i!==u.i&&x.next.i!==u.i&&x.i!==p.i&&x.next.i!==p.i&&iQ(x,x.next,u,p))return!0;x=x.next}while(x!==u);return!1}(h,l)&&(f2(h,l)&&f2(l,h)&&function(u,p){let x=u,b=!1;const T=(u.x+p.x)/2,k=(u.y+p.y)/2;do x.y>k!=x.next.y>k&&x.next.y!==x.y&&T<(x.next.x-x.x)*(k-x.y)/(x.next.y-x.y)+x.x&&(b=!b),x=x.next;while(x!==u);return b}(h,l)&&(ao(h.prev,h,l.prev)||ao(h,l.prev,l))||Pw(h,l)&&ao(h.prev,h,h.next)>0&&ao(l.prev,l,l.next)>0)}function ao(h,l,u){return(l.y-h.y)*(u.x-l.x)-(l.x-h.x)*(u.y-l.y)}function Pw(h,l){return h.x===l.x&&h.y===l.y}function iQ(h,l,u,p){const x=$P(ao(h,l,u)),b=$P(ao(h,l,p)),T=$P(ao(u,p,h)),k=$P(ao(u,p,l));return x!==b&&T!==k||!(x!==0||!BP(h,u,l))||!(b!==0||!BP(h,p,l))||!(T!==0||!BP(u,h,p))||!(k!==0||!BP(u,l,p))}function BP(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 $P(h){return h>0?1:h<0?-1:0}function f2(h,l){return ao(h.prev,h,h.next)<0?ao(h,l,h.next)>=0&&ao(h,h.prev,l)>=0:ao(h,l,h.prev)<0||ao(h,h.next,l)<0}function aQ(h,l){const u=HB(h.i,h.x,h.y),p=HB(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,p.next=u,u.prev=p,b.next=p,p.prev=b,p}function oQ(h,l,u,p){const x=HB(h,l,u);return p?(x.next=p.next,x.prev=p,p.next.prev=x,p.next=x):(x.prev=x,x.next=x),x}function m2(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 HB(h,l,u){return{i:h,x:l,y:u,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function p2(h,l){const u=h.length;if(u<=1)return[h];const p=[];let x,b;for(let T=0;T1)for(let T=0;T=fr&&u>=fr}static evaluate(l){if(l.length===0)return new Up;let u=[];for(const P of l)u.push(...P.portals);if(u.length===0)return new Up;for(const P of u){const O=P.va,$=P.vb;(Up.isOnBorder(O.x,$.x)||Up.isOnBorder(O.y,$.y))&&(P.type="border")}const p=u.filter(P=>P.type!=="unevaluated"),x=u.filter(P=>P.type==="unevaluated");if(x.length===0)return new Up;x.sort((P,O)=>P.hash===O.hash?P.isTunnel===O.isTunnel?0:P.isTunnel?-1:1:P.hashP.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new ie(u,{zoom:p,lut:x},b=>b!=="fill-bridge-guard-rail-color")}addVertices(l,u){const p=this.unevalVertices.length;for(let x=0;x=b.min.x&&V.x<=b.max.x&&V.y>=b.min.y&&V.y<=b.max.y||G.x>=b.min.x&&G.x<=b.max.x&&G.y>=b.min.y&&G.y<=b.max.y||am(V,G,k))||this.isOnBorder(V.x,G.x)||this.isOnBorder(V.y,G.y))continue;const Y=eu.computeEdgeHash(this.unevalVertices[O],this.unevalVertices[$]);let X,te=this.vertexHashLookup.get(eu.computePosHash(V));te!=null?X=te.next:(te=this.vertexHashLookup.get(eu.computePosHash(G)),X=te!=null?te.prev:Y),this.unevalEdges.push({polygonIdx:l,a:O,b:$,hash:Y,portalHash:X,isTunnel:x,type:"unevaluated",featureInfo:T})}}addPortalCandidates(l,u,p,x,b){if(u.length!==0){this.vertexHashLookup.clear();for(const T of u){if(T.length===0)continue;const k=T[0];let P=eu.computeEdgeHash(k[k.length-2],k[k.length-1]);for(let O=0;O({vertexOffset:0,primitiveOffset:this.indexArray.length}),p=G=>{G.primitiveLength=this.indexArray.length-G.primitiveOffset},x=new SPe(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(l.portals,this.unevalEdges);const b=u(),T=u(),k=u(),P=(G,Y)=>{G.sort((te,se)=>te.type===Y&&se.type!==Y?-1:te.type!==Y&&se.type===Y?1:0);const X=G.findIndex(te=>te.type!==Y);return X>=0?X:G.length};let O=0;this.unevalEdges.length>0&&(O=P(this.unevalEdges,"none"),this.constructBridgeStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},this.tileToMeters)),p(k);const $=u(),V=u();if(this.unevalEdges.length>0){const G=this.unevalEdges.splice(O),Y=P(G,"tunnel")+O;this.unevalEdges.push(...G),this.constructTunnelStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},{min:O,max:Y})}p($),x.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),p(V),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),p(T),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),p(b),this.maskSegments=Os.simpleSegment(0,V.primitiveOffset,0,V.primitiveLength),this.depthSegments=Os.simpleSegment(0,T.primitiveOffset,0,T.primitiveLength),this.renderableBridgeSegments=Os.simpleSegment(0,k.primitiveOffset,0,k.primitiveLength),this.renderableTunnelSegments=Os.simpleSegment(0,$.primitiveOffset,0,$.primitiveLength),this.shadowCasterSegments=Os.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(l,u,p,x,b,T,k,P){this.bridgeProgramConfigurations.updatePaintArrays(l,u,b,p,x,T,k,P),this.tunnelProgramConfigurations.updatePaintArrays(l,u,b,p,x,T,k,P)}upload(l){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=l.createVertexBuffer(this.vertexPositions,dPe.members),this.vertexBufferNormal=l.createVertexBuffer(this.vertexNormals,hPe.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(l),this.tunnelProgramConfigurations.upload(l))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(l,u,p,x,b){const T=(k,P)=>{for(let O=0;Ove(Dt,u[Pt].x,u[Pt].y,p[Pt]*P),V=ye(),G=ye(),Y=ye(),X=ye(),te=ye(),se=(Dt,Pt)=>{const Ht=k.get(eu.computePosHash(u[Pt])),vt=Ht.from,Rt=Ht.to;if(!vt||!Rt)return;$(V,vt),$(G,Pt),$(Y,Rt),Lr(X),$r(V,G)||(qr(te,G,V),ft(X,te)),$r(Y,G)||(qr(te,Y,G),me(X,X,ft(te,te)));const Bt=tt(X);return Bt>0?Ue(Dt,X,1/Bt):void 0};let ae=Number.POSITIVE_INFINITY;this.sortSubarray(x,b.min,b.max,(Dt,Pt)=>Dt.featureInfo.featureIndex-Pt.featureInfo.featureIndex);const fe=ye(),ue=ye(),Te=ye(),Ae=ye(),Ie=ye(),We=ye(),ze=ye(),He=ye(),Ve=ye(),qe=[ye(),ye(),ye(),ye()],bt=[ye(),ye(),ye(),ye()],Et=[{coord:new Ft(0,0),height:0},{coord:new Ft(0,0),height:0}],It=(Dt,Pt)=>Dt>Pt;for(let Dt=b.min;Dtae.featureInfo.featureIndex-fe.featureInfo.featureIndex;this.sortSubarray(x,b.min,b.max,P),this.sortSubarray(x,T.min,T.max,P);const O=ae=>ft(ae,ae),$=[{coord:new Ft(0,0),height:0},{coord:new Ft(0,0),height:0}],V=(ae,fe)=>aek.hash===P.hash?P.polygonIdx-k.polygonIdx:P.hash>k.hash?1:-1);let p=0,x=0,b=0,T=u[p].polygonIdx;do x++,(x===u.length||u[p].hash!==u[x].hash)&&((x-p===1||u[x-1].polygonIdx!==T)&&(bO.portalHash<$.portalHash?1:-1);let k=0,P=0;for(;k!==u.length&&P!==l.length;){const O=u[k],$=l[P];O.portalHash>$.hash?k++:$.hash>O.portalHash?P++:(O.type=$.type,k++)}}}isOnBorder(l,u){return l<=0&&u<=0||l>=fr&&u>=fr}addFeatureSection(l,u,p,x){return l!==u&&(u=l,p.push({featureIndex:l,vertexStart:x.getVertexCount()}),x.clearVertexLookup()),u}sortSubarray(l,u,p,x){const b=l.slice(u,p);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(eu.computePosHash(l))<<32n|BigInt(eu.computePosHash(u))}static computePosHash(l){return((65535&l.x)<<16|65535&l.y)>>>0}}function TPe(h,l){return h>l?1:h0))return u;u=u.left}}return null}contains(l){for(var u=this._root,p=this._compare;u;){var x=p(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 p=this.minNode(u.right);p.parent!==u&&(this.replace(p,p.right),p.right=u.right,p.right.parent=p),this.replace(u,p),p.left=u.left,p.left.parent=p}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}removeNode(l){if(!l)return!1;if(this.splay(l),l.left)if(l.right){var u=this.minNode(l.right);u.parent!==l&&(this.replace(u,u.right),u.right=l.right,u.right.parent=u),this.replace(l,u),u.left=l.left,u.left.parent=u}else this.replace(l,l.left);else this.replace(l,l.right);return this._size--,!0}erase(l){var u=this.find(l);if(u){this.splay(u);var p=u.left,x=u.right,b=null;p&&(p.parent=null,b=this.maxNode(p),this.splay(b),this._root=b),x&&(p?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,p=[],x=!1,b=0;!x;)u?(p.push(u),u=u.left):p.length>0?(l(u=p.pop(),b++),u=u.right):x=!0;return this}range(l,u,p,x){const b=[],T=this._compare;let k,P=this._root;for(;b.length!==0||P;)if(P)b.push(P),P=P.left;else{if(P=b.pop(),k=T(P.key,u),k>0)break;if(T(P.key,l)>=0&&p.call(x,P))return this;P=P.right}return this}keys(){for(var l=this._root,u=[],p=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),p.push(l.key),l=l.right):x=!0;return p}values(){for(var l=this._root,u=[],p=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),p.push(l.data),l=l.right):x=!0;return p}at(l){for(var u=this._root,p=[],x=!1,b=0;!x;)if(u)p.push(u),u=u.left;else if(p.length>0){if(u=p.pop(),b===l)return u;b++,u=u.right}else x=!0;return null}load(l=[],u=[],p=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const x=l.length;return p&&XB(l,u,0,x-1,this._compare),this._root=ZB(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,p,x,b){return new YB(p,b).load(l,u,x)}}function ZB(h,l,u,p,x){const b=x-p;if(b>0){const T=p+Math.floor(b/2),k={key:l[T],data:u[T],parent:h};return k.left=ZB(k,l,u,p,T),k.right=ZB(k,l,u,T+1,x),k}return null}function XB(h,l,u,p,x){if(u>=p)return;const b=h[u+p>>1];let T=u-1,k=p+1;for(;;){do T++;while(x(h[T],b)<0);do k--;while(x(h[k],b)>0);if(T>=k)break;let P=h[T];h[T]=h[k],h[k]=P,P=l[T],l[T]=l[k],l[k]=P}XB(h,l,u,k,x),XB(h,l,k+1,p,x)}const cQ=11102230246251565e-32,Nc=134217729,jPe=(3+8*cQ)*cQ;function QB(h,l,u,p,x){let b,T,k,P,O=l[0],$=p[0],V=0,G=0;$>O==$>-O?(b=O,O=l[++V]):(b=$,$=p[++G]);let Y=0;if(VO==$>-O?(T=O+b,k=b-(T-O),O=l[++V]):(T=$+b,k=b-(T-$),$=p[++G]),b=T,k!==0&&(x[Y++]=k);VO==$>-O?(T=b+O,P=T-b,k=b-(T-P)+(O-P),O=l[++V]):(T=b+$,P=T-b,k=b-(T-P)+($-P),$=p[++G]),b=T,k!==0&&(x[Y++]=k);for(;V0:(p[0]-l[0])*(u[1]-l[1])-(u[0]-l[0])*(p[1]-l[1])>0}isAbove(l){return!this.isBelow(l)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const l=new Lw(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 cm(h,l){return h[0]===l[0]&&h[1]===l[1]}function JB(h,l,u){const p=function(x,b,T,k,P,O){const $=(b-O)*(T-P),V=(x-P)*(k-O),G=$-V;if($===0||V===0||$>0!=V>0)return G;const Y=Math.abs($+V);return Math.abs(G)>=33306690738754716e-32*Y?G:-function(X,te,se,ae,fe,ue,Te){let Ae,Ie,We,ze,He,Ve,qe,bt,Et,It,Dt,Pt,Ht,vt,Rt,Bt,Yt,tr;const wr=X-fe,ur=se-fe,cr=te-ue,rr=ae-ue;vt=wr*rr,Ve=Nc*wr,qe=Ve-(Ve-wr),bt=wr-qe,Ve=Nc*rr,Et=Ve-(Ve-rr),It=rr-Et,Rt=bt*It-(vt-qe*Et-bt*Et-qe*It),Bt=cr*ur,Ve=Nc*cr,qe=Ve-(Ve-cr),bt=cr-qe,Ve=Nc*ur,Et=Ve-(Ve-ur),It=ur-Et,Yt=bt*It-(Bt-qe*Et-bt*Et-qe*It),Dt=Rt-Yt,He=Rt-Dt,Rw[0]=Rt-(Dt+He)+(He-Yt),Pt=vt+Dt,He=Pt-vt,Ht=vt-(Pt-He)+(Dt-He),Dt=Ht-Bt,He=Ht-Dt,Rw[1]=Ht-(Dt+He)+(He-Bt),tr=Pt+Dt,He=tr-Pt,Rw[2]=Pt-(tr-He)+(Dt-He),Rw[3]=tr;let _r=function(Wn,mn){let es=mn[0];for(let En=1;En<4;En++)es+=mn[En];return es}(0,Rw),Rr=22204460492503146e-32*Te;if(_r>=Rr||-_r>=Rr||(He=X-wr,Ae=X-(wr+He)+(He-fe),He=se-ur,We=se-(ur+He)+(He-fe),He=te-cr,Ie=te-(cr+He)+(He-ue),He=ae-rr,ze=ae-(rr+He)+(He-ue),Ae===0&&Ie===0&&We===0&&ze===0)||(Rr=11093356479670487e-47*Te+jPe*Math.abs(_r),_r+=wr*ze+rr*Ae-(cr*We+ur*Ie),_r>=Rr||-_r>=Rr))return _r;vt=Ae*rr,Ve=Nc*Ae,qe=Ve-(Ve-Ae),bt=Ae-qe,Ve=Nc*rr,Et=Ve-(Ve-rr),It=rr-Et,Rt=bt*It-(vt-qe*Et-bt*Et-qe*It),Bt=Ie*ur,Ve=Nc*Ie,qe=Ve-(Ve-Ie),bt=Ie-qe,Ve=Nc*ur,Et=Ve-(Ve-ur),It=ur-Et,Yt=bt*It-(Bt-qe*Et-bt*Et-qe*It),Dt=Rt-Yt,He=Rt-Dt,tu[0]=Rt-(Dt+He)+(He-Yt),Pt=vt+Dt,He=Pt-vt,Ht=vt-(Pt-He)+(Dt-He),Dt=Ht-Bt,He=Ht-Dt,tu[1]=Ht-(Dt+He)+(He-Bt),tr=Pt+Dt,He=tr-Pt,tu[2]=Pt-(tr-He)+(Dt-He),tu[3]=tr;const Wr=QB(4,Rw,4,tu,uQ);vt=wr*ze,Ve=Nc*wr,qe=Ve-(Ve-wr),bt=wr-qe,Ve=Nc*ze,Et=Ve-(Ve-ze),It=ze-Et,Rt=bt*It-(vt-qe*Et-bt*Et-qe*It),Bt=cr*We,Ve=Nc*cr,qe=Ve-(Ve-cr),bt=cr-qe,Ve=Nc*We,Et=Ve-(Ve-We),It=We-Et,Yt=bt*It-(Bt-qe*Et-bt*Et-qe*It),Dt=Rt-Yt,He=Rt-Dt,tu[0]=Rt-(Dt+He)+(He-Yt),Pt=vt+Dt,He=Pt-vt,Ht=vt-(Pt-He)+(Dt-He),Dt=Ht-Bt,He=Ht-Dt,tu[1]=Ht-(Dt+He)+(He-Bt),tr=Pt+Dt,He=tr-Pt,tu[2]=Pt-(tr-He)+(Dt-He),tu[3]=tr;const Dr=QB(Wr,uQ,4,tu,dQ);vt=Ae*ze,Ve=Nc*Ae,qe=Ve-(Ve-Ae),bt=Ae-qe,Ve=Nc*ze,Et=Ve-(Ve-ze),It=ze-Et,Rt=bt*It-(vt-qe*Et-bt*Et-qe*It),Bt=Ie*We,Ve=Nc*Ie,qe=Ve-(Ve-Ie),bt=Ie-qe,Ve=Nc*We,Et=Ve-(Ve-We),It=We-Et,Yt=bt*It-(Bt-qe*Et-bt*Et-qe*It),Dt=Rt-Yt,He=Rt-Dt,tu[0]=Rt-(Dt+He)+(He-Yt),Pt=vt+Dt,He=Pt-vt,Ht=vt-(Pt-He)+(Dt-He),Dt=Ht-Bt,He=Ht-Dt,tu[1]=Ht-(Dt+He)+(He-Bt),tr=Pt+Dt,He=tr-Pt,tu[2]=Pt-(tr-He)+(Dt-He),tu[3]=tr;const fn=QB(Dr,dQ,4,tu,hQ);return hQ[fn-1]}(x,b,T,k,P,O,Y)}(h[0],h[1],l[0],l[1],u[0],u[1]);return p>0?-1:p<0?1:0}function Ay(h,l){const u=h.point,p=l.point;return u[0]>p[0]?1:u[0]p[1]?1:-1:function(x,b,T){return x.left!==b.left?x.left?1:-1:JB(T,x.otherEvent.point,b.otherEvent.point)!==0?x.isBelow(b.otherEvent.point)?-1:1:!x.isSubject&&b.isSubject?1:-1}(h,l,u)}function Ny(h,l,u){const p=new Lw(l,!1,h,h.isSubject),x=new Lw(l,!0,h.otherEvent,h.isSubject);return cm(h.point,h.otherEvent.point)&&console.warn("what is that, a collapsed segment?",h),p.contourId=x.contourId=h.contourId,Ay(x,h.otherEvent)>0&&(h.otherEvent.left=!0,x.left=!1),h.otherEvent.otherEvent=x,h.otherEvent=p,u.push(x),u.push(p),u}function zP(h,l){return h[0]*l[1]-h[1]*l[0]}function e$(h,l){return h[0]*l[0]+h[1]*l[1]}function t$(h,l,u){const p=function(P,O,$,V){const G=[O[0]-P[0],O[1]-P[1]],Y=[V[0]-$[0],V[1]-$[1]];function X(We,ze,He){return[We[0]+ze*He[0],We[1]+ze*He[1]]}const te=[$[0]-P[0],$[1]-P[1]];let se=zP(G,Y),ae=se*se;const fe=e$(G,G);if(ae>0){const We=zP(te,Y)/se;if(We<0||We>1)return null;const ze=zP(te,G)/se;return ze<0||ze>1?null:We===0||We===1?[X(P,We,G)]:ze===0||ze===1?[X($,ze,Y)]:[X(P,We,G)]}if(se=zP(te,G),ae=se*se,ae>0)return null;const ue=e$(G,te)/fe,Te=ue+e$(G,Y)/fe,Ae=Math.min(ue,Te),Ie=Math.max(ue,Te);return Ae<=1&&Ie>=0?Ae===1?[X(P,Ae>0?Ae:0,G)]:Ie===0?[X(P,Ie<1?Ie:1,G)]:[X(P,Ae>0?Ae:0,G),X(P,Ie<1?Ie:1,G)]:null}(h.point,h.otherEvent.point,l.point,l.otherEvent.point),x=p?p.length:0;if(x===0||x===1&&(cm(h.point,l.point)||cm(h.otherEvent.point,l.otherEvent.point))||x===2&&h.isSubject===l.isSubject)return 0;if(x===1)return!cm(h.point,p[0])&&!cm(h.otherEvent.point,p[0])&&Ny(h,p[0],u),!cm(l.point,p[0])&&!cm(l.otherEvent.point,p[0])&&Ny(l,p[0],u),1;const b=[];let T=!1,k=!1;return cm(h.point,l.point)?T=!0:Ay(h,l)===1?b.push(l,h):b.push(h,l),cm(h.otherEvent.point,l.otherEvent.point)?k=!0:Ay(h.otherEvent,l.otherEvent)===1?b.push(l.otherEvent,h.otherEvent):b.push(h.otherEvent,l.otherEvent),T&&k||T?(l.type=1,h.type=l.inOut===h.inOut?2:3,T&&!k&&Ny(b[1].otherEvent,b[0].point,u),2):k?(Ny(b[0],b[1].point,u),3):b[0]!==b[3].otherEvent?(Ny(b[0],b[1].point,u),Ny(b[1],b[2].point,u),3):(Ny(b[0],b[1].point,u),Ny(b[3].otherEvent,b[2].point,u),3)}function EPe(h,l){if(h===l)return 0;if(JB(h.point,h.otherEvent.point,l.point)!==0||JB(h.point,h.otherEvent.point,l.otherEvent.point)!==0)return cm(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 Ay(h,l)===1?1:-1}class kPe{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function APe(h,l,u,p){let x,b=h+1,T=l[h].point;const k=l.length;for(bp;)b--;return b}function NPe(h,l,u){const p=new kPe;if(h.prevInResult!=null){const x=h.prevInResult,b=x.outputContourId;if(x.resultTransition>0){const T=l[b];if(T.holeOf!=null){const k=T.holeOf;l[k].holeIds.push(u),p.holeOf=k,p.depth=l[b].depth}else l[b].holeIds.push(u),p.holeOf=b,p.depth=l[b].depth+1}else p.holeOf=null,p.depth=l[b].depth}else p.holeOf=null,p.depth=0;return p}const mQ=Math.max,pQ=Math.min;let UP=0;function gQ(h,l,u,p,x,b){let T,k,P,O,$,V;for(T=0,k=h.length-1;T0?V.left=!0:$.left=!0;const G=P[0],Y=P[1];x[0]=pQ(x[0],G),x[1]=pQ(x[1],Y),x[2]=mQ(x[2],G),x[3]=mQ(x[3],Y),p.push($),p.push(V)}}const VP=[];function yQ(h,l,u){let p=h,x=l;typeof h[0][0][0]=="number"&&(p=[h]),typeof l[0][0][0]=="number"&&(x=[l]);let b=function(G,Y,X){let te=null;return G.length*Y.length===0&&(X===0?te=VP:X===2?te=G:(X===1||X===3)&&(te=G.length===0?Y:G)),te}(p,x,u);if(b)return b===VP?null:b;const T=[1/0,1/0,-1/0,-1/0],k=[1/0,1/0,-1/0,-1/0],P=function(G,Y,X,te,se){const ae=new X0(void 0,Ay);let fe,ue,Te,Ae,Ie,We;for(Te=0,Ae=G.length;Tete[2]||te[0]>X[2]||X[1]>te[3]||te[1]>X[3])&&(se===0?ae=VP:se===2?ae=G:(se===1||se===3)&&(ae=G.concat(Y))),ae}(p,x,T,k,u),b)return b===VP?null:b;const O=function(G,Y,X,te,se,ae){const fe=new YB(EPe),ue=[],Te=Math.min(te[2],se[2]);let Ae,Ie,We;for(;G.length!==0;){let ze=G.pop();if(ue.push(ze),ae===0&&ze.point[0]>Te||ae===2&&ze.point[0]>te[2])break;if(ze.left){Ie=Ae=fe.insert(ze),We=fe.minNode(),Ae=Ae!==We?fe.prev(Ae):null,Ie=fe.next(Ie);const He=Ae?Ae.key:null;let Ve;if(y2(ze,He,ae),Ie&&t$(ze,Ie.key,G)===2&&(y2(ze,He,ae),y2(Ie.key,ze,ae)),Ae&&t$(Ae.key,ze,G)===2){let qe=Ae;qe=qe!==We?fe.prev(qe):null,Ve=qe?qe.key:null,y2(He,Ve,ae),y2(ze,He,ae)}}else ze=ze.otherEvent,Ie=Ae=fe.find(ze),Ae&&Ie&&(Ae=Ae!==We?fe.prev(Ae):null,Ie=fe.next(Ie),fe.remove(ze),Ie&&Ae&&t$(Ae.key,Ie.key,G))}return ue}(P,0,0,T,k,u),$=function(G){let Y,X;const te=function(fe){let ue,Te,Ae,Ie,We;const ze=[];for(Te=0,Ae=fe.length;Te{se[We]=!0,We=te.length)&&te[Ae];);ae.push(ue)}return ae}(O),V=[];for(let G=0;G<$.length;G++){let Y=$[G];if(Y.isExterior()){let X=[Y.points];for(let te=0;te{T.push(new Ft(V,P+(V-k)/(O-k)*($-P)))}:(T,k,P,O,$,V)=>{T.push(new Ft(k+(V-P)/($-P)*(O-k),V))};for(const T of h){const k=[];for(const P of T){if(P.length<=2)continue;const O=[];for(let G=0;Gl&&b(O,Y,X,te,se,l):ae>u?fe=l&&b(O,Y,X,te,se,l),fe>u&&ae<=u&&b(O,Y,X,te,se,u)}let $=P[P.length-1];const V=p===0?$.x:$.y;V>=l&&V<=u&&O.push($),O.length&&($=O[O.length-1],O[0].x===$.x&&O[0].y===$.y||O.push(O[0]),k.push(O))}k.length&&x.push(k)}return x}function CPe(h,l){const u=yQ(r$(h),r$([l]),0);return u==null?[]:xQ(u)}function IPe(h,l,u=0){let x=r$(h,65536);const b=[];for(;l.valid();l.next()){const[T,k]=l.get();let P=T.x*65536,O=T.y*65536,$=k.x*65536,V=k.y*65536;const G=$-P,Y=V-O,X=Math.hypot(G,Y);if(X===0)continue;P-=G*u,O-=Y*u,$+=G*u,V+=Y*u;const te=Math.trunc(Y/X*3),se=-Math.trunc(G/X*3);b.push([[[P,O],[$,V],[$+te,V+se],[P+te,O+se],[P,O]]])}return b.length>0&&(x=yQ(x,b,2)),xQ(x,1/65536,128)}function r$(h,l=1){return[h.map(u=>u.map(p=>[p.x*l,p.y*l]))]}function xQ(h,l=1,u){return h.map(p=>p.map((x,b)=>{const T=x.map(k=>{let P=k[0],O=k[1];return u&&(P=Math.round(P/u)*u,O=Math.round(O/u)*u),new Ft(P*l,O*l)._round()});return b>0&&T.reverse(),T}))}class n${constructor(l,u){this.layoutVertexArray=new Ec,this.indexArray=new Pi,this.lineIndexArray=new Fu,this.triangleSegments=new Os,this.lineSegments=new Os,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.uploaded=!1,u&&(this.elevatedLayoutVertexArray=new Zc)}update(l,u,p,x,b,T,k,P){this.programConfigurations.updatePaintArrays(l,u,b,p,x,T,k,P)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,cPe.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,uPe.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(l,u,p,x,b,T,k){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,u,p,x,b,T,void 0,k)}}class GP{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 n$(l,!1),this.elevationBufferData=new n$(l,!0),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=l.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=l.sourceLayerIndex,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){this.hasPattern=WB("fill",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("fill-sort-key"),T=[];for(const{feature:k,id:P,index:O,sourceLayerIndex:$}of l){const V=this.layers[0]._featureFilter.needGeometry,G=jn(k,V);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),G,p))continue;const Y=b?b.evaluate(G,{},p,u.availableImages):void 0,X={id:P,properties:k.properties,type:k.type,sourceLayerIndex:$,index:O,geometry:V?G.geometry:Kr(k,p,x),patterns:{},sortKey:Y};T.push(X)}b&&T.sort((k,P)=>k.sortKey-P.sortKey);for(const k of T){const{geometry:P,index:O,sourceLayerIndex:$}=k;if(this.hasPattern){const V=KB("fill",this.layers,k,this.zoom,this.pixelRatio,u);this.patternFeatures.push(V)}else this.addFeature(k,P,O,p,{},u.availableImages,u.brightness,u.elevationFeatures);u.featureIndex.insert(l[O].feature,P,O,$,this.index)}}update(l,u,p,x,b,T,k){this.bufferData.update(l,u,p,x,b,T,k,this.worldview),this.elevationBufferData.update(l,u,p,x,b,T,k,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(l,u,p,x,b,T,k,this.worldview)}addFeatures(l,u,p,x,b,T){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,u,p,x,T,l.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(l){this.bufferData.upload(l),this.elevationBufferData.upload(l),this.elevatedStructures&&this.elevatedStructures.upload(l)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(l,u,p,x,b,T=[],k,P){const O=p2(u,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(l,O,x,p,P):this.addGeometry(O,this.bufferData),this.bufferData.populatePaintArrays(l,p,b,T,x,k,this.worldview),this.elevationBufferData.populatePaintArrays(l,p,b,T,x,k,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(l,u,p,x,b){this.elevatedStructures&&(this.elevatedStructures.construct(l),this.elevatedStructures.populatePaintArrays(u,p,x,b,this.worldview))}addElevatedRoadFeature(l,u,p,x,b){const T=new Array,k=Vs.getElevationFeature(l,b);if(!k)return void this.addGeometry(u,this.bufferData);{const O=this.clipPolygonsToTile(u,1);O.length>0&&T.push({polygons:O,elevationFeature:k,elevationTileID:p})}const P={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(l,{},p),featureIndex:x};for(const O of T)if(O.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new eu(O.elevationTileID,this.layers,this.zoom,this.lut));const V=O.elevationFeature.isTunnel();let G=0;l.properties.hasOwnProperty(Bs)&&(G=+l.properties[Bs]),this.elevatedStructures.addPortalCandidates(O.elevationFeature.id,O.polygons,V,O.elevationFeature,G)}O.elevationFeature.constantHeight==null&&(O.polygons=this.prepareElevatedPolygons(O.polygons,O.elevationFeature,O.elevationTileID));const $=new Ys(p,O.elevationTileID);this.addElevatedGeometry(O.polygons,$,O.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,x,P)}}addElevatedGeometry(l,u,p,x,b,T){const k={elevation:p,elevationSampler:u,bias:x,index:b,featureInfo:T},[P,O]=this.addGeometry(l,this.elevationBufferData,k);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:P,max:O}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,P),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,O))}addGeometry(l,u,p){let x=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,T=null;p&&(T=p.elevationSampler.constantElevation(p.elevation,p.bias),T!=null&&(x=T,b=T));const k=(P,O,$)=>{if(p!=null)if(O.push(P),T!=null)u.elevatedLayoutVertexArray.emplaceBack(T),$.push(T);else{const V=p.elevationSampler.pointElevation(P,p.elevation,p.bias);u.elevatedLayoutVertexArray.emplaceBack(V),$.push(V),x=Math.min(x,V),b=Math.max(b,V)}};for(const P of l){let O=0;for(const ue of P)O+=ue.length;const $=u.triangleSegments.prepareSegment(O,u.layoutVertexArray,u.indexArray),V=$.vertexLength,G=[],Y=[],X=[],te=[],se=[],ae=u.layoutVertexArray.length;for(const ue of P){if(ue.length===0)continue;ue!==P[0]&&Y.push(G.length/2);const Te=u.lineSegments.prepareSegment(ue.length,u.layoutVertexArray,u.lineIndexArray),Ae=Te.vertexLength;p&&se.push(u.layoutVertexArray.length-ae),k(ue[0],X,te),u.layoutVertexArray.emplaceBack(ue[0].x,ue[0].y),u.lineIndexArray.emplaceBack(Ae+ue.length-1,Ae),G.push(ue[0].x),G.push(ue[0].y);for(let Ie=1;Ie0&&p&&this.elevationMode==="hd-road-base"){const ue=p.elevation.isTunnel(),Te=p.elevation.safeArea,Ae=this.elevatedStructures.addVertices(X,te);this.elevatedStructures.addTriangles(fe,Ae,ue);const Ie=se.length;if(Ie>0){for(let We=0;We=p&&Y.max.x<=b&&Y.min.y>=x&&Y.max.y<=T?P:O).push(G)}if(P.length===l.length)return l;const $=[new Ft(p,x),new Ft(b,x),new Ft(b,T),new Ft(p,T),new Ft(p,x)],V=P;for(const G of O)V.push(...CPe(G,$));return V}}let vQ,_Q,bQ,wQ;jr(GP,"FillBucket",{omit:["layers","patternFeatures"]}),jr(n$,"FillBufferData"),jr(eu,"ElevatedStructures");class HP{constructor(l,u,p,x){if(this.triangleCount=u.length/3,this.min=new Ft(0,0),this.max=new Ft(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,T]=[l[0].clone(),l[0].clone()];for(let V=1;VV.cellIdx-G.cellIdx||V.triIdx-G.triIdx);let $=0;for(;$this.max.x||this.min.x>l.x||l.y>this.max.y||this.min.y>l.y)return;const p=um(l.x-this.min.x,this.xScale,this.cellsX),x=um(l.y-this.min.y,this.yScale,this.cellsY),b=this.cells[x*this.cellsX+p];if(b){this._lazyInitLookup();for(let T=0;Tthis.max.x||this.min.x>u.x||l.y>this.max.y||this.min.y>u.y)return;this._lazyInitLookup();const x=um(l.x-this.min.x,this.xScale,this.cellsX),b=um(u.x-this.min.x,this.xScale,this.cellsX),T=um(l.y-this.min.y,this.yScale,this.cellsY),k=um(u.y-this.min.y,this.yScale,this.cellsY);for(let P=T;P<=k;P++)for(let O=x;O<=b;O++){const $=this.cells[P*this.cellsX+O];if($)for(let V=0;V<$.len;V++){const G=this.payload[$.start+V],Y=Math.floor(G/8),X=1<u.fqid),this.index=l.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.footprints=[],this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){for(const p of this.footprints)u.push({footprint:p,id:l})}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){const b=[];for(const{feature:T,id:k,index:P,sourceLayerIndex:O}of l){const $=this.layers[0]._featureFilter.needGeometry,V=jn(T,$);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),V,p))continue;const G={id:k,properties:T.properties,type:T.type,sourceLayerIndex:O,index:P,geometry:$?V.geometry:Kr(T,p,x),patterns:{}};b.push(G)}for(const T of b){const{geometry:k,index:P,sourceLayerIndex:O}=T;this.addFeature(T,k,P,p,{},u.availableImages,u.brightness),u.featureIndex.insert(l[P].feature,k,P,O,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(l){}update(l,u,p,x,b,T,k){}destroy(){}addFeature(l,u,p,x,b,T=[],k){for(const P of p2(u,2)){const O=[],$=[],V=[],G=new Ft(1/0,1/0),Y=new Ft(-1/0,-1/0);for(const se of P)if(se.length!==0){se!==P[0]&&V.push($.length/2);for(let ae=0;ael.max.x||h.max.xl.max.y||h.max.ynew Ft((P.x+b.x*fr)*k-T.x*fr,(P.y+b.y*fr)*k-T.y*fr))}return i$(u,x,h.indices,0,h.indices.length,0,0)}function AQ(h,l,u,p){const x=Math.pow(2,p.z-u.z);return new Ft((h+u.x*fr)*x-p.x*fr,(l+u.y*fr)*x-p.y*fr)}function NQ(h,l){const u=[];l.grid.queryPoint(h,u);const p=l.indices,x=l.vertices;for(let b=0;b0&&(p.length>1&&u.push(p),p=[])}return p.length>1&&u.push(p),u}const o$=ln.types,UPe=["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"],VPe=["fill-extrusion-flood-light-ground-radius"],qPe=Math.pow(2,13),GPe=Math.pow(2,15)-1,ZP=new Ft(0,1),Vp=2147483648,XP=1073741824;function v2(h,l,u,p,x,b,T,k){h.emplaceBack((l<<1)+T,(u<<1)+b,(Math.floor(p*qPe)<<1)+x,Math.round(k))}function _2(h,l,u){h.emplaceBack(l.x*fr,l.y*fr,u?1:0)}function QP(h,l,u,p,x,b){h.emplaceBack(l.x,l.y,(u.x<<1)+p,(u.y<<1)+x,b)}function b2(h,l,u){h.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}class IQ{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class l${constructor(){this.centroidXY=new Ft(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 Ft(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ft(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ft(0,0)}span(){return new Ft(this.max.x-this.min.x,this.max.y-this.min.y)}}class c${constructor(){this.acc=new Ft(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(l,u){l.min.x===Number.MAX_VALUE&&(l.min.x=l.max.x=u.x,l.min.y=l.max.y=u.y)}appendEdge(l,u,p){this.accCount++,this.acc._add(u);let 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===fr)&&u.x===p.x)!=((u.y===0||u.y===fr)&&u.y===p.y)&&this.processBorderOverlap(u,p),x&&this.checkBorderIntersection(u,p)}checkBorderIntersection(l,u){u.x<0!=l.x<0&&this.addBorderIntersection(0,sn(u.y,l.y,(0-u.x)/(l.x-u.x))),u.x>fr!=l.x>fr&&this.addBorderIntersection(1,sn(u.y,l.y,(fr-u.x)/(l.x-u.x))),u.y<0!=l.y<0&&this.addBorderIntersection(2,sn(u.x,l.x,(0-u.y)/(l.y-u.y))),u.y>fr!=l.y>fr&&this.addBorderIntersection(3,sn(u.x,l.x,(fr-u.y)/(l.y-u.y)))}addBorderIntersection(l,u){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const p=this.borders[l];up[1]&&(p[1]=u)}processBorderOverlap(l,u){if(l.x===u.x){if(l.y===u.y)return;const p=l.x===0?0:1;this.addBorderIntersection(p,u.y),this.addBorderIntersection(p,l.y)}else{const p=l.y===0?2:3;this.addBorderIntersection(p,u.x),this.addBorderIntersection(p,l.x)}}centroid(){return this.accCount===0?new Ft(0,0):new Ft(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 PQ(h,l){const u=h.add(l)._unit(),p=pe(h.x*u.x+h.y*u.y,-1,1);var x,b,T;return T=Math.acos(p),Math.min(4,Math.max(-4,Math.tan(T)))/4*GPe*((x=h).x*(b=l).y-x.y*b.x<0?-1:1)}const HPe=[h=>h.x<0,h=>h.x>fr,h=>h.y<0,h=>h.y>fr];function WPe(h,l,u,p){const x=[4];if(p===0)return x;u._mult(p);const b=h.sub(u),T=l.sub(u),k=[h,l,b,T];for(let P=0;P<4;P++)for(const O of k)if(HPe[P](O)){x.push(P);break}return x}class u${constructor(l){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new WE,this.indexArray=new Pi,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>VPe.includes(u)),this._segments=new Os,this.hiddenByLandmarkVertexArray=new Ew,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Os}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(l,u,p,x=!1){const b=l.length;if(b>2){let T=Math.max(0,this._segments.get().length-1);const k=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[T].length);let P;T!==this._segments.get().length-1&&(T++,this._segmentToGroundQuads[T]=[],this._segmentToRegionTriCounts[T]=[0,0,0,0,0]);{const O=l[0],$=l[1];P=PQ(O.sub(l[b-1])._perp()._unit(),$.sub(O)._perp()._unit())}for(let O=0;Ox.region-b.region);for(let p=0;pP+O,0);let k=0;for(let P=0;P<=4;P++){const O=T[P];if(O!==0){let $=this.regionSegments[P];$||($=this.regionSegments[P]=new Os);const V={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+k,vertexLength:b.vertexLength,primitiveLength:O};$.get().push(V)}k+=O}for(let P=0;P0?this.hiddenByLandmarkVertexBuffer=l.createVertexBuffer(this.hiddenByLandmarkVertexArray,OPe.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 JP{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 Pi,this.footprintVertices=new Ec,this.footprintSegments=[],this.layoutVertexArray=new HE,this.centroidVertexArray=new PP,this.wallVertexArray=new i2,this.indexArray=new Pi,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>UPe.includes(u)),this.segments=new Os,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.groundEffect=new u$(l),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){this.features=[],this.hasPattern=WB("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=zt(p),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:b,id:T,index:k,sourceLayerIndex:P}of l){const O=this.layers[0]._featureFilter.needGeometry,$=jn(b,O);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),$,p))continue;const V={id:T,sourceLayerIndex:P,index:k,geometry:O?$.geometry:Kr(b,p,x),properties:b.properties,type:b.type,patterns:{}},G=this.layoutVertexArray.length,Y=o$[V.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:b.id,feature:KB("fill-extrusion",this.layers,V,this.zoom,this.pixelRatio,u)});else if(this.wallMode)for(const X of V.geometry)for(const te of CQ(X,Y))this.addFeature(b.id,V,[te],k,p,{},u.availableImages,x,u.brightness);else this.addFeature(b.id,V,V.geometry,k,p,{},u.availableImages,x,u.brightness);u.featureIndex.insert(b,V.geometry,k,P,this.index,G)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(l,u,p,x,b,T){for(const{featureId:k,feature:P}of this.features){const O=o$[P.type]==="Polygon",{geometry:$}=P;if(this.wallMode)for(const V of $)for(const G of CQ(V,O))this.addFeature(k,P,[G],P.index,u,p,x,b,T);else this.addFeature(k,P,$,P.index,u,p,x,b,T)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(l,u,p,x,b,T,k){this.programConfigurations.updatePaintArrays(l,u,b,p,x,T,k,this.worldview),this.groundEffect.update(l,u,b,p,x,T,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,BPe),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.wallVertexBuffer=l.createVertexBuffer(this.wallVertexArray,DPe.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=l.createVertexBuffer(this.layoutVertexExtArray,FPe.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,MPe.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(l,u,p,x,b,T,k,P,O){const $=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(u,{})/this.tileToMeter,V=[new Ft(0,0),new Ft(fr,fr)],G=P.projection,Y=G.name==="globe",X=this.wallMode||o$[u.type]==="Polygon",te=new c$;te.centroidDataIndex=this.centroidData.length;const se=new l$;se.buildingId=l,u.properties&&u.properties.hasOwnProperty("building_id")&&(se.buildingId=Number(u.properties.building_id)),te.buildingId=se.buildingId;const ae=this.layers[0].paint.get("fill-extrusion-base").evaluate(u,{},b)<=0,fe=this.layers[0].paint.get("fill-extrusion-height").evaluate(u,{},b);let ue;if(se.height=fe,se.vertexArrayOffset=this.layoutVertexArray.length,se.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Y&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new _w),this.wallMode){if(Y)return void hr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(p.length!==1)return;ue=function(Ve){const qe=Ve[0].x===Ve[Ve.length-1].x&&Ve[0].y===Ve[Ve.length-1].y;(function(cr){let rr=0;const _r=cr.length;for(let Rr=0;Rr<_r;Rr++)rr+=(cr[(Rr+1)%_r].x-cr[Rr].x)*(cr[(Rr+1)%_r].y+cr[Rr].y);return rr>=0})(Ve)||(Ve=Ve.reverse());const Et={geometry:[],joinNormals:[],indices:[]},It=[],Dt=[],Pt=[];let Ht=Ve.length;for(;Ht>=2&&Ve[Ht-1].equals(Ve[Ht-2]);)Ht--;if(Ht<(qe?3:2))return Et;let vt,Rt,Bt,Yt,tr,wr=0;for(;wr0;let Dr="miter";const fn=2;Dr==="miter"&&Rr>fn&&(Dr="bevel"),Dr==="bevel"&&(Rr>100&&(Dr="flipbevel"),Rr{const ms=new Ft(mn.x,mn.y),ns=new Ft(mn.x,mn.y);ms.x+=es.x*ji,ms.y+=es.y*ji,ns.x-=es.x*Math.max(En,1),ns.y-=es.y*Math.max(En,1),Pt.push(es),It.push(ms),Dt.push(ns)};if(Dr==="miter")rr._mult(Rr),Wn(vt,rr,0,0);else if(Dr==="flipbevel")rr=tr.mult(-1),Wn(vt,rr,0,0),Wn(vt,rr.mult(-1),0,0);else{const mn=-Math.sqrt(Rr*Rr-1),es=Wr?mn:0,En=Wr?0:mn;Rt&&Wn(vt,Yt,es,En),Bt&&Wn(vt,tr,es,En)}}Et.geometry=[...It,...Dt.reverse(),It[0]],Et.joinNormals=[...Pt,...Pt.reverse(),Pt[Pt.length-1]];const ur=Et.geometry.length-1;for(let cr=0;crVe<(qe.length-1)/2||Ve===qe.length-1,Ae=this.wallMode?[p]:p2(p,500);for(let Ve=Ae.length-1;Ve>=0;Ve--){const qe=Ae[Ve];(qe.length===0||YPe(qe[0]))&&Ae.splice(Ve,1)}let Ie;if(Y)Ie=BQ(Ae,V,b);else{Ie=[];for(const Ve of Ae)Ie.push({polygon:Ve,bounds:V})}const We=X?this.edgeRadius:0,ze=We>0&&this.zoom<17,He=(Ve,qe)=>{if(Ve.length===0)return!1;const bt=Ve[Ve.length-1];return qe.x===bt.x&&qe.y===bt.y};for(const{polygon:Ve,bounds:qe}of Ie){let bt=0,Et=0;for(const Ht of Ve)X&&!Ht[0].equals(Ht[Ht.length-1])&&Ht.push(Ht[0]),Et+=X?Ht.length-1:Ht.length;const It=this.segments.prepareSegment((X?5:4)*Et,this.layoutVertexArray,this.indexArray);se.footprintSegIdx<0&&(se.footprintSegIdx=this.footprintSegments.length),se.polygonSegIdx<0&&(se.polygonSegIdx=this.polygonSegments.length);const Dt={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Pt=new IQ;if(Pt.vertexOffset=this.footprintVertices.length,Pt.indexOffset=3*this.footprintIndices.length,Pt.ringIndices=[],X){const Ht=[],vt=[];bt=It.vertexLength;for(let Bt=0;Bt4&&DQ(vt[vt.length-2],vt[0],vt[1]),Bt=We?KPe(vt[vt.length-2],vt[0],vt[1],We):0;const Yt=[];let tr,wr,ur;wr=vt[1].sub(vt[0])._perp()._unit();let cr=!0;for(let rr=1,_r=0;rr0?1:0,es=Rr.dist(Wr);if(_r+es>32768&&(_r=0),We){ur=Dr.sub(Wr)._perp()._unit();let ns=LQ(Rr,Wr,Dr,RQ(wr,ur),We);isNaN(ns)&&(ns=0);const $s=Wr.sub(Rr)._unit();Rr=Rr.add($s.mult(Bt))._round(),Wr=Wr.add($s.mult(-ns))._round(),Bt=ns,wr=ur,ae&&this.zoom>=17&&(He(Yt,Rr)||Yt.push(Rr),He(Yt,Wr)||Yt.push(Wr))}const En=It.vertexLength,ji=vt.length>4&&DQ(Rr,Wr,Dr);let ms=OQ(_r,Rt,cr);if(v2(this.layoutVertexArray,Rr.x,Rr.y,Wn,mn,0,0,ms),v2(this.layoutVertexArray,Rr.x,Rr.y,Wn,mn,0,1,ms),this.wallMode){const ns=Te(rr-1,vt),$s=ue.joinNormals[rr-1];_2(this.wallVertexArray,$s,ns),_2(this.wallVertexArray,$s,ns)}if(_r+=es,ms=OQ(_r,ji,!cr),Rt=ji,v2(this.layoutVertexArray,Wr.x,Wr.y,Wn,mn,0,0,ms),v2(this.layoutVertexArray,Wr.x,Wr.y,Wn,mn,0,1,ms),this.wallMode){const ns=Te(rr,vt),$s=ue.joinNormals[rr];_2(this.wallVertexArray,$s,ns),_2(this.wallVertexArray,$s,ns)}if(It.vertexLength+=4,this.indexArray.emplaceBack(En+0,En+1,En+2),this.indexArray.emplaceBack(En+1,En+3,En+2),It.primitiveLength+=2,We){const ns=bt+(rr===1?vt.length-2:rr-2),$s=rr===1?bt:ns+1;if(this.indexArray.emplaceBack(En+1,ns,En+3),this.indexArray.emplaceBack(ns,$s,En+3),It.primitiveLength+=2,tr===void 0&&(tr=En),!d$(Dr,vt[rr],qe)){const vi=rr===vt.length-1?tr:It.vertexLength;this.indexArray.emplaceBack(En+2,En+3,vi),this.indexArray.emplaceBack(En+3,vi+1,vi),this.indexArray.emplaceBack(En+3,$s,vi+1),It.primitiveLength+=3}cr=!cr}if(Y){const ns=this.layoutVertexExtArray,$s=G.projectTilePoint(Rr.x,Rr.y,b),vi=G.projectTilePoint(Wr.x,Wr.y,b),Xa=G.upVector(b,Rr.x,Rr.y),_i=G.upVector(b,Wr.x,Wr.y);b2(ns,$s,Xa),b2(ns,$s,Xa),b2(ns,vi,_i),b2(ns,vi,_i)}}X&&(bt+=vt.length-1),ae&&We&&this.zoom>=17&&(Yt.length!==0&&He(Yt,Yt[0])&&Yt.pop(),this.groundEffect.addData(Yt,qe,$,We>0))}this.footprintSegments.push(Pt),Dt.triangleCount=this.indexArray.length-Dt.triangleArrayOffset,this.polygonSegments.push(Dt),++se.footprintSegLen,++se.polygonSegLen}if(se.vertexCount=this.layoutVertexArray.length-se.vertexArrayOffset,se.groundVertexCount=this.groundEffect.vertexArray.length-se.groundVertexArrayOffset,se.vertexCount!==0){if(se.centroidXY=te.borders?ZP:this.encodeCentroid(te,se),u.properties&&u.properties.hasOwnProperty("building_id")){const Ve=se.buildingId;let qe=this.buildingGroups.get(Ve);qe||(qe={accX:0,accY:0,accCount:0,mergedMin:new Ft(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ft(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Ve,qe)),qe.accX+=te.acc.x,qe.accY+=te.acc.y,qe.accCount+=te.accCount,qe.mergedMin.x=Math.min(qe.mergedMin.x,se.min.x),qe.mergedMin.y=Math.min(qe.mergedMin.y,se.min.y),qe.mergedMax.x=Math.max(qe.mergedMax.x,se.max.x),qe.mergedMax.y=Math.max(qe.mergedMax.y,se.max.y),qe.partIndices.push(this.centroidData.length)}if(this.centroidData.push(se),te.borders){this.featuresOnBorder.push(te);const Ve=this.featuresOnBorder.length-1;for(let qe=0;qethis.featuresOnBorder[u].borders[l][0]-this.featuresOnBorder[p].borders[l][0])}splitToSubtiles(){const l=[];for(let k=0;kfr),$=2*O+(+(P.min.x+P.max.x>fr)^O);for(let V=0;Vk.triangleSegmentIdx===P.triangleSegmentIdx?k.subtile-P.subtile:k.triangleSegmentIdx-P.triangleSegmentIdx);let p=0,x=0,b=0;for(const k of l){if(k.triangleSegmentIdx!==p)break;b++}const T=l.length;for(;x!==l.length;){p=l[x].triangleSegmentIdx;let k=0,P=x,O=x;for(let $=P;$0&&this.triangleSubSegments.push({segment:Y,min:V,max:G}),P=O;for(let X=P;X[te[0]*(1-ae[0])+se[0]*ae[0],te[1]*(1-ae[1])+se[1]*ae[1]],Y=[],X=[];for(const te of this.triangleSubSegments){Y[0]=te.min.x/fr,Y[1]=te.min.y/fr,X[0]=te.max.x/fr,X[1]=te.max.y/fr;const se=G($,V,Y),ae=G($,V,X);if(new ys([se[0],se[1],b],[ae[0],ae[1],T]).intersectsPrecise(p)===0){O&&(x.segments.push(O),O=void 0);continue}const fe=te.segment;O&&O.vertexOffset!==fe.vertexOffset&&(x.segments.push(O),O=void 0),O?(O.vertexLength+=fe.vertexLength,O.primitiveLength+=fe.primitiveLength):O={vertexOffset:fe.vertexOffset,primitiveLength:fe.primitiveLength,vertexLength:fe.vertexLength,primitiveOffset:fe.primitiveOffset,sortKey:void 0,vaos:{}}}return O&&x.segments.push(O),x}encodeCentroid(l,u){const p=l.centroid(),x=u.span(),b=Math.min(7,Math.round(x.x*this.tileToMeter/10)),T=Math.min(6,Math.round(x.y*this.tileToMeter/10));return new Ft(pe(p.x,1,8191)<<3|b,pe(p.y,1,8191)<<3|T)}encodeBorderCentroid(l){if(!l.borders)return new Ft(0,0);const u=l.borders,p=Number.MAX_VALUE;if(u[0][0]!==p||u[1][0]!==p){const x=u[0][0]!==p?0:1;return new Ft(6|(u[0][0]!==p?0:65528),(u[x][0]+u[x][1])/2<<3|6)}{const x=u[2][0]!==p?2:3;return new Ft((u[x][0]+u[x][1])/2<<3|6,6|(u[2][0]!==p?0:65528))}}showCentroid(l){const u=this.centroidData[l.centroidDataIndex];if(u.flags&=Vp,u.groupCentroidPos.x!==0||u.groupCentroidPos.y!==0){const p=u.span(),x=Math.min(7,Math.round(p.x*this.tileToMeter/10)),b=Math.min(6,Math.round(p.y*this.tileToMeter/10));u.centroidXY=new Ft(pe(u.groupCentroidPos.x,1,8191)<<3|x,pe(u.groupCentroidPos.y,1,8191)<<3|b)}else u.centroidXY=new Ft(0,0);this.writeCentroidToBuffer(u)}writeCentroidToBuffer(l){this.groundEffect.updateHiddenByLandmark(l);const u=l.vertexArrayOffset,p=l.vertexCount+l.vertexArrayOffset,x=-1073741824&l.flags?ZP:l.centroidXY,b=this.centroidVertexArray.geta_centroid_pos0(u);if(this.centroidVertexArray.geta_centroid_pos1(u)!==x.y||b!==x.x){for(let T=u;TP.max.x||P.min.x>T.max.x||T.min.y>P.max.y||P.min.y>T.max.y||T.footprint.buildingIds.has(P.buildingId)&&(P.flags|=T.clipMask!==YP.None?-1073741824:Vp);else for(const P of this.centroidData)if(!(P.flags&Vp||P.flags&XP||T.min.x>P.max.x||P.min.x>T.max.x||T.min.y>P.max.y||P.min.y>T.max.y))for(let O=0;Ou!=Y>u&&l<(this.footprintVertices.int16[2*($+T.vertexOffset)+0]-V)*(u-G)/(Y-G)+V&&(x=!x)}k=P}}return x}getHeightAtTileCoord(l,u){let p=Number.NEGATIVE_INFINITY,x=!0;const b=4*(l+fr)*fr+(u+fr);if(this.partLookup.hasOwnProperty(b)){const T=this.partLookup[b];return T?{height:T.height,hidden:!!(T.flags&Vp)}:void 0}for(const T of this.centroidData)l>T.max.x||T.min.x>l||u>T.max.y||T.min.y>u||T.height<=p||this.footprintContainsPoint(l,u,T)&&(p=T.height,this.partLookup[b]=T,x=!!(T.flags&Vp));if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:x};this.partLookup[b]=void 0}}function RQ(h,l){const u=h.add(l)._unit();return h.x*u.x+h.y*u.y}function KPe(h,l,u,p){const x=l.sub(h)._perp()._unit(),b=u.sub(l)._perp()._unit();return LQ(h,l,u,RQ(x,b),p)}function LQ(h,l,u,p,x){const b=Math.sqrt(1-p*p);return Math.min(h.dist(l)/3,l.dist(u)/3,x*b/p)}function d$(h,l,u){return h.xu[1].x&&l.x>u[1].x||h.yu[1].y&&l.y>u[1].y}function MQ(h,l){return h.xl[1].x||h.yl[1].y}function YPe(h){return h.every(l=>l.x<=0)||h.every(l=>l.x>=fr)||h.every(l=>l.y<=0)||h.every(l=>l.y>=fr)}function DQ(h,l,u){if(h.x<0||h.x>=fr||l.x<0||l.x>=fr||u.x<0||u.x>=fr)return!1;const p=u.sub(l),x=p.perp(),b=h.sub(l);return(p.x*b.x+p.y*b.y)/Math.sqrt((p.x*p.x+p.y*p.y)*(b.x*b.x+b.y*b.y))>-.866&&x.x*b.x+x.y*b.y<0}function OQ(h,l,u){const p=l?2|h:-3&h;return u?1|p:-2&p}function FQ(){const h=Math.PI/32,l=Math.tan(h),u=Ge;return u*Math.sqrt(1+2*l*l)-u}function BQ(h,l,u){const p=1<{for(const ze of Ie)X.push({polygon:ze,bounds:We})},se=Math.ceil(Math.log2($)),ae=Math.ceil(Math.log2(V)),fe=se-ae,ue=[];for(let Ie=0;Ie0?0:1);for(let Ie=0;IeWe+1?Ae.push({polygons:It,bounds:Pt,depth:We+1}):te(It,Pt)}if(Dt.length){const Pt=[new Ft(ze===0?Et:He.x,ze===1?Et:He.y),Ve];ue.length>We+1?Ae.push({polygons:Dt,bounds:Pt,depth:We+1}):te(Dt,Pt)}}return X}(h,l,Math.ceil((b-x)/11.25),Math.ceil((T-k)/11.25),1,(P,O,$)=>{if(P===0)return .5*(O+$);{const V=_t((u.y+O/fr)/p);return(Ut(.5*(_t((u.y+$/fr)/p)+V))*p-u.y)*fr}})}function ZPe(h,l,u,p,x,b){const T=Math.pow(2,p.z-x.z);for(let k=0;k=P[T]&&(k=l,P=h),k[T]x&&VQ(k,P,T,x),k[T]b&&VQ(P,k,T,b)}}function eR(h,l,u,p,x,b){const T=[];for(let k=0;k=p&&X.x>=p||(Y.x>=p?Y=new Ft(p,Y.y+(p-Y.x)/(X.x-Y.x)*(X.y-Y.y))._round():X.x>=p&&(X=new Ft(p,Y.y+(p-Y.x)/(X.x-Y.x)*(X.y-Y.y))._round()),Y.y>=x&&X.y>=x||(Y.y>=x?Y=new Ft(Y.x+(x-Y.y)/(X.y-Y.y)*(X.x-Y.x),x)._round():X.y>=x&&(X=new Ft(Y.x+(x-Y.y)/(X.y-Y.y)*(X.x-Y.x),x)._round()),O&&Y.equals(O[O.length-1])||(O=[Y],T.push(O),b&&b.push({progress:{min:se+GQ(ae,fe,Y)*te,max:1},parentIndex:k,prevPoint:ae,nextPoint:fe})),O.push(X),b&&(b[b.length-1].progress.max=se+GQ(ae,fe,X)*te,b[b.length-1].nextPoint=fe)))))}if(b&&V>0)for(let G=$;GO.t-$.t);let T=0,k=0,P=[];for(p.push(P);T!==h.length;){if(k===b.length){for(;T!==h.length;)P.length!==0&&P[P.length-1].equals(h[T])||P.push(h[T]),T++;break}b[k].t<=T?(P.length!==0&&P[P.length-1].equals(b[k].point)||P.push(b[k].point),Math.trunc(b[k].t),k++):(P.length!==0&&P[P.length-1].equals(h[T])||P.push(h[T]),T++)}}function GQ(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 w2(h,l){return h.x*l.x+h.y*l.y}function HQ(h,l){if(h.length===1){let u=0;const p=l[u++];let x;for(;!x||p.equals(x);)if(x=l[u++],!x)return 1/0;for(;u{Et[0]=It,Et[1]=Dt,Et[2]=Pt,Et[3]=1},bt=FQ();Y>0&&(Y+=bt),X+=bt;for(const Et of G){const It=[],Dt=[];for(const Pt of Et){const Ht=Pt.x+te.x,vt=Pt.y+te.y,Rt=V.projection.projectTilePoint(Ht,vt,Ae),Bt=V.projection.upVector(Ae,Pt.x,Pt.y);let Yt=Y,tr=X;if(ae){const wr=YQ(Ht,vt,Y,X,ae,fe,ue,Te);Yt+=wr.base,tr+=wr.top}Y!==0?qe(He,Rt.x+Bt[0]*ze*Yt,Rt.y+Bt[1]*ze*Yt,Rt.z+Bt[2]*ze*Yt):qe(He,Rt.x,Rt.y,Rt.z),qe(Ve,Rt.x+Bt[0]*ze*tr,Rt.y+Bt[1]*ze*tr,Rt.z+Bt[2]*ze*tr),or(He,He,se),or(Ve,Ve,se),It.push(new Iv(He[0],He[1],He[2])),Dt.push(new Iv(Ve[0],Ve[1],Ve[2]))}Ie.push(It),We.push(Dt)}return[Ie,We]}(h,l,u,p,x,b,T,k,P,O,$):T?function(V,G,Y,X,te,se,ae,fe,ue){const Te=[],Ae=[],Ie=[0,0,0,1];for(const We of V){const ze=[],He=[];for(const Ve of We){const qe=Ve.x+X.x,bt=Ve.y+X.y,Et=YQ(qe,bt,G,Y,se,ae,fe,ue);Ie[0]=qe,Ie[1]=bt,Ie[2]=Et.base,Ie[3]=1,Kt(Ie,Ie,te),Ie[3]=Math.max(Ie[3],1e-5);const It=new Iv(Ie[0]/Ie[3],Ie[1]/Ie[3],Ie[2]/Ie[3]);Ie[0]=qe,Ie[1]=bt,Ie[2]=Et.top,Ie[3]=1,Kt(Ie,Ie,te),Ie[3]=Math.max(Ie[3],1e-5);const Dt=new Iv(Ie[0]/Ie[3],Ie[1]/Ie[3],Ie[2]/Ie[3]);ze.push(It),He.push(Dt)}Te.push(ze),Ae.push(He)}return[Te,Ae]}(l,u,p,x,b,T,k,P,O):function(V,G,Y,X,te){const se=[],ae=[],fe=te[8]*G,ue=te[9]*G,Te=te[10]*G,Ae=te[11]*G,Ie=te[8]*Y,We=te[9]*Y,ze=te[10]*Y,He=te[11]*Y;for(const Ve of V){const qe=[],bt=[];for(const Et of Ve){const It=Et.x+X.x,Dt=Et.y+X.y,Pt=te[0]*It+te[4]*Dt+te[12],Ht=te[1]*It+te[5]*Dt+te[13],vt=te[2]*It+te[6]*Dt+te[14],Rt=te[3]*It+te[7]*Dt+te[15],Bt=Pt+fe,Yt=Ht+ue,tr=vt+Te,wr=Math.max(Rt+Ae,1e-5),ur=Pt+Ie,cr=Ht+We,rr=vt+ze,_r=Math.max(Rt+He,1e-5);qe.push(new Iv(Bt/wr,Yt/wr,tr/wr)),bt.push(new Iv(ur/_r,cr/_r,rr/_r))}se.push(qe),ae.push(bt)}return[se,ae]}(l,u,p,x,b)}function YQ(h,l,u,p,x,b,T,k){const P=T*x.getElevationAt(h,l,!0,!0),O=b[0]!==0,$=O?b[1]===0?T*(b[0]/7-450):T*function(V,G,Y){const X=Math.floor(G[0]/8),te=Math.floor(G[1]/8),se=10*(G[0]-8*X),ae=10*(G[1]-8*te),fe=V.getElevationAt(X,te,!0,!0),ue=V.getMeterToDEM(Y),Te=Math.floor(.5*(se*ue-1)),Ae=Math.floor(.5*(ae*ue-1)),Ie=V.tileCoordToPixel(X,te),We=2*Te+1,ze=2*Ae+1,He=function(Dt,Pt,Ht,vt,Rt){return[Dt.getElevationAtPixel(Pt,Ht,!0),Dt.getElevationAtPixel(Pt+Rt,Ht,!0),Dt.getElevationAtPixel(Pt,Ht+Rt,!0),Dt.getElevationAtPixel(Pt+vt,Ht+Rt,!0)]}(V,Ie.x-Te,Ie.y-Ae,We,ze),Ve=Math.abs(He[0]-He[1]),qe=Math.abs(He[2]-He[3]),bt=Math.abs(He[0]-He[2])+Math.abs(He[1]-He[3]),Et=Math.min(.25,.5*ue*(Ve+qe)/We),It=Math.min(.25,.5*ue*bt/ze);return fe+Math.max(Et*se,It*ae)}(x,b,k):P;return{base:P+(u===0?-1:u),top:O?Math.max($+p,P+u+2):P+p}}const h$=4096;class QPe{constructor(l){this.module=l,this.memoryStack=this.module.malloc(h$),this.memoryStackNextFree=this.memoryStack}createIntArray(l){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>h$?-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>h$?-1:(new Float32Array(this.module.heapF32.buffer,u,l.length).set(l),u)}readStringBuffer(l){let u="";for(;this.module.heapU8[l]!==0;)u+=String.fromCharCode(this.module.heapU8[l]),++l;return u}setStyle(l){const u=l.normalScale;this.module.setStyle(u[0],u[1],u[2],l.tileToMeters)}setAOOptions(l,u){this.module.setAOOptions(l?1:0,u)}setMetricOptions(l,u){this.module.setMetricOptions(l?1:0,u)}setStructuralOptions(l){this.module.setStructuralOptions(l?1:0)}setFacadeOptions(l,u){this.module.setFacadeOptions(l,u?1:0)}setFauxFacadeOptions(l,u,p){this.module.setFauxFacadeOptions(l?1:0,u?1:0,p)}setFacadeClassifierOptions(l){this.module.setFacadeClassifierOptions(l)}generateMesh(l,u){this.memoryStackNextFree=this.memoryStack;for(const k of l){const P=this.createIntArray(k.ringIndices),O=this.createFloatArray(k.coordinates);if(P===-1||O===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(k.id,k.sourceId,k.minHeight,k.height,k.roofType,O,P,k.ringIndices.length-1)}for(const k of u){let P;P=k.entrances?JSON.parse(k.entrances):[];const O=this.createFloatArray(P),$=this.createFloatArray(k.coordinates);if(O===-1||$===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(k.sourceId,k.crossPerc,k.distanceToRoad,O,P.length,$,k.coordinates.length)}if(!this.module.generateMesh()){const k=this.module.getLastError();return this.readStringBuffer(k)}const p=this.module.getMeshCount(),x=new Array(p);for(let k=0;k>2)-3,se=Y[X++]>>2;if(X++,x.json=JSON.parse(iJ.decode(Y.subarray(X,X+se))),X+=se,X>>0,Math.ceil(1.2*Te)),Ie=Math.ceil((Ae-Te)/65536);try{return te.grow(Ie),se(),!0}catch{return!1}},b:ae}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Y,fe):Y.then(ue=>ue.arrayBuffer()).then(ue=>WebAssembly.instantiate(ue,fe))).then(ue=>{const{Rb:Te,Qb:Ae,P:Ie,T:We,X:ze,Ja:He,La:Ve,Qa:qe,Va:bt,Wa:Et,eb:It,jb:Dt,f:Pt,e:Ht,yb:vt,zb:Rt,Ab:Bt,Bb:Yt,Db:tr,Gb:wr}=ue.instance.exports;te=Ht;const ur=(()=>{let cr=0,rr=0,_r=0,Rr=0;return Wr=>{_r&&(Te(Rr),Te(cr),rr+=_r,_r=cr=0),cr||(rr+=128,cr=Ae(rr));const Dr=Wr.length+7&-8;let fn=cr;Dr>=rr&&(_r=Dr,fn=Rr=Ae(Dr));for(let Wn=0;Wn{Xh=Y,S2=void 0}))}()),G&&$.push(function(){if(f$)return;const Y=function(X){let te;const se=WebAssembly.instantiateStreaming(X,{}).then(ue=>{te=ue.instance,te.exports.__wasm_call_ctors()}),ae={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},fe={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:se,supported:!0,decodeGltfBuffer(ue,Te,Ae,Ie,We,ze){(function(He,Ve,qe,bt,Et,It,Dt){const Pt=He.exports.sbrk,Ht=bt+3&-4,vt=Pt(Ht*Et),Rt=Pt(It.length),Bt=new Uint8Array(He.exports.memory.buffer);Bt.set(It,Rt);const Yt=Ve(vt,bt,Et,Rt,It.length);if(Yt===0&&Dt&&Dt(vt,Ht,Et),qe.set(Bt.subarray(vt,vt+bt*Et)),Pt(vt-Pt(0)),Yt!==0)throw new Error(`Malformed buffer data: ${Yt}`)})(te,te.exports[fe[We]],ue,Te,Ae,Ie,te.exports[ae[ze]])}}}(fetch(Lo()));return Y.ready.then(()=>{f$=Y})}()),T)for(let Y=0;Y{const k=Jg(p,(P,O)=>{P?T(P):b(O)});x&&x.addEventListener("abort",()=>{k.cancel(),T(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:h,type:"arrayBuffer"},l);return lJ(u,0,h,l)}function p$(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 g$(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 dm{constructor(l,u,p,x){this.context=l,this.format=p,this.useMipmap=x&&x.useMipmap,this.texture=l.gl.createTexture(),this.update(u,{premultiply:x&&x.premultiply})}update(l,u){const p=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:T}=b,{x:k,y:P}=u&&u.position?u.position:{x:0,y:0},O=k+p,$=P+x;this.size&&(this.size[0]!==O||this.size[1]!==$)&&(!u||u.recreateWhenResize===void 0||u.recreateWhenResize)&&(T.bindTexture(T.TEXTURE_2D,null),T.deleteTexture(this.texture),this.texture=T.createTexture(),this.size=null),T.bindTexture(T.TEXTURE_2D,this.texture),b.pixelStoreUnpackFlipY.set(!1),b.pixelStoreUnpack.set(1),b.pixelStoreUnpackPremultiplyAlpha.set(this.format===T.RGBA8&&(!u||u.premultiply!==!1));const V=l instanceof HTMLImageElement||l instanceof HTMLCanvasElement||l instanceof HTMLVideoElement||l instanceof ImageData||ImageBitmap&&l instanceof ImageBitmap;if(!this.size&&O>0&&$>0){const G=this.useMipmap?Math.floor(Math.log2(Math.max(O,$)))+1:1;T.texStorage2D(T.TEXTURE_2D,G,this.format,O,$),this.size=[O,$]}this.size&&(V?T.texSubImage2D(T.TEXTURE_2D,0,k,P,p$(this.format),g$(this.format),l):"data"in l&&l.data&&T.texSubImage2D(T.TEXTURE_2D,0,k,P,p,x,p$(this.format),g$(this.format),l.data)),this.useMipmap&&T.generateMipmap(T.TEXTURE_2D)}bind(l,u,p=!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&&!p?l===b.NEAREST?b.NEAREST_MIPMAP_NEAREST:b.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),u!==this.wrapS&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,u),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,u),this.wrapS=u)}bindExtraParam(l,u,p,x,b){const{context:T}=this,{gl:k}=T;k.bindTexture(k.TEXTURE_2D,this.texture),u!==this.magFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MAG_FILTER,u),this.magFilter=u),l!==this.minFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MIN_FILTER,this.useMipmap?l===k.NEAREST?k.NEAREST_MIPMAP_NEAREST:k.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),p!==this.wrapS&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_S,p),this.wrapS=p),x!==this.wrapT&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_T,x),this.wrapT=x),b!==this.compareMode&&(b?(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.COMPARE_REF_TO_TEXTURE),k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_FUNC,b)):k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.NONE),this.compareMode=b)}destroy(){const{gl:l}=this.context;l.deleteTexture(this.texture),this.texture=null}}class j2{constructor(l,u){this.context=l,this.texture=u}bind(l,u){const{context:p}=this,{gl:x}=p;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 iRe=On([{name:"a_pos_3f",components:3,type:"Float32"}]),aRe=On([{name:"a_color_3f",components:3,type:"Float32"}]),oRe=On([{name:"a_color_4f",components:4,type:"Float32"}]),lRe=On([{name:"a_uv_2f",components:2,type:"Float32"}]),cRe=On([{name:"a_normal_3f",components:3,type:"Float32"}]),uRe=On([{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"}]),dRe=On([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function uJ(h,l){const u=sR(h.projection,h.zoom,h.width,h.height),p=function(b,T,k,P,O){const $=new Je(k.lng-180*Cy,k.lat),V=new Je(k.lng+180*Cy,k.lat),G=b.project($.lng,$.lat),Y=b.project(V.lng,V.lat),X=-Math.atan2(Y.y-G.y,Y.x-G.x),te=Pr.fromLngLat(k);te.y=pe(te.y,-1+Cy,1-Cy);const se=te.toLngLat(),ae=b.project(se.lng,se.lat),fe=Pr.fromLngLat(se);fe.x+=Cy;const ue=fe.toLngLat(),Te=b.project(ue.lng,ue.lat),Ae=hJ(Te.x-ae.x,Te.y-ae.y,X),Ie=Pr.fromLngLat(se);Ie.y+=Cy;const We=Ie.toLngLat(),ze=b.project(We.lng,We.lat),He=hJ(ze.x-ae.x,ze.y-ae.y,X),Ve=Math.abs(Ae.x)/Math.abs(He.y),qe=I([]);K(qe,qe,-X*(1-(O?0:P)));const bt=I([]);return z(bt,bt,[1,1-(1-Ve)*P,1]),bt[4]=-He.x/He.y*P,K(bt,bt,X),D(bt,qe,bt),bt}(h.projection,0,h.center,u,l),x=dJ(h);return z(p,p,[x,x,1]),p}function dJ(h){const l=h.projection,u=sR(h.projection,h.zoom,h.width,h.height),p=y$(l,h.center),x=y$(l,Je.convert(l.center));return Math.pow(2,p*u+(1-u)*x)}function sR(h,l,u,p,x=1/0){const b=h.range;if(!b)return 0;const T=Math.min(x,Math.max(u,p)),k=Math.log2(T/1024);return Fe(b[0]+k,b[1]+k,l)}const Cy=1/4e4;function y$(h,l){const u=pe(l.lat,-85.051129,Nt),p=new Je(l.lng-180*Cy,u),x=new Je(l.lng+180*Cy,u),b=h.project(p.lng,u),T=h.project(x.lng,u),k=Pr.fromLngLat(p),P=Pr.fromLngLat(x),O=T.x-b.x,$=T.y-b.y,V=P.x-k.x,G=P.y-k.y,Y=Math.sqrt((V*V+G*G)/(O*O+$*$));return Math.log2(Y)}function hJ(h,l,u){const p=Math.cos(u),x=Math.sin(u);return{x:h*p-l*x,y:h*x+l*p}}function fJ(h,l,u){I(h),K(h,h,Xn(l[2])),q(h,h,Xn(l[0])),H(h,h,Xn(l[1])),z(h,h,u),D(h,h,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function iR(h,l,u,p,x,b,T,k){const P=[u[0]-l[0],u[1]-l[1],0],O=[p[0]-l[0],p[1]-l[1],0];if(Le(P)<1e-12||Le(O)<1e-12)return pr(h);const $=Vt([],P,O);ft($,$),ke(O,p,l),P[2]=(b-x)*k,O[2]=(T-x)*k;const V=P;return Vt(V,P,O),ft(V,V),zi(h,$,V)}function aR(h,l,u=!1){const p=zp(l.zoom),x=function(b,T,k){const P=T.worldSize,O=[b[12],b[13],b[14]],$=_t(O[1]/P),V=st(O[0]/P),G=I([]),Y=ut(1,$)*P,X=ut(1,0)*P*Jt($,T.zoom),te=1/UB(P);let se=X*te;if(k){const Te=sR(T.projection,T.zoom,T.width,T.height,1024);se=te*T.projection.pixelSpaceConversion(T.center.lat,P,Te)}const ae=Be($,V);me(ae,ae,Ue([],ft([],ae),Y*se*O[2]));const fe=function(Te){const Ae=[Te[0],Te[1],Te[2]];let Ie=[0,1,0];const We=Vt([],Ie,Ae);return Vt(Ie,Ae,We),yt(Ie)===0&&(Ie=[0,1,0],Vt(We,Ae,Ie)),ft(We,We),ft(Ie,Ie),ft(Ae,Ae),[We[0],We[1],We[2],0,Ie[0],Ie[1],Ie[2],0,Ae[0],Ae[1],Ae[2],0,Te[0],Te[1],Te[2],1]}(ae);z(G,G,[se,se,se*Y]),F(G,G,[-O[0],-O[1],-O[2]]);const ue=D([],T.globeMatrix,fe);return D(ue,ue,G),D(ue,ue,b),ue}(h,l,u);if(p>0){const b=function(T,k){const P=k.worldSize,O=ut(1,0)*P*Jt(k.center.lat,k.zoom)/UB(P),$=ut(1,k.center.lat)*P,V=I([]);H(V,V,Xn(k.center.lng)),q(V,V,Xn(k.center.lat)),F(V,V,[0,0,Me]),z(V,V,[O,O,O*$]);const G=k.point;return F(V,V,[-G.x,-G.y,0]),D(V,V,T),D(V,k.globeMatrix,V)}(h,l);return function(T,k,P){const O=(X,te,se)=>{const ae=Le(X),fe=Le(te),ue=$p(X,te,se);return Ue(ue,ue,1/Le(ue)*sn(ae,fe,se))},$=O([T[0],T[1],T[2]],[k[0],k[1],k[2]],P),V=O([T[4],T[5],T[6]],[k[4],k[5],k[6]],P),G=O([T[8],T[9],T[10]],[k[8],k[9],k[10]],P),Y=$p([T[12],T[13],T[14]],[k[12],k[13],k[14]],P);return[$[0],$[1],$[2],0,V[0],V[1],V[2],0,G[0],G[1],G[2],0,Y[0],Y[1],Y[2],1]}(x,b,p)}return x}function x$(h,l,u,p){const x=ys.projectAabbCorners(p,u);let b=Number.MAX_VALUE;for(let k=0;k0||se===0&&X[0]*te[0]+X[1]*te[1]>=0&&X[0]*X[0]+X[1]*X[1]>te[0]*te[0]+te[1]*te[1])&&($=Y)}V=$}while(V!==O);return P.length>0&&P.push(P[0]),P}(x);if(qi(h,T))return b}const Pv=64,Dw={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function oR(h,l,u,p,x,b,T,k,P,O=!1){const $=u.zoom,V=u.project(p),G=Jt(p.lat,$),Y=1/G;I(h),F(h,h,[V.x+T[0]*Y,V.y+T[1]*Y,T[2]]);let X=1,te=1;const se=u.worldSize;if(O){if(u.projection.name==="mercator"){let Te=0;u.elevation&&(Te=u.elevation.getAtPointOrZero(new Pr(V.x/se,V.y/se),0));const Ae=Kt([],[V.x,V.y,Te,1],u.projMatrix)[3]/u.cameraToCenterDistance;X=Ae,te=Ae*Jt(u.center.lat,$)}else if(u.projection.name==="globe"){const Te=aR(h,u),Ae=[0,0,0,1];Kt(Ae,Ae,D([],u.projMatrix,Te));const Ie=Ae[3]/u.cameraToCenterDistance,We=zp($),ze=u.projection.pixelsPerMeter(p.lat,se)*Jt(p.lat,$),He=u.projection.pixelsPerMeter(u.center.lat,se)*Jt(u.center.lat,$);X=Ie/sn(ze,lr(u.center.lat),We),te=Ie*G/ze,X*=He,te*=He}}else X=Y;z(h,h,[X,X,te]);const ae=[...h],fe=l.orientation,ue=[];if(fJ(ue,[fe[0]+(x?x[0]:0),fe[1]+(x?x[1]:0),fe[2]+(x?x[2]:0)],b),D(h,ae,ue),k&&u.elevation){let Te=0;const Ae=[];if(P&&u.elevation){Te=function(We,ze,He,Ve,qe){const bt=ze.elevation;if(!bt)return 0;const Et=ys.projectAabbCorners(He,Ve),It=ut(1,qe.lat)*ze.worldSize,Dt=function(rr,_r){const Rr=[0,0,1],Wr=[{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 Dr of Wr){const fn=rr[Dr.corners[0]],Wn=rr[Dr.corners[1]],mn=rr[Dr.corners[2]],es=[Wn[0]-fn[0],Wn[1]-fn[1],_r*(Wn[2]-fn[2])],En=Vt(es,es,[mn[0]-fn[0],mn[1]-fn[1],_r*(mn[2]-fn[2])]);ft(En,En),Dr.dotProductWithUp=kt(En,Rr)}return Wr.sort((Dr,fn)=>Dr.dotProductWithUp-fn.dotProductWithUp),Wr[0].corners}(Et,It),Pt=Et[Dt[0]],Ht=Et[Dt[1]],vt=Et[Dt[2]],Rt=Et[Dt[3]],Bt=bt.getAtPointOrZero(new Pr(Pt[0]/ze.worldSize,Pt[1]/ze.worldSize),0),Yt=bt.getAtPointOrZero(new Pr(Ht[0]/ze.worldSize,Ht[1]/ze.worldSize),0),tr=bt.getAtPointOrZero(new Pr(vt[0]/ze.worldSize,vt[1]/ze.worldSize),0),wr=bt.getAtPointOrZero(new Pr(Rt[0]/ze.worldSize,Rt[1]/ze.worldSize),0),ur=(Bt+wr)/2,cr=(Yt+tr)/2;return ur>cr?Yt=l.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function hRe(h,l,u){h.indexBuffer=l.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=l.createVertexBuffer(h.vertexArray,iRe.members,!1,!0),h.normalArray&&(h.normalBuffer=l.createVertexBuffer(h.normalArray,cRe.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=l.createVertexBuffer(h.texcoordArray,lRe.members,!1,!0)),h.colorArray&&(h.colorBuffer=l.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?aRe:oRe).members,!1,!0)),h.featureArray&&(h.pbrBuffer=l.createVertexBuffer(h.featureArray,dRe.members,!0)),h.segments=Os.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const p=h.material;p.pbrMetallicRoughness.baseColorTexture&&E2(p.pbrMetallicRoughness.baseColorTexture,l),p.pbrMetallicRoughness.metallicRoughnessTexture&&E2(p.pbrMetallicRoughness.metallicRoughnessTexture,l),p.normalTexture&&E2(p.normalTexture,l),p.occlusionTexture&&E2(p.occlusionTexture,l,u),p.emissionTexture&&E2(p.emissionTexture,l)}function v$(h,l,u){if(h.meshes)for(const p of h.meshes)hRe(p,l,u);if(h.children)for(const p of h.children)v$(p,l,u)}function lR(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)lR(l)}function fRe(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 _$(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&&fRe(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)_$(l)}function Rv(h,l){const u=h.json.bufferViews[l.bufferView],p=rR[l.componentType];return new p(h.buffers[u.buffer],(l.byteOffset||0)+(u.byteOffset||0),l.count*(u.byteStride&&u.byteStride!==T2[l.type]*p.BYTES_PER_ELEMENT?u.byteStride/p.BYTES_PER_ELEMENT:T2[l.type]))}function b$(h,l,u,p){const x=rR[l.componentType],b=function($){switch($){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(x),T=h.json.bufferViews[l.bufferView],k=T.byteStride?T.byteStride/x.BYTES_PER_ELEMENT:T2[l.type],P=u.float32,O=P.length/u.capacity;for(let $=0,V=0;$0){for(let se=0;se0){b.texcoordArray=new Dp;const G=l.json.accessors[x.TEXCOORD_0];b.texcoordArray.resize(G.count);const Y=Rv(l,G);b$(l,G,b.texcoordArray,Y)}if(x._FEATURE_ID_RGBA4444!==void 0){const G=l.json.accessors[x._FEATURE_ID_RGBA4444];l.json.extensionsUsed&&l.json.extensionsUsed.includes("EXT_meshopt_compression")&&(b.featureData=Rv(l,G))}x._FEATURE_RGBA4444!==void 0&&(b.featureData=new Uint32Array(Rv(l,l.json.accessors[x._FEATURE_RGBA4444]).buffer));const V=h.material;return b.material=function(G,Y){const{emissiveFactor:X=[0,0,0],alphaMode:te="OPAQUE",alphaCutoff:se=.5,normalTexture:ae,occlusionTexture:fe,emissiveTexture:ue,doubleSided:Te,name:Ae}=G,{baseColorFactor:Ie=[1,1,1,1],metallicFactor:We=1,roughnessFactor:ze=1,baseColorTexture:He,metallicRoughnessTexture:Ve}=G.pbrMetallicRoughness||{},qe=fe?Y[fe.index]:void 0;if(fe&&fe.extensions&&fe.extensions.KHR_texture_transform&&qe){const bt=fe.extensions.KHR_texture_transform;qe.offsetScale=[bt.offset[0],bt.offset[1],bt.scale[0],bt.scale[1]]}return{name:Ae,pbrMetallicRoughness:{baseColorFactor:new as(...Ie),metallicFactor:We,roughnessFactor:ze,baseColorTexture:He?Y[He.index]:void 0,metallicRoughnessTexture:Ve?Y[Ve.index]:void 0},doubleSided:Te,emissiveFactor:new as(...X),alphaMode:te,alphaCutoff:se,normalTexture:ae?Y[ae.index]:void 0,occlusionTexture:qe,emissionTexture:ue?Y[ue.index]:void 0,defined:G.defined===void 0}}(V!==void 0?l.json.materials[V]:{defined:!1},u),b}function pJ(h,l,u){const{matrix:p,rotation:x,translation:b,scale:T,mesh:k,extras:P,children:O,name:$}=h,V={};if(V.name=$,V.localMatrix=p||function(G,Y,X,te){var se=Y[0],ae=Y[1],fe=Y[2],ue=Y[3],Te=se+se,Ae=ae+ae,Ie=fe+fe,We=se*Te,ze=se*Ae,He=se*Ie,Ve=ae*Ae,qe=ae*Ie,bt=fe*Ie,Et=ue*Te,It=ue*Ae,Dt=ue*Ie,Pt=te[0],Ht=te[1],vt=te[2];return G[0]=(1-(Ve+bt))*Pt,G[1]=(ze+Dt)*Pt,G[2]=(He-It)*Pt,G[3]=0,G[4]=(ze-Dt)*Ht,G[5]=(1-(We+bt))*Ht,G[6]=(qe+Et)*Ht,G[7]=0,G[8]=(He+It)*vt,G[9]=(qe-Et)*vt,G[10]=(1-(We+Ve))*vt,G[11]=0,G[12]=X[0],G[13]=X[1],G[14]=X[2],G[15]=1,G}([],x||[0,0,0,1],b||[0,0,0],T||[1,1,1]),V.globalMatrix=C(V.localMatrix),k!==void 0){V.meshes=u[k];const G=V.anchor=[0,0];for(const Y of V.meshes){const{min:X,max:te}=Y.aabb;G[0]+=X[0]+te[0],G[1]+=X[1]+te[1]}G[0]=Math.floor(G[0]/V.meshes.length/2),G[1]=Math.floor(G[1]/V.meshes.length/2)}if(P&&(P.id&&(V.id=P.id),P.lights&&(V.lights=function(G){if(!G.length)return[];const Y=function(fe){const ue=atob(fe),Te=new Uint8Array(ue.length);for(let Ae=0;Ae1&&p[p.length-1].equals(p[0])&&p.pop();let x=0;for(let T=0;T0&&p.reverse();const b=Iw(p.flatMap(T=>[T.x,T.y]),[]);return b.length===0?null:{vertices:p,indices:b}}function yRe(h,l){const u=[],p=[];let x=0;const b=[];for(const T of h){x=u.length;const k=T.vertexArray.float32,P=T.indexArray.uint16;for(let O=0;O0&&([p[T+1],p[T+2]]=[p[T+2],p[T+1]])}return{vertices:u,indices:p}}function w$(h){const l=function(P,O){const $=[],V=WebGL2RenderingContext;if(P.json.textures)for(const G of P.json.textures){const Y={magFilter:V.LINEAR,minFilter:V.NEAREST,wrapS:V.REPEAT,wrapT:V.REPEAT};G.sampler!==void 0&&Object.assign(Y,P.json.samplers[G.sampler]),$.push({image:O[G.source],sampler:Y,uploaded:!1})}return $}(h,h.images),u=function(P,O){const $=[];for(const V of P.json.meshes){const G=[];for(const Y of V.primitives)G.push(mRe(Y,P,O));$.push(G)}return $}(h,l),{scenes:p,scene:x,nodes:b}=h.json,T=p?p[x||0].nodes:[...b.keys()],k=[];for(const P of T)k.push(pJ(b[P],h,u));return function(P,O,$){const V={},G=new Set;for(let Y=0;Y0){const Y=Array.from(G.values()).sort((X,te)=>X-te);for(let X=Y.length-1;X>=0;X--)P.splice(Y[X],1)}}(k,T,h.json.nodes),k}function xRe(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const l=h.vertexArray.float32,u=h.aabb.min[0]-1,p=h.aabb.min[1]-1,x=Pv/(h.aabb.max[0]-u+2),b=Pv/(h.aabb.max[1]-p+2);for(let T=0;Th.heightmap[O*Pv+P]&&(h.heightmap[O*Pv+P]=k)}}function gJ(h,l,u,p,x){u.reserve(u.length+4*h.length),p.reserve(p.length+10*h.length),x.reserve(x.length+10*h.length);let b=p.length;for(const T of h){const k=Math.min(10,Math.max(4,1.3*T.height))*l,P=[-T.normal[1],T.normal[0],0],O=Math.min(.29,.1*T.width/T.depth),$=T.width-2*T.depth*l*(O+.01),V=Ze([],T.pos,P,$/2),G=Ze([],T.pos,P,-$/2),Y=[V[0],V[1],V[2]+T.height],X=[G[0],G[1],G[2]+T.height],te=Ze([],T.normal,P,O);Ue(te,te,k);const se=Ze([],T.normal,P,-O);Ue(se,se,k),me(te,V,te),me(se,G,se),V[2]+=.1,G[2]+=.1,p.emplaceBack(te[0],te[1],te[2]),p.emplaceBack(se[0],se[1],se[2]),p.emplaceBack(V[0],V[1],V[2]),p.emplaceBack(G[0],G[1],G[2]),p.emplaceBack(Y[0],Y[1],Y[2]),p.emplaceBack(X[0],X[1],X[2]),p.emplaceBack(V[0],V[1],V[2]),p.emplaceBack(G[0],G[1],G[2]),p.emplaceBack(te[0],te[1],te[2]),p.emplaceBack(se[0],se[1],se[2]);const ae=$/k/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 vRe(h,l){const u={};u.indexArray=new Pi,u.vertexArray=new Ou,u.colorArray=new Yh,gJ(h,l,u.indexArray,u.vertexArray,u.colorArray);const p={defined:!0};p.emissiveFactor=as.black;const x={};return x.baseColorFactor=as.white,p.pbrMetallicRoughness=x,u.material=p,u.aabb=new ys([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),u}const yJ=On([{name:"a_pos_3f",components:3,type:"Float32"}]),_Re=On([{name:"a_normal_3",components:3,type:"Int16"}]),bRe=On([{name:"a_centroid_3",components:3,type:"Int16"}]),xJ=On([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),wRe=On([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),SRe=On([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),TRe=On([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),jRe=On([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),ERe=On([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),vJ=ln.types,cR=32767;function kRe(h,l){const u=fr+l;for(const p of h)for(const x of p)if(x.x<-l||x.x>u||x.y<-l||x.y>u)return!1;return!0}function ARe(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 S${constructor(){this.layoutVertexArray=new Ou,this.layoutAttenuationArray=new Yh,this.layoutColorArray=new Fu,this.indexArray=new Pi,this.indexArrayForConflation=new Pi,this.segmentsBucket=new Os}}class T${constructor(l){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Os,this.entranceBloom=new S$;const u=66560;this.layoutVertexArray=new Ou,this.layoutVertexArray.reserve(u),this.layoutNormalArray=new rh,this.layoutNormalArray.reserve(u),this.layoutCentroidArray=new rh,this.layoutCentroidArray.reserve(u),this.layoutColorArray=new Fu,this.layoutColorArray.reserve(u),this.layoutFloodLightDataArray=new jw,this.layoutFloodLightDataArray.reserve(u),this.layoutAOArray=new Ew,this.layoutAOArray.reserve(u),this.indexArray=new Pi,this.indexArray.reserve(66560),this.indexArrayForConflation=new Pi,this.segmentsBucket=new Os,this.entranceBloom=new S$,l&&(this.layoutFacadePaintArray=new Fu,this.layoutFacadeDataArray=new Sy,this.layoutFacadeVerticalRangeArray=new Fu)}reserve(l,u,p){this.layoutVertexArray.reserveForAdditional(l),this.layoutCentroidArray.reserveForAdditional(l),this.layoutFloodLightDataArray.reserveForAdditional(l),this.layoutNormalArray.reserveForAdditional(l),this.layoutAOArray.reserveForAdditional(l),this.layoutColorArray.reserveForAdditional(l),this.indexArray.reserveForAdditional(u),p&&(this.layoutFacadePaintArray.reserveForAdditional(l),this.layoutFacadeDataArray.reserveForAdditional(l),this.layoutFacadeVerticalRangeArray.reserveForAdditional(l))}}class _J{constructor(l){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Dp,this.footprintsIndices=new Op,this.footprintsMin=new Ft(1/0,1/0),this.footprintsMax=new Ft(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new T$(!1),this.buildingWithFacade=new T$(!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 u$(l),this.groundEffect.groundRadiusArray=new Zc,this.hasAppearances=null}updateFootprints(l,u){const p=new HP([],[],1),x={vertices:[],indices:new Uint32Array(0),grid:p,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};u.push({footprint:x,id:l})}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(tR!=null||ZQ!=null)return null;if(Mw!=null)return Mw;const l=fetch(Eo());return Mw=function(u){let p,x,b,T,k;function P(){p=new Uint8Array(k.buffer),x=new Int16Array(k.buffer),b=new Int32Array(k.buffer),T=new Float32Array(k.buffer)}function O(){throw new Error("Unexpected BuildingGen error.")}const $=()=>{},V={a:{a:O,f:function(G){const Y=p.length,X=Math.max(G>>>0,Math.ceil(1.2*Y)),te=Math.ceil((X-Y)/65536);try{return k.grow(te),P(),!0}catch{return!1}},g:O,b:$,c:$,d:$,e:$}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(u,V):u.then(G=>G.arrayBuffer()).then(G=>WebAssembly.instantiate(G,V))).then(G=>{const Y=G.instance.exports;return(0,Y.g)(),k=Y.f,P(),new QPe({setStyle:Y.h,setAOOptions:Y.i,setMetricOptions:Y.j,setStructuralOptions:Y.k,setFacadeOptions:Y.l,setFauxFacadeOptions:Y.m,setFacadeClassifierOptions:Y.n,addFeature:Y.o,addFacade:Y.p,generateMesh:Y.q,getLastError:Y.r,getOuterRingLength:Y.s,getMeshCount:Y.t,getPositionsPtr:Y.u,getPositionsLength:Y.v,getNormalsPtr:Y.w,getNormalsLength:Y.x,getAOPtr:Y.y,getAOLength:Y.z,getUVPtr:Y.A,getUVLength:Y.B,getFauxFacadePtr:Y.C,getFauxFacadeLength:Y.D,getIndicesPtr:Y.E,getIndicesLength:Y.F,getBuildingPart:Y.G,getRingCount:Y.H,getRingPtr:Y.I,getRingLength:Y.J,malloc:Y.K,free:Y.L,heapU8:p,heap16:x,heap32:b,heapF32:T})})}(l).then(u=>(Mw=null,tR=u,tR)).catch(u=>{hr("Could not load building-gen"),Mw=null,ZQ=u instanceof Error?u:new Error("Unknown error")}),Mw}()}populate(l,u,p,x){const b=JPe();if(!b)return;const T=zt(p);this.tileToMeter=T,this.brightness=u.brightness,b.setStyle({normalScale:[1,-1,T],tileToMeters:T}),b.setAOOptions(!1,.3),b.setMetricOptions(!1,16),b.setStructuralOptions(!0),b.setFacadeClassifierOptions(3);const k=new Map,P=new Map;let O=0;for(const{feature:ae}of l){if(vJ[ae.type]!=="LineString"){k.set(ae.id,ae.properties.source_id);continue}const fe=this.layers[0]._featureFilter.needGeometry;if(fe&&!this.layers[0]._featureFilter.filter(new fs(this.zoom),ae,p))continue;const ue=jn(ae,fe);if(!fe&&!this.layers[0]._featureFilter.filter(new fs(this.zoom),ue,p))continue;const Te=fe?ue.geometry:Kr(ae,p,x),Ae=[];for(const He of Te)for(const Ve of He)Ae.push(Ve.x),Ae.push(Ve.y);const Ie={coordinates:Ae,crossPerc:ae.properties.cross_perc,distanceToRoad:ae.properties.distance_to_road,entrances:ae.properties.entrances,sourceId:0},We=ae.properties.source_id;let ze=P.get(We);ze||(ze=[],P.set(We,ze)),ze.push(Ie),++O}this.maxHeight=0;const $=new Array,V=new Set,G=ae=>{ae!=null&&V.add(ae)},Y=(ae,fe)=>{ae!=null&&$.push({buildingId:ae,footprintIndex:fe})},X=64*(l.length-O),te=X/2;this.buildingWithFacade.reserve(X,te,!0),this.buildingWithoutFacade.reserve(2*X,2*te,!1),this.footprintsIndices.reserve(16*(l.length-O)),this.footprintsVertices.reserve(8*(l.length-O));for(const{feature:ae,id:fe,index:ue,sourceLayerIndex:Te}of l){if(vJ[ae.type]==="LineString")continue;const Ae=this.layers[0]._featureFilter.needGeometry;if(Ae&&!this.layers[0]._featureFilter.filter(new fs(this.zoom),ae,p))continue;let Ie=null;if(ae.properties&&ae.properties.hasOwnProperty("building_id")&&(Ie=Number(ae.properties.building_id),V.has(Ie)))continue;const We=jn(ae,Ae);if(!Ae&&!this.layers[0]._featureFilter.filter(new fs(this.zoom),We,p))continue;const ze=Ae?We.geometry:Kr(ae,p,x),He=p2(ze,500);let Ve=!1;for(const Rn of He)if(Rn.length!==1){Ve=!0;break}if(Ve){G(Ie);continue}if(!kRe(ze,163)){G(Ie);continue}const qe=this.layers[0],bt=ARe(qe.layout.get("building-roof-shape").evaluate(ae,{},p)),Et=qe.layout.get("building-base").evaluate(ae,{},p),It=qe.layout.get("building-height").evaluate(ae,{},p),Dt=qe.layout.get("building-flood-light-ground-radius").evaluate(ae,{},p),Pt=qe.paint.get("building-ambient-occlusion-intensity"),Ht=Dt/this.tileToMeter;ae.properties["building-part"]="roof";const vt=qe.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),Rt=qe.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="wall";const Bt=qe.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),Yt=qe.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="window";const tr=qe.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),wr=qe.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="door";const ur=qe.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),cr=qe.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);let rr=qe.layout.get("building-flood-light-wall-radius").evaluate(ae,{},p);rr=pe(rr,0,2048);const _r=rr/2048*cR,Rr=k.get(fe),Wr=P.get(Rr)||[],Dr=Wr.length!==0&&qe.layout.get("building-facade").evaluate(ae,{},p);b.setFacadeOptions(4,!0),b.setFauxFacadeOptions(Dr,!1,1);let fn=0,Wn=0,mn=0,es=0,En=0,ji=0,ms=0,ns=0,$s=0,vi=0,Xa=0;if(Dr){let Rn=Math.round(qe.layout.get("building-facade-floors").evaluate(ae,{},p));if(Et===0){Rn=Math.max(1,Rn-(Wr.length>0?1:0));let Mi=4;if(It>100){const Ba=[10,13,15];Mi=Ba[ae.id?ae.id%Ba.length:0]}else It<=10&&(Mi=3);b.setFacadeOptions(Mi,!0),En=(It<15?1.3:1.61803)*Mi/T}else En=Et/T;ji=It/T,En=Math.min(En,ji),mn=qe.layout.get("building-facade-unit-width").evaluate(ae,{},p)/T,es=(ji-En)/Rn,b.setFauxFacadeOptions(!0,!0,mn);const co=qe.layout.get("building-facade-window").evaluate(ae,{},p);fn=co[0],Wn=co[1],ms=Math.floor(65535*Math.min(1,En/fr)),ns=Math.floor(65535*Math.min(1,ji/fr)),$s=Math.floor(255*fn)<<8|Math.floor(255*Wn),vi=Math.floor(65535*Math.min(1,mn/fr)),Xa=Math.floor(65535*Math.min(1,es/fr))}const _i=Array(He.length),Ri={x:1/0,y:1/0},aa={x:-1/0,y:-1/0},Li={x:0,y:0};let Oo=0;for(let Rn=0;Rn0){const Mi=[],Ba=Array(co.length+1);Ba[0]=0;for(let vd=0;vdfr||Ri.y<0||aa.y>fr)&&this.featuresOnBorder.push({featureId:ae.id,footprintIndex:this.footprints.length});{const Rn=Iw(Wp,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Rn.length),this.footprintsIndices.uint16.set(Rn,Yw),this.buildingIds.add(Ie??ae.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,yd.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,yd.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,xd.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,xd.y);const co={footprintVertexOffset:Hp,footprintVertexLength:this.footprintsVertices.length-Hp,footprintIndexOffset:Yw,footprintIndexLength:this.footprintsIndices.length-Yw,min:yd,max:xd,hiddenFlags:0,indicesOffset:FR,indicesLength:mz,bloomIndicesOffset:Fo,bloomIndicesLength:Ei,groundEffectVertexOffset:$v,groundEffectVertexLength:Zw,hasFauxFacade:Dr,height:Kw,promoteId:fe,feature:We,parts:oo,buildingBloom:Fl},Mi=this.footprints.length;ae.id!==void 0&&this.featureFootprintLookup.set(ae.id,Mi),Y(Ie,Mi),this.footprints.push(co)}this.programConfigurations.populatePaintArrays(An.layoutVertexArray.length,ae,ue,{},u.availableImages,p,u.brightness),this.groundEffect.addPaintPropertiesData(ae,ue,{},u.availableImages,p,u.brightness),u.featureIndex.insert(ae,ze,ue,Te,this.index,gl)}$.forEach(({buildingId:ae,footprintIndex:fe})=>{V.has(ae)&&(this.footprints[fe].hiddenFlags|=4)});const se=new Set;this.buildingIds.forEach((ae,fe,ue)=>{V.has(ae)||se.add(ae)}),this.buildingIds=se,this.groundEffect.prepareBorderSegments()}update(l,u,p,x,b,T,k){this.programConfigurations.updatePaintArrays(l,u,b,p,x,T,k),this.groundEffect.update(l,u,b,p,x,T,k),this.evaluate(this.layers[0],l),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){const u=p=>{p.layoutVertexBuffer=l.createVertexBuffer(p.layoutVertexArray,yJ.members),p.layoutNormalBuffer=l.createVertexBuffer(p.layoutNormalArray,_Re.members),p.layoutCentroidBuffer=l.createVertexBuffer(p.layoutCentroidArray,bRe.members),p.layoutFloodLightDataBuffer=l.createVertexBuffer(p.layoutFloodLightDataArray,ERe.members),p.layoutFacadeDataArray&&p.layoutFacadeDataArray.length&&(p.layoutFacadeDataBuffer=l.createVertexBuffer(p.layoutFacadeDataArray,SRe.members)),p.layoutFacadeVerticalRangeArray&&p.layoutFacadeVerticalRangeArray.length&&(p.layoutFacadeVerticalRangeBuffer=l.createVertexBuffer(p.layoutFacadeVerticalRangeArray,TRe.members)),p.entranceBloom.layoutVertexArray.length&&(p.entranceBloom.layoutVertexBuffer=l.createVertexBuffer(p.entranceBloom.layoutVertexArray,yJ.members),p.entranceBloom.layoutAttenuationBuffer=l.createVertexBuffer(p.entranceBloom.layoutAttenuationArray,jRe.members)),this.uploadUpdatedColorBuffer(l),this.uploadUpdatedIndexBuffer(l)};this.uploaded||(u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){const l=u=>{u.layoutVertexBuffer&&(u.layoutVertexBuffer.destroy(),u.layoutNormalBuffer.destroy(),u.layoutColorBuffer.destroy(),u.segmentsBucket.destroy(),u.indexBuffer&&u.indexBuffer.destroy(),u.entranceBloom.layoutVertexBuffer&&(u.entranceBloom.layoutVertexBuffer.destroy(),u.entranceBloom.layoutColorBuffer.destroy(),u.entranceBloom.layoutAttenuationBuffer.destroy(),u.entranceBloom.indexBuffer.destroy(),u.entranceBloom.segmentsBucket.destroy()))};l(this.buildingWithoutFacade),l(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(l,u,p=!0){let x=!1;const b=p?u:0,T=0|(p?-1:~u);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const k of l){const P=this.footprints[k],O=P.hiddenFlags&T|b;P.hiddenFlags!==O&&(P.hiddenFlags=O,x=!0,this.groundEffect.updateHiddenByLandmarkRange(P.groundEffectVertexOffset,P.groundEffectVertexLength,P.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,T=x.indicesOffset+x.indicesLength;if(x.hiddenFlags!==0){for(let P=x.indicesOffset;P{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))};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(l){const u=p=>{p.layoutColorBuffer?p.layoutColorBuffer.updateData(p.layoutColorArray):p.layoutColorBuffer=l.createVertexBuffer(p.layoutColorArray,xJ.members,!0),p.layoutFacadePaintArray&&(p.layoutFacadePaintBuffer?p.layoutFacadePaintBuffer.updateData(p.layoutFacadePaintArray):p.layoutFacadePaintBuffer=l.createVertexBuffer(p.layoutFacadePaintArray,wRe.members,!0)),p.entranceBloom.layoutColorBuffer?p.entranceBloom.layoutColorBuffer.updateData(p.entranceBloom.layoutColorArray):p.entranceBloom.layoutColorBuffer=l.createVertexBuffer(p.entranceBloom.layoutColorArray,xJ.members,!0)};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(l,u){const p=l.paint.get("building-ambient-occlusion-intensity");for(const x of this.footprints){if(4&x.hiddenFlags)continue;const b=u[x.promoteId],T=x.feature;T.properties["building-part"]="roof";const k=l.paint.get("building-color").evaluate(T,b,this.canonical).toPremultipliedRenderColor(this.lut),P=l.paint.get("building-emissive-strength").evaluate(T,b,this.canonical);T.properties["building-part"]="wall";const O=l.paint.get("building-color").evaluate(T,b,this.canonical).toPremultipliedRenderColor(this.lut),$=l.paint.get("building-emissive-strength").evaluate(T,b,this.canonical);T.properties["building-part"]="window";const V=l.paint.get("building-color").evaluate(T,b,this.canonical).toPremultipliedRenderColor(this.lut),G=l.paint.get("building-emissive-strength").evaluate(T,b,this.canonical);T.properties["building-part"]="door";const Y=l.paint.get("building-color").evaluate(T,b,this.canonical).toPremultipliedRenderColor(this.lut),X=l.paint.get("building-emissive-strength").evaluate(T,b,this.canonical),te=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const ae of x.parts){let fe,ue=k;ae.part===1?(ue=k,fe=P):ae.part===0?(ue=O,fe=$):ae.part===2?(ue=V,fe=G):ae.part===3&&(ue=Y,fe=X),fe=pe(fe,0,1);for(let Te=0;TeT.max.x||P.max.xT.max.y||P.max.yk.max.x||k.min.x>l||u>k.max.y||k.min.y>u||k.height<=p||NRe(T,this.footprintsVertices.float32.subarray(2*k.footprintVertexOffset,2*(k.footprintVertexOffset+k.footprintVertexLength)),this.footprintsIndices.uint16.subarray(k.footprintIndexOffset,k.footprintIndexOffset+k.footprintIndexLength))&&(p=k.height,this.footprintLookup[b]=k,x=k.hiddenFlags!==0);if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:x};this.footprintLookup[b]=void 0}}function NRe(h,l,u){for(let p=0;p1&&(P=l[++k]);const $=Math.abs(O-P.left),V=Math.abs(O-P.right),G=Math.min($,V);let Y;const X=b/p*(x+1);if(P.isDash){const te=x-Math.abs(X);Y=Math.sqrt(G*G+te*te)}else Y=x-Math.sqrt(G*G+X*X);this.image.data[T+O]=Math.max(0,Math.min(255,Y+128))}}}addRegularDash(l,u){for(let P=l.length-1;P>=0;--P){const O=l[P],$=l[P+1];O.zeroLength?l.splice(P,1):$&&$.isDash===O.isDash&&($.left=O.left,l.splice(P,1))}const p=l[0],x=l[l.length-1];p.isDash===x.isDash&&(p.left=x.left-this.width,x.right=p.right+this.width);const b=this.width*this.nextRow;let T=0,k=l[T];for(let P=0;P1&&(k=l[++T]);const O=Math.abs(P-k.left),$=Math.abs(P-k.right),V=Math.min(O,$);this.image.data[b+P]=Math.max(0,Math.min(255,(k.isDash?V:-V)+u+128))}}addDash(l,u){const p=this.getKey(l,u);if(this.positions[p])return this.positions[p];const x=u==="round",b=x?7:0,T=2*b+1;if(this.nextRow+T>this.height)return hr("LineAtlas out of space"),null;l.length===0&&l.push(1);let k=0;for(let V=0;Vu.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 xv,this.layoutVertexArray2=new Ou,this.patternVertexArray=new Ou,this.indexArray=new Pi,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.segments=new Os,this.maxLineLength=0,this.zOffsetVertexArray=new Ou,this.elevationGroundScaleVertexArray=new Zc,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.tessellationStep=l.tessellationStep?l.tessellationStep:128,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){this.hasPattern=WB("line",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=zt(p);const T=this.layers[0].layout.get("line-elevation-reference");if(T==="hd-road-markup")this.elevationType="road";else{const G=this.layers[0].layout.get("line-z-offset"),Y=G.isConstant()&&!G.constantOr(0);this.elevationType=T!=="sea"&&T!=="ground"&&Y?"none":"offset",this.elevationType==="offset"&&T==="none"&&hr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=T==="sea"}const k=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&k!==void 0;const P=[];for(const{feature:G,id:Y,index:X,sourceLayerIndex:te}of l){const se=this.layers[0]._featureFilter.needGeometry,ae=jn(G,se);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),ae,p))continue;const fe=b?b.evaluate(ae,{},p):void 0,ue={id:Y,properties:G.properties,type:G.type,sourceLayerIndex:te,index:X,geometry:se?ae.geometry:Kr(G,p,x),patterns:{},sortKey:fe};P.push(ue)}b&&P.sort((G,Y)=>G.sortKey-Y.sortKey);const{lineAtlas:O,featureIndex:$}=u,V=this.addConstantDashes(O);for(const G of P){const{geometry:Y,index:X,sourceLayerIndex:te}=G;if(V&&this.addFeatureDashes(G,O),this.hasPattern){const se=KB("line",this.layers,G,this.zoom,this.pixelRatio,u);this.patternFeatures.push(se)}else this.addFeature(G,Y,X,p,O.positions,u.availableImages,u.brightness,u.elevationFeatures);$.insert(l[X].feature,Y,X,te,this.index)}}addConstantDashes(l){let u=!1;for(const p of this.layers){const x=p.paint.get("line-dasharray").value,b=p.layout.get("line-cap").value;if(x.kind!=="constant"||b.kind!=="constant")u=!0;else{const T=b.value,k=x.value;if(!k)continue;l.addDash(k,T)}}return u}addFeatureDashes(l,u){const p=this.zoom;for(const x of this.layers){const b=x.paint.get("line-dasharray").value,T=x.layout.get("line-cap").value;if(b.kind==="constant"&&T.kind==="constant")continue;let k,P;if(b.kind==="constant"){if(k=b.value,!k)continue}else k=b.evaluate({zoom:p},l);P=T.kind==="constant"?T.value:T.evaluate({zoom:p},l),u.addDash(k,P),l.patterns[x.id]=[u.getKey(k,P)]}}update(l,u,p,x,b,T,k,P,O){this.programConfigurations.updatePaintArrays(l,u,b,p,x,T,k,O)}addFeatures(l,u,p,x,b,T){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,u,p,x,T,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,DRe)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=l.createVertexBuffer(this.patternVertexArray,FRe)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,PRe.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=l.createVertexBuffer(this.elevationGroundScaleVertexArray,RRe.members,!0)),this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,LRe),this.indexBuffer=l.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(l,u){let p,x;if(u&&u>0?(p=`mapbox_clip_start_${u}`,x=`mapbox_clip_end_${u}`):(p="mapbox_clip_start",x="mapbox_clip_end"),l.properties&&l.properties.hasOwnProperty(p)&&l.properties.hasOwnProperty(x))return{start:+l.properties[p],end:+l.properties[x]}}addFeature(l,u,p,x,b,T,k,P){const O=this.layers[0].layout,$=O.get("line-join").evaluate(l,{}),V=O.get("line-cap").evaluate(l,{}),G=O.get("line-miter-limit"),Y=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 te=this.layers[0].paint.get("line-width").value;if(te.kind!=="constant"&&te.isLineProgressConstant===!1&&(this.variableWidthValue=te),this.isSeaLevelReference){const se=O.get("line-elevation-ground-scale").value;se.kind==="constant"&&se.value===0||(this.elevationGroundScaleValue=se)}if(this.elevationType==="road"){const se=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(l,u,x,P,$,V,G,Y)){const[ae,fe]=this.clipRuntimeLinesToTile(u,1);for(let ue=0;ue0?Ae.parentIndex:null)}this.fillNonElevatedRoadSegment(se)}}else for(let se=0;se0?se:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,b,T,x,k,void 0,this.worldview)}computeSegNextDir(l,u){return l.nextPoint.sub(u.at(-2)).unit()}computeSegPrevDir(l,u){return u[1].sub(l.prevPoint).unit()}clipLinesToTile(l,u){return eR(l,-u,-u,fr+u,fr+u)}clipRuntimeLinesToTile(l,u){const p=[];return[eR(l,-u,-u,fr+u,fr+u,p),p]}addElevatedRoadFeature(l,u,p,x,b,T,k,P){const O=[],$=Vs.getElevationFeature(l,x);if($){const V=this.clipLinesToTile(u,1),G=this.prepareElevatedLines(V,$,p);for(const Y of G)O.push({geometry:Y,elevation:$,elevationTileID:p,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(O.length===0)return!1;for(const V of O){const G=this.layoutVertexArray.length;this.addLine(V.geometry,l,p,b,T,k,P);const Y=new Ys(p,V.elevationTileID);if(V.elevation)for(let X=G;X>1,this.layoutVertexArray.int16[6*X+1]>>1),se=Y.pointElevation(te,V.elevation,.05);this.updateHeightRange(se),this.zOffsetVertexArray.emplaceBack(se,0,0)}else this.fillNonElevatedRoadSegment(G)}return!0}prepareElevatedLines(l,u,p){if(u.constantHeight!=null)return l;const x=[],b=1/zt(p);for(const T of l)XPe(T,new Qc(u,b),0,x);return x}fillNonElevatedRoadSegment(l){for(let u=l;u0,G=P&&P.progress.max<1;if(this.lineClips){let He={min:this.lineClips.start,max:this.lineClips.end},Ve=1;if(P){const Et=this.lineClips.end-this.lineClips.start;He=function(It,Dt,Pt){return{min:hi(It.min,Dt,Pt),max:hi(It.max,Dt,Pt)}}(P.progress,{min:0,max:1},He),Et>0&&(Ve=(He.max-He.min)/Et)}const qe=+u.properties.mapbox_clip_feature_len,bt=+u.properties.mapbox_clip_seg_len;if(Number.isNaN(qe)||Number.isNaN(bt)){for(let It=0;It=2&&l[X-1].equals(l[X-2]);)X--;let te=0;for(;te0,Rt=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ve&&qe==="round"){if(DtT&&(qe="bevel"),qe==="bevel"&&(Dt>2&&(qe="flipbevel"),Dt2*Rt){const tr=ae.sub(ae.sub(fe)._mult(Rt/Bt)._round());this.updateDistance(fe,tr),this.addCurrentVertex(tr,Te,0,0,se,ze),fe=tr}this.updateDistance(fe,ae),Et._mult(Dt),this.addCurrentVertex(ae,Et,0,0,se,ze);const Yt=ae.dist(ue);if(Yt>2*Rt){const tr=ae.add(ue.sub(ae)._mult(Rt/Yt)._round());this.updateDistance(ae,tr),this.addCurrentVertex(tr,Ae,0,0,se,ze),ae=tr}}else Et._mult(Dt),this.addCurrentVertex(ae,Et,0,0,se,ze);else if(qe==="flipbevel"){if(Dt>100)Et=Ae.mult(-1);else{const Bt=Dt*Te.add(Ae).mag()/Te.sub(Ae).mag();Et._perp()._mult(Bt*(vt?-1:1))}this.addCurrentVertex(ae,Et,0,0,se,ze),this.addCurrentVertex(ae,Et.mult(-1),0,0,se,ze)}else if(qe==="bevel"||qe==="fakeround"){const Bt=ae.dist(fe);let Yt=1;if(this.elevationType==="offset"&&qe==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&ze!=null&&fe&&ue){const _r=4*Rt;Bt<_r&&(Yt=Math.max(0,Bt/_r))}ze!=null&&fe&&this.addCurrentVertex(ae,We||Te,-Yt,-Yt,se,ze);const tr=Bt<=2*Rt&&qe!=="bevel",wr=Et.mult(vt?1:-1);wr._mult(Dt);const ur=Ae.mult(vt?-1:1),cr=Te.mult(vt?-1:1),rr=this.evaluateLineProgressFeatures(this.distance);if(ze==null&&(this.addHalfVertex(ae,wr.x,wr.y,!1,!vt,0,se,rr),tr||this.addHalfVertex(ae,wr.x+2*cr.x,wr.y+2*cr.y,!1,vt,0,se,rr)),qe==="fakeround"){const _r=Math.round(180*Pt/Math.PI/20);this.addHalfVertex(ae,cr.x,cr.y,!1,vt,0,se,rr);for(let Rr=0;Rr<_r;Rr++){let Wr=Rr/_r;if(Wr!==.5){const fn=Wr-.5;Wr+=Wr*fn*(Wr-1)*((1.0904+bt*(bt*(3.55645-1.43519*bt)-3.2452))*fn*fn+(.848013+bt*(.215638*bt-1.06021)))}const Dr=ur.sub(cr)._mult(Wr)._add(cr)._unit();this.addHalfVertex(ae,Dr.x,Dr.y,!1,vt,0,se,rr)}this.addHalfVertex(ae,ur.x,ur.y,!1,vt,0,se,rr)}tr||ze!=null||this.addHalfVertex(ae,wr.x+2*ur.x,wr.y+2*ur.y,!1,vt,0,se,rr),ze!=null&&ue&&this.addCurrentVertex(ae,Ie||Ae,Yt,Yt,se,ze)}else if(qe==="butt")this.addCurrentVertex(ae,Et,0,0,se,ze);else if(qe==="square"){if(!fe){const Bt=V?0:-1;this.addCurrentVertex(ae,Et,Bt,Bt,se,ze)}if(this.addCurrentVertex(ae,Et,0,0,se,ze),fe){const Bt=G?0:1;this.addCurrentVertex(ae,Et,Bt,Bt,se,ze)}}else if(qe==="round"){if(fe){const Bt=!Ve&&We?We:Te;this.addCurrentVertex(ae,Bt,0,0,se,ze),!Ve&&G||this.addCurrentVertex(ae,Bt,1,1,se,ze,!0)}if(ue){const Bt=!Ve&&Ie?Ie:Ae;!Ve&&V||this.addCurrentVertex(ae,Bt,-1,-1,se,ze,!0),this.addCurrentVertex(ae,Bt,0,0,se,ze)}}}}addVerticesTo(l,u,p,x,b,T,k,P,O,$){const V=(u.w-l.w)/this.tessellationStep|0;let G=0;const Y=this.scaledDistance;if(V>1){this.lineSoFar=l.w;const te=(u.x-l.x)/V,se=(u.y-l.y)/V,ae=(u.z-l.z)/V,fe=(u.w-l.w)/V,ue=u.x-l.x,Te=u.y-l.y,Ae=Math.sqrt(ue*ue+Te*Te);if(Ae===0)return;const Ie=-Te/Ae,We=ue/Ae,ze=Ie,He=We,Ve=-Ie,qe=-We;for(let bt=1;bt=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,$),P.primitiveLength++),T?this.e2=$:this.e1=$,O!=null&&this.zOffsetVertexArray.emplaceBack(O.zOffset,O.variableWidth,O.variableWidth),this.elevationGroundScaleValue){const V=O?O.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(V)}}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 j$(h,l,u){return h.xu||h.yu}let TJ,jJ;function EJ(h,l,u){return l*(fr/(h.tileSize*Math.pow(2,u-h.tileID.overscaledZ)))}jr(uR,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const kJ=(h,l,u)=>(1-u)*h+u*l;function AJ(h,l){return 1/EJ(h,1,l.tileZoom)}function NJ(h,l,u,p){return h.translatePosMatrix(p||l.tileID.projMatrix,l,u.paint.get("line-translate"),u.paint.get("line-translate-anchor"))}const CJ=h=>{const l=[];IJ(h)&&l.push("RENDER_LINE_DASH"),h.paint.get("line-gradient")&&l.push("RENDER_LINE_GRADIENT"),h.paint.get("line-blend-mode")==="multiply"&&l.push("LINE_BLEND_MULTIPLY");const u=h.paint.get("line-trim-offset");u[0]===0&&u[1]===0||l.push("RENDER_LINE_TRIM_OFFSET"),h.paint.get("line-border-width").constantOr(1)!==0&&l.push("RENDER_LINE_BORDER");const p=h.layout.get("line-join").constantOr("miter")==="none",x=!!h.paint.get("line-pattern").constantOr(1);return p&&x&&l.push("LINE_JOIN_NONE"),l};function IJ(h){const l=h.paint.get("line-dasharray").value;return l.kind!=="constant"||l.value}let E$;const PJ=()=>E$||(E$={layout:TJ||(TJ=new fi({"line-cap":new Qt(at.layout_line["line-cap"]),"line-join":new Qt(at.layout_line["line-join"]),"line-miter-limit":new sr(at.layout_line["line-miter-limit"]),"line-round-limit":new sr(at.layout_line["line-round-limit"]),"line-sort-key":new Qt(at.layout_line["line-sort-key"]),"line-z-offset":new Qt(at.layout_line["line-z-offset"]),"line-elevation-reference":new sr(at.layout_line["line-elevation-reference"]),"line-cross-slope":new sr(at.layout_line["line-cross-slope"]),visibility:new sr(at.layout_line.visibility),"line-width-unit":new sr(at.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Qt(at.layout_line["line-elevation-ground-scale"])})),paint:jJ||(jJ=new fi({"line-opacity":new Qt(at.paint_line["line-opacity"]),"line-color":new Qt(at.paint_line["line-color"]),"line-translate":new sr(at.paint_line["line-translate"]),"line-translate-anchor":new sr(at.paint_line["line-translate-anchor"]),"line-width":new Qt(at.paint_line["line-width"]),"line-gap-width":new Qt(at.paint_line["line-gap-width"]),"line-offset":new Qt(at.paint_line["line-offset"]),"line-blur":new Qt(at.paint_line["line-blur"]),"line-dasharray":new Qt(at.paint_line["line-dasharray"]),"line-pattern":new Qt(at.paint_line["line-pattern"]),"line-pattern-cross-fade":new sr(at.paint_line["line-pattern-cross-fade"]),"line-gradient":new by(at.paint_line["line-gradient"]),"line-trim-offset":new sr(at.paint_line["line-trim-offset"]),"line-trim-fade-range":new sr(at.paint_line["line-trim-fade-range"]),"line-trim-color":new sr(at.paint_line["line-trim-color"]),"line-emissive-strength":new Qt(at.paint_line["line-emissive-strength"]),"line-border-width":new Qt(at.paint_line["line-border-width"]),"line-border-color":new Qt(at.paint_line["line-border-color"]),"line-occlusion-opacity":new sr(at.paint_line["line-occlusion-opacity"]),"line-blend-mode":new sr(at.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"})}))},E$);class URe extends Qt{possiblyEvaluate(l,u){return u=new fs(Math.floor(u.zoom),{now:u.now,fadeDuration:u.fadeDuration,transition:u.transition,worldview:u.worldview}),super.possiblyEvaluate(l,u)}evaluate(l,u,p,x){return u=Object.assign({},u,{zoom:Math.floor(u.zoom)}),super.evaluate(l,u,p,x)}}let k2;function RJ(h,l){return l>0?l+2*h:h}const VRe=On([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),qRe=On([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),GRe=On([{name:"a_projected_pos",components:4,type:"Float32"}],4);On([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const HRe=On([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),WRe=On([{name:"a_feature_index",components:1,type:"Float32"}],4),KRe=On([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),YRe=On([{name:"a_texb",components:2,type:"Uint16"}]),ZRe=On([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),XRe=On([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);On([{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 LJ=On([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),QRe=On([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);On([{name:"triangle",components:3,type:"Uint16"}]),On([{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"}]),On([{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"}]),On([{type:"Float32",name:"offsetX"}]),On([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const k$=class KM{constructor(l=null,u=0,p=4096){this.batchIndex=u,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=l||null,this.propsDwords=p,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(KM.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,KM.HEADER_BYTES,u.DYNAMIC_DRAW),this.propertiesBuffer=u.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(u.bindBuffer(u.UNIFORM_BUFFER,this.propertiesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),this.blockIndicesBuffer=u.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");u.bindBuffer(u.UNIFORM_BUFFER,this.blockIndicesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),u.bindBuffer(u.UNIFORM_BUFFER,null)}writeHeader(l){const u=this.headerData;u[0]=l.dataDrivenMask,u[1]=l.zoomDependentMask,u[2]=l.dataDrivenBlockSizeVec4,u[3]=l.offsets[0],u[4]=l.offsets[1],u[5]=l.offsets[2],u[6]=l.offsets[3],u[7]=l.offsets[4],u[8]=l.offsets[5],u[9]=l.offsets[6],u[10]=l.offsets[7],u[11]=l.offsets[8]}writeDataDrivenBlock(l,u,p){const x=4*p.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 T=0;T<9;T++)p.dataDrivenMask&1<{if(!k)return;const O=p.getUniformBlockIndex(u,T);O!==p.INVALID_INDEX&&(p.uniformBlockBinding(u,O,P),p.bindBufferBase(p.UNIFORM_BUFFER,P,k))},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)}}};k$.HEADER_DWORDS=12,k$.HEADER_BYTES=48;let A$=k$;function N$(h,l,u,p){return[kw(255*h,255*l),kw(255*u,255*p)]}function MJ(h,l,u,p,x,b,T,k){return!!h&&(h.kind==="constant"?h.value==="none":h.kind==="composite"||h.kind==="source"?h.evaluate({zoom:0,brightness:b,worldview:k},l,u,x,p,T)==="none":typeof h=="string"&&h==="none")}jr(A$,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class C${constructor(l,u,p,x,b="",T,k){this.layer=l,this.zoom=u,this.lut=p,this.isText=x,this.propDefs=this._getPropDefs(),this.worldview=b,this.maxUniformBufferBindings=T||24,this.uboSizeDwords=k||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(l,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 p=0,x=0,b=0,T=0;const k=[0,0,0,0,0,0,0,0,0];for(let P=0;P<9;P++){const{name:O,isColor:$,isVec2:V}=u[P],G=l.get(O),Y=!(!G||typeof G.isConstant!="function"||G.isConstant()),X=this._appearancesHavePaintProperties(O),te=Y||X,se=!(!G||!G.value||G.value.kind!=="composite"),ae=this.layer._transitionablePaint._values[O],fe=!te&&(ae&&ae.value&&ae.value.expression&&ae.value.expression.kind)==="camera";te?(p|=1<u.hasPaintProperty(l):this.isText?u=>u.hasTextPaintProperties():u=>u.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(l,u){const p=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 T of b){const k=p.get(T);if(k&&typeof k=="object"&&"isConstant"in k&&!k.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(l,u){if(u.dataDrivenMask===0)return"";const p=[];for(let x=0;x<9;x++){if(!(u.dataDrivenMask&1<=X){hr(`Too many symbol features: batch ${G} requires binding points up to ${3*G+2}, device limit ${X}. Some features will render incorrectly.`);const se={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:u,featureId:P};return this.allFeatures.push(se),P!=null&&(this.featureVertexRangesFromId.has(P)||this.featureVertexRangesFromId.set(P,[]),this.featureVertexRangesFromId.get(P).push(se)),0}this.ubos[G]||(this.ubos[G]=new A$(k,G,this.uboSizeDwords),this.ubos[G].writeHeader(O)),this.ubos[G].writeDataDrivenBlock($,Y,O);const te={batchIndex:G,localFeatureIndex:Y,vtFeatureIndex:u,featureId:P};return this.allFeatures.push(te),P!=null&&(this.featureVertexRangesFromId.has(P)||this.featureVertexRangesFromId.set(P,[]),this.featureVertexRangesFromId.get(P).push(te)),Y}updateFeatures(l,u,p,x,b,T,k){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const P=this.cachedHeader;for(const O of l){const $=this.featureVertexRangesFromId.get(O);if(!$)continue;const V=T[O]||{};for(const G of $){if(!p)continue;const Y=p.feature(G.vtFeatureIndex);if(!Y)continue;const X={type:Y.type,id:O,properties:Y.properties||{},geometry:[]},te=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(G.vtFeatureIndex):void 0,se=this.evaluateAllProperties(X,V,x,b,k,void 0,te);this.ubos[G.batchIndex]&&this.ubos[G.batchIndex].writeDataDrivenBlock(se,G.localFeatureIndex,P)}}}updateDynamicExpressions(l,u,p,x,b,T){if(this.layer=l,this.cachedConstantUniforms=null,!this.cachedHeader)return;const k=this.cachedHeader;for(const P of this.allFeatures){if(!u)continue;const O=u.feature(P.vtFeatureIndex);if(!O)continue;const $=P.featureId!=null&&b[P.featureId]||{},V={type:O.type,id:P.featureId,properties:O.properties||{},geometry:[]},G=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(P.vtFeatureIndex):void 0,Y=this.evaluateAllProperties(V,$,p,x,T,void 0,G);this.ubos[P.batchIndex]&&this.ubos[P.batchIndex].writeDataDrivenBlock(Y,P.localFeatureIndex,k)}}updateFeaturePaintForAppearance(l,u,p,x,b,T,k){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(l,k||null),!this.cachedHeader))return!1;const P=this.cachedHeader;if(P.dataDrivenMask===0)return!1;let O=!1;for(const $ of this.allFeatures){if($.vtFeatureIndex!==l)continue;const V=this.evaluateAllProperties(u,p,x,b,T,void 0,k);this.ubos[$.batchIndex]&&(this.ubos[$.batchIndex].writeDataDrivenBlock(V,$.localFeatureIndex,P),O=!0)}return O}getConstantUniformValues(l,u){const p=this.cachedHeader,x=!(!p||!p.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===u&&(!x||this.cachedConstantRenderZoom===l))return this.cachedConstantUniforms;const b=this.layer.paint,T=this.propDefs,k=x?new fs(l,{brightness:u,worldview:this.worldview}):null,P={type:1,id:void 0,properties:{},geometry:[]},O=G=>{const Y=T[G],X=b.get(Y.name);if(!X)return[0,0,0,1];const te=Y.useThemeName?b.get(Y.useThemeName):void 0,se=MJ(te&&typeof te!="string"?te.value:void 0,P,{},[],void 0,u,void 0,this.worldview)?null:this.lut;let ae;ae=p&&p.cameraMask&1<{const X=b.get(T[G].name);if(!X)return Y;if(p&&p.cameraMask&1<{p.text=function(x,b,T){const k=b.layout.get("text-transform").evaluate(T,{});return k==="uppercase"?x=x.toLocaleUpperCase():k==="lowercase"&&(x=x.toLocaleLowerCase()),Hh.applyArabicShaping&&(x=Hh.applyArabicShaping(x)),x}(p.text,l,u)}),h}const A2={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function eLe(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function tLe(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const I$=4294967296,DJ=1/I$,OJ=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let dR=class{constructor(h=new Uint8Array(16)){this.buf=ArrayBuffer.isView(h)?h:new Uint8Array(h),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(h,l,u=this.length){for(;this.pos>3,b=this.pos;this.type=7&p,h(x,l,this),this.pos===b&&this.skip(p)}return l}readMessage(h,l){return this.readFields(h,l,this.readVarint()+this.pos)}readFixed32(){const h=this.dataView.getUint32(this.pos,!0);return this.pos+=4,h}readSFixed32(){const h=this.dataView.getInt32(this.pos,!0);return this.pos+=4,h}readFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*I$;return this.pos+=8,h}readSFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*I$;return this.pos+=8,h}readFloat(){const h=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,h}readDouble(){const h=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,h}readVarint(h){const l=this.buf;let u,p;return p=l[this.pos++],u=127&p,p<128?u:(p=l[this.pos++],u|=(127&p)<<7,p<128?u:(p=l[this.pos++],u|=(127&p)<<14,p<128?u:(p=l[this.pos++],u|=(127&p)<<21,p<128?u:(p=l[this.pos],u|=(15&p)<<28,function(x,b,T){const k=T.buf;let P,O;if(O=k[T.pos++],P=(112&O)>>4,O<128||(O=k[T.pos++],P|=(127&O)<<3,O<128)||(O=k[T.pos++],P|=(127&O)<<10,O<128)||(O=k[T.pos++],P|=(127&O)<<17,O<128)||(O=k[T.pos++],P|=(127&O)<<24,O<128)||(O=k[T.pos++],P|=(1&O)<<31,O<128))return Ow(x,P,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&&OJ?OJ.decode(this.buf.subarray(l,h)):function(u,p,x){let b="",T=p;for(;T239?4:k>223?3:k>191?2:1;if(T+G>x)break;G===1?k<128&&(V=k):G===2?(P=u[T+1],(192&P)==128&&(V=(31&k)<<6|63&P,V<=127&&(V=null))):G===3?(P=u[T+1],O=u[T+2],(192&P)==128&&(192&O)==128&&(V=(15&k)<<12|(63&P)<<6|63&O,(V<=2047||V>=55296&&V<=57343)&&(V=null))):G===4&&(P=u[T+1],O=u[T+2],$=u[T+3],(192&P)==128&&(192&O)==128&&(192&$)==128&&(V=(15&k)<<18|(63&P)<<12|(63&O)<<6|63&$,(V<=65535||V>=1114112)&&(V=null))),V===null?(V=65533,G=1):V>65535&&(V-=65536,b+=String.fromCharCode(V>>>10&1023|55296),V=56320|1023&V),b+=String.fromCharCode(V),T+=G}return b}(this.buf,l,h)}readBytes(){const h=this.readVarint()+this.pos,l=this.buf.subarray(this.pos,h);return this.pos=h,l}readPackedVarint(h=[],l){const u=this.readPackedEnd();for(;this.pos127;);else if(l===2)this.pos=this.readVarint()+this.pos;else if(l===5)this.pos+=4;else{if(l!==1)throw new Error(`Unimplemented type: ${l}`);this.pos+=8}}writeTag(h,l){this.writeVarint(h<<3|l)}realloc(h){let l=this.length||16;for(;l268435455||h<0?function(l,u){let p,x;if(l>=0?(p=l%4294967296|0,x=l/4294967296|0):(p=~(-l%4294967296),x=~(-l/4294967296),4294967295^p?p=p+1|0:(p=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,T,k){k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,k.buf[k.pos]=127&(b>>>=7)}(p,0,u),function(b,T){const k=(7&b)<<4;T.buf[T.pos++]|=k|((b>>>=3)?128:0),b&&(T.buf[T.pos++]=127&b|((b>>>=7)?128:0),b&&(T.buf[T.pos++]=127&b|((b>>>=7)?128:0),b&&(T.buf[T.pos++]=127&b|((b>>>=7)?128:0),b&&(T.buf[T.pos++]=127&b|((b>>>=7)?128:0),b&&(T.buf[T.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(p,x,b){for(let T,k,P=0;P55295&&T<57344){if(!k){T>56319||P+1===x.length?(p[b++]=239,p[b++]=191,p[b++]=189):k=T;continue}if(T<56320){p[b++]=239,p[b++]=191,p[b++]=189,k=T;continue}T=k-55296<<10|T-56320|65536,k=null}else k&&(p[b++]=239,p[b++]=191,p[b++]=189,k=null);T<128?p[b++]=T:(T<2048?p[b++]=T>>6|192:(T<65536?p[b++]=T>>12|224:(p[b++]=T>>18|240,p[b++]=T>>12&63|128),p[b++]=T>>6&63|128),p[b++]=63&T|128)}return b}(this.buf,h,this.pos);const u=this.pos-l;u>=128&&FJ(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&&FJ(u,p,this),this.pos=u-1,this.writeVarint(p),this.pos+=p}writeMessage(h,l,u){this.writeTag(h,2),this.writeRawMessage(l,u)}writePackedVarint(h,l){l.length&&this.writeMessage(h,rLe,l)}writePackedSVarint(h,l){l.length&&this.writeMessage(h,nLe,l)}writePackedBoolean(h,l){l.length&&this.writeMessage(h,aLe,l)}writePackedFloat(h,l){l.length&&this.writeMessage(h,sLe,l)}writePackedDouble(h,l){l.length&&this.writeMessage(h,iLe,l)}writePackedFixed32(h,l){l.length&&this.writeMessage(h,oLe,l)}writePackedSFixed32(h,l){l.length&&this.writeMessage(h,lLe,l)}writePackedFixed64(h,l){l.length&&this.writeMessage(h,cLe,l)}writePackedSFixed64(h,l){l.length&&this.writeMessage(h,uLe,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 Ow(h,l,u){return u?4294967296*l+(h>>>0):4294967296*(l>>>0)+(h>>>0)}function FJ(h,l,u){const p=l<=16383?1:l<=2097151?2:l<=268435455?3:Math.floor(Math.log(l)/(7*Math.LN2));u.realloc(p);for(let x=u.pos-1;x>=h;x--)u.buf[x+p]=u.buf[x]}function rLe(h,l){for(let u=0;u=0&&p>=l&&hR[this.text.charCodeAt(p)];p--)u--;this.text=this.text.substring(l,u),this.sectionIndex=this.sectionIndex.slice(l,u)}substring(l,u){const p=new Fw;return p.text=this.text.substring(l,u),p.sectionIndex=this.sectionIndex.slice(l,u),p.sections=this.sections,p}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((l,u)=>Math.max(l,this.sections[u].scale),0)}addTextSection(l,u){this.text+=l.text,this.sections.push(N2.forText(l.scale,l.fontStack||u));const p=this.sections.length-1;for(let x=0;x=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function P$(h,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te=1,se=1){const ae=Fw.fromFeature(h,x,te,se);V===ru.vertical&&ae.verticalizePunctuation(G);let fe=[];const ue=function(ze,He,Ve,qe,bt,Et,It=1){if(!ze)return[];const Dt=[],Pt=function(Rt,Bt,Yt,tr,wr,ur,cr=1){let rr=0;for(let _r=0;_r=0;let vt=0;for(let Rt=0;Rt0&&gl>En&&(En=gl)}else{const oo=Ve[vi.fontStack];if(!oo)continue;oo[_i]&&(Li=oo[_i]);const Fl=He[vi.fontStack];if(!Fl)continue;const Fo=Fl.glyphs[_i];if(!Fo)continue;if(aa=Fo.metrics,Qa=_i!==8203?Za:0,cr){const Ei=Fl.ascender!==void 0?Math.abs(Fl.ascender):0,gl=Fl.descender!==void 0?Math.abs(Fl.descender):0,lo=(Ei+gl)*Ri;ji-u/2;){if(T--,T<0)return!1;k-=h[T].dist(b),b=h[T]}k+=h[T].dist(h[T+1]),T++;const P=[];let O=0;for(;kp;)O-=P.shift().angleDelta;if(O>x)return!1;T++,k+=$.dist(V)}return!0}function KJ(h){let l=0;for(let u=0;uO){const X=(O-P)/Y,te=sn(V.x,G.x,X),se=sn(V.y,G.y,X),ae=new Gp(te,se,0,G.angleTo(V),$);return!T||WJ(h,ae,k,T,l)?ae:void 0}P+=Y}}function yLe(h,l,u,p,x,b,T,k,P){const O=YJ(p,b,T),$=ZJ(p,x),V=$*T,G=h[0].x===0||h[0].x===P||h[0].y===0||h[0].y===P;return l-V=0&&Te=0&&Ae=0&&G+O<=$){const Ie=new Gp(Te,Ae,0,fe,X);p&&!WJ(h,Ie,b,p,x)||Y.push(Ie)}}V+=ae}return k||Y.length||T||(Y=XJ(h,V/2,u,p,x,b,T,!0,P)),Y}function QJ(h){let l=0,u=0;for(const T of h)l+=T.w*T.h,u=Math.max(u,T.w);h.sort((T,k)=>k.h-T.h);const p=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(l/.95)),u),h:1/0}];let x=0,b=0;for(const T of h)for(let k=p.length-1;k>=0;k--){const P=p[k];if(!(T.w>P.w||T.h>P.h)){if(T.x=P.x,T.y=P.y,b=Math.max(b,T.y+T.h),x=Math.max(x,T.x+T.w),T.w===P.w&&T.h===P.h){const O=p.pop();O&&kl.id?1:h.versionl.version?1:h.sxl.sx?1:h.syl.sy?1:0}function O$(h){let l=0;for(let u=0;u0,JJ(l,p,this.iconDescriptors,b),JJ(u,p,this.patternDescriptors,b),this.iconDescriptors.sort(mR),this.patternDescriptors.sort(mR);let T=0;const k=x?x.data:"";k&&(T=Qh(T,O$(k))),T=Qh(T,1);for(const P of this.iconDescriptors)T=Qh(T,O$(P.id)),T=Qh(T,P.version),T=Qh(T,P.sx),T=Qh(T,P.sy);T=Qh(T,1);for(const P of this.patternDescriptors)T=Qh(T,O$(P.id)),T=Qh(T,P.version),T=Qh(T,P.sx),T=Qh(T,P.sy);this.hash=T}subsetOf(l){return this.isSubsetArray(this.iconDescriptors,l.iconDescriptors,mR)&&this.isSubsetArray(this.patternDescriptors,l.patternDescriptors,mR)}isSubsetArray(l,u,p){let x=0,b=0;if(l.length>u.length)return!1;for(;x{const T=x.variant.id.toString().localeCompare(b.variant.id.toString());return T!==0?T: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 p=new Map;for(const x of u)p.set(x.key,x.value);return p}class eee{constructor(l){this.sourceAtlasHash=l}}class tee{constructor(l,u,p,x){const b=new Map,T=new Map;this.haveRenderCallbacks=[];const k=[],P=x!==void 0,O=P?new Map:void 0,$=P?$$(l,O):l,V=P?$$(u,O):u;this.addImages($,b,1,k),this.addImages(V,T,2,k);const{w:G,h:Y}=QJ(k),X=new Jo({width:G||1,height:Y||1});for(const[te,se]of $.entries()){const ae=b.get(te).paddedRect;Jo.copy(se.data,X,{x:0,y:0},{x:ae.x+1,y:ae.y+1},se.data,null,se.sdf)}for(const[te,se]of V.entries()){const ae=T.get(te),fe=ae.paddedRect;let ue=ae.padding;const Te=fe.x+ue,Ae=fe.y+ue,Ie=se.data.width,We=se.data.height;ue=ue>1?ue-1:ue,Jo.copy(se.data,X,{x:0,y:0},{x:Te,y:Ae},se.data,p),Jo.copy(se.data,X,{x:0,y:We-ue},{x:Te,y:Ae-ue},{width:Ie,height:ue},p),Jo.copy(se.data,X,{x:0,y:0},{x:Te,y:Ae+We},{width:Ie,height:ue},p),Jo.copy(se.data,X,{x:Ie-ue,y:0},{x:Te-ue,y:Ae},{width:ue,height:We},p),Jo.copy(se.data,X,{x:0,y:0},{x:Te+Ie,y:Ae},{width:ue,height:We},p),Jo.copy(se.data,X,{x:Ie-ue,y:We-ue},{x:Te-ue,y:Ae-ue},{width:ue,height:ue},p),Jo.copy(se.data,X,{x:0,y:We-ue},{x:Te+Ie,y:Ae-ue},{width:ue,height:ue},p),Jo.copy(se.data,X,{x:0,y:0},{x:Te+Ie,y:Ae+We},{width:ue,height:ue},p),Jo.copy(se.data,X,{x:Ie-ue,y:0},{x:Te-ue,y:Ae+We},{width:ue,height:ue},p)}this.lut=p,this.image=X,this.iconPositions=b,this.patternPositions=T,P&&(this.contentDescriptor=new F$($,V,x,p,O))}addImages(l,u,p,x){for(const[b,T]of l.entries()){const{bin:k,imagePosition:P,imageVariant:O}=B$(b,T,p);u.set(b,P),x.push(k),T.hasRenderCallback&&this.haveRenderCallbacks.push(O.id)}}patchUpdatedImages(l,u,p,x){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(b=>l.hasImage(b,p)),l.dispatchRenderCallbacks(this.haveRenderCallbacks,p);for(const b of l.getUpdatedImages(p)){for(const T of this.iconPositions.keys()){const k=Mu.parse(T);if(Tc.isEqual(k.id,b)){const P=l.getImage(b,p);this.patchUpdatedImage(this.iconPositions.get(T),P,u,null)}}for(const T of this.patternPositions.keys()){const k=Mu.parse(T);if(Tc.isEqual(k.id,b)){const P=l.getImage(b,p);this.patchUpdatedImage(this.patternPositions.get(T),P,u,x||this.lut)}}}}patchUpdatedImage(l,u,p,x=null){if(!l||!u||l.version===u.version)return;l.version=u.version;const[b,T]=l.tl,k=l.sdf;if(this.lut||k){const P={width:u.data.width,height:u.data.height},O=new Jo(P);Jo.copy(u.data,O,{x:0,y:0},{x:0,y:0},P,x,k),p.update(O,{position:{x:b,y:T},recreateWhenResize:!1})}else p.update(u.data,{position:{x:b,y:T},recreateWhenResize:!1})}}jr(C2,"ImagePosition"),jr(tee,"ImageAtlas",{omit:["lut"]}),jr(eee,"ImageAtlasReference");class I2{constructor(l){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!l||l.useServerFontComposition===void 0||l.useServerFontComposition}loadGlyphRange(l,u,p,x,b){if(this.useServerFontComposition)return void I2.loadGlyphRange(l,u,p,x,b);const T=l.split(",").map(k=>k.trim()).filter(k=>k.length>0);T.length!==0?T.length!==1?this._loadMultipleFonts(T,u,p,x,b):this._loadFont(T[0],u,p,x,b):b(new Error("Empty fontstack"))}_loadMultipleFonts(l,u,p,x,b){const T=l.map(()=>null),k={completed:0,firstError:null,callbackCalled:!1},P=(O,$,V)=>{if(!k.callbackCalled&&($&&!k.firstError&&(k.firstError=$),V&&(T[O]=V),k.completed++,k.completed===l.length)){k.callbackCalled=!0;const G=T.filter(X=>X!==null);if(G.length===0)return void b(k.firstError||new Error("All fonts failed to load"));const Y=this._composeGlyphs(G);b(null,Y)}};for(let O=0;O{P(O,$,V)})}_loadFont(l,u,p,x,b){const T=`${l}:${u}`;if(this.cachedRanges.has(T)){const P=this.cachedRanges.get(T);return void Zl.frame(()=>b(null,P))}const k=this.pendingRequests.get(T);k?k.push(b):(this.pendingRequests.set(T,[b]),I2.loadGlyphRange(l,u,p,x,(P,O)=>{P||this.cachedRanges.set(T,O||null);const $=this.pendingRequests.get(T);if(this.pendingRequests.delete(T),$)for(const V of $)V(P,O)}))}_composeGlyphs(l){const u={};let p,x;for(const b of l)if(p===void 0&&b.ascender!==void 0&&(p=b.ascender),x===void 0&&b.descender!==void 0&&(x=b.descender),b.glyphs)for(const T in b.glyphs)u[T]===void 0&&(u[T]=b.glyphs[T]);return{glyphs:u,ascender:p,descender:x}}}I2.loadGlyphRange=function(h,l,u,p,x){const b=256*l,T=b+255,k=p.transformRequest(p.normalizeGlyphsURL(u).replace("{fontstack}",h).replace("{range}",`${b}-${T}`),D0.Glyphs);ey(k,(P,O)=>{if(P)x(P);else if(O){const $={},V=function(G){return new dR(G).readFields(dLe,{})}(O);for(const G of V.glyphs)$[G.id]=G;x(null,{glyphs:$,ascender:V.ascender,descender:V.descender})}})};const P2=1e20;function ree(h,l,u,p,x,b,T,k,P){for(let O=l;O-1);P++,b[P]=k,T[P]=O,T[P+1]=P2}for(let k=0,P=0;k{if(T){x.ascender=T.ascender,x.descender=T.descender;for(const k in T.glyphs)this._doesCharSupportLocalGlyph(+k)||(x.glyphs[+k]=T.glyphs[+k]);x.ranges[u]=!0}for(const k of x.requests[u]||[])k(b,T);delete x.requests[u]}))}getGlyphs(l,u){const p=[],x=this.url||Vn.GLYPHS_URL;for(const b in l)for(const T of l[b])p.push({stack:b,id:T});et(p,({stack:b,id:T},k)=>{let P=this.entries[b];P||(P=this.entries[b]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let O=P.glyphs[T];if(O!==void 0)return void k(null,{stack:b,id:T,glyph:O});if(O=this._tinySDF(P,b,T),O)return P.glyphs[T]=O,void k(null,{stack:b,id:T,glyph:O});const $=Math.floor(T/256);if(256*$>65535)return hr("glyphs > 65535 not supported"),void k(null,{stack:b,id:T,glyph:O});if(P.ranges[$])return void k(null,{stack:b,id:T,glyph:O});let V=P.requests[$];V||(V=P.requests[$]=[],this.glyphLoader.loadGlyphRange(b,$,x,this.requestManager,(G,Y)=>{if(Y){P.ascender=Y.ascender,P.descender=Y.descender;for(const X in Y.glyphs)this._doesCharSupportLocalGlyph(+X)||(P.glyphs[+X]=Y.glyphs[+X]);P.ranges[$]=!0}for(const X of V)X(G,Y);delete P.requests[$]})),V.push((G,Y)=>{G?k(G):Y&&k(null,{stack:b,id:T,glyph:Y.glyphs[T]||null})})},(b,T)=>{if(b)u(b);else if(T){const k={};for(const{stack:P,id:O,glyph:$}of T)k[P]===void 0&&(k[P]={}),k[P].glyphs===void 0&&(k[P].glyphs={}),k[P].glyphs[O]=$&&{id:$.id,bitmap:$.bitmap.clone(),metrics:$.metrics},k[P].ascender=this.entries[P].ascender,k[P].descender=this.entries[P].descender;u(null,k)}})}_doesCharSupportLocalGlyph(l){return this.localGlyphMode!==z$.none&&(this.localGlyphMode===z$.all?!!this.localFontFamily:!!this.localFontFamily&&(uw(l)||jE(l)||fv(l)||Ip(l)||hv(l)||SE(l)||(u=l)>=131072&&u<=173791||(p=>p>=66736&&p<=66815)(l)));var u}_tinySDF(l,u,p){const x=this.localFontFamily;if(!x||!this._doesCharSupportLocalGlyph(p))return;let b=l.tinySDF;if(!b){let se="400";/bold/i.test(u)?se="900":/medium/i.test(u)?se="500":/light/i.test(u)&&(se="200"),b=l.tinySDF=new pR.TinySDF({fontFamily:x,fontWeight:se,fontSize:48,buffer:6,radius:16}),b.fontWeight=se}const T=b.fontWeight;if(this.localGlyphs[T][p])return this.localGlyphs[T][p];const k=String.fromCodePoint(p),{data:P,width:O,height:$,glyphWidth:V,glyphHeight:G,glyphLeft:Y,glyphTop:X,glyphAdvance:te}=b.draw(k);return this.localGlyphs[T][p]={id:p,bitmap:new ky({width:O,height:$},P),metrics:{width:V/2,height:G/2,left:Y/2,top:X/2-27,advance:te/2,localGlyph:!0}}}}function see(h,l){return h+l[1]-l[0]}function U$(h,l,u,p,x=1){const b=[],T=h.imagePrimary,k=T.pixelRatio,P=T.paddedRect.w-2,O=T.paddedRect.h-2,$=(h.right-h.left)*x,V=(h.bottom-h.top)*x,G=T.stretchX||[[0,P]],Y=T.stretchY||[[0,O]],X=G.reduce(see,0),te=Y.reduce(see,0),se=P-X,ae=O-te;let fe=0,ue=X,Te=0,Ae=te,Ie=0,We=se,ze=0,He=ae;if(T.content&&p){const qe=T.content;fe=gR(G,0,qe[0]),Te=gR(Y,0,qe[1]),ue=gR(G,qe[0],qe[2]),Ae=gR(Y,qe[1],qe[3]),Ie=qe[0]-fe,ze=qe[1]-Te,We=qe[2]-qe[0]-ue,He=qe[3]-qe[1]-Ae}const Ve=(qe,bt,Et,It)=>{const Dt=yR(qe.stretch-fe,ue,$,h.left*x),Pt=xR(qe.fixed-Ie,We,qe.stretch,X),Ht=yR(bt.stretch-Te,Ae,V,h.top*x),vt=xR(bt.fixed-ze,He,bt.stretch,te),Rt=yR(Et.stretch-fe,ue,$,h.left*x),Bt=xR(Et.fixed-Ie,We,Et.stretch,X),Yt=yR(It.stretch-Te,Ae,V,h.top*x),tr=xR(It.fixed-ze,He,It.stretch,te),wr=new Ft(Dt,Ht),ur=new Ft(Rt,Ht),cr=new Ft(Rt,Yt),rr=new Ft(Dt,Yt),_r=new Ft(Pt/k,vt/k),Rr=new Ft(Bt/k,tr/k),Wr=l*Math.PI/180;if(Wr){const En=Math.sin(Wr),ji=Math.cos(Wr),ms=[ji,-En,En,ji];wr._matMult(ms),ur._matMult(ms),rr._matMult(ms),cr._matMult(ms)}const Dr=qe.stretch+qe.fixed,fn=Et.stretch+Et.fixed,Wn=bt.stretch+bt.fixed,mn=It.stretch+It.fixed,es=h.imageSecondary;return{tl:wr,tr:ur,bl:rr,br:cr,texPrimary:{x:T.paddedRect.x+1+Dr,y:T.paddedRect.y+1+Wn,w:fn-Dr,h:mn-Wn},texSecondary:es?{x:es.paddedRect.x+1+Dr,y:es.paddedRect.y+1+Wn,w:fn-Dr,h:mn-Wn}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:_r,pixelOffsetBR:Rr,minFontScaleX:We/k/$,minFontScaleY:He/k/V,isSDF:u}};if(T.stretchX||T.stretchY){const qe=iee(G,se,X),bt=iee(Y,ae,te);for(let Et=0;Et0?[fe,-ue]:Te<0?[-fe,ue]:fe===0?[ue,fe]:[ue,-fe]}(u);let Y=Math.abs(l.top-l.bottom);for(const ae of l.positionedLines)Y-=ae.lineOffset;const X=l.positionedLines.length,te=Y/X;let se=l.top-u[1];for(let ae=0;aeb)&&(b=X.x),(!Y||X.y>T)&&(T=X.y)}const P=Math.min(b-p,T-x);let O=P/2;const $=new X0([],bLe);if(P===0)return new Ft(p,x);for(let Y=p;YV.d||!V.d)&&(V=Y,u&&console.log("found best %d after %d probes",Math.round(1e4*Y.d)/1e4,G)),Y.max-V.d<=l||(O=Y.h/2,$.push(new $w(Y.p.x-O,Y.p.y-O,O,h)),$.push(new $w(Y.p.x+O,Y.p.y-O,O,h)),$.push(new $w(Y.p.x-O,Y.p.y+O,O,h)),$.push(new $w(Y.p.x+O,Y.p.y+O,O,h)),G+=4)}return u&&(console.log(`num probes: ${G}`),console.log(`best distance: ${V.d}`)),V.p}function bLe(h,l){return l.max-h.max}pR.TinySDF=class{constructor({fontSize:h=24,buffer:l=3,radius:u=8,cutoff:p=.25,fontFamily:x="sans-serif",fontWeight:b="normal",fontStyle:T="normal",lang:k=null}={}){this.buffer=l,this.cutoff=p,this.radius=u,this.lang=k;const P=this.size=h+4*l,O=this._createCanvas(P),$=this.ctx=O.getContext("2d",{willReadFrequently:!0});$.font=`${T} ${b} ${h}px ${x}`,$.textBaseline="alphabetic",$.textAlign="left",$.fillStyle="black",this.gridOuter=new Float64Array(P*P),this.gridInner=new Float64Array(P*P),this.f=new Float64Array(P),this.z=new Float64Array(P+1),this.v=new Uint16Array(P)}_createCanvas(h){const l=document.createElement("canvas");return l.width=l.height=h,l}draw(h){const{width:l,actualBoundingBoxAscent:u,actualBoundingBoxDescent:p,actualBoundingBoxLeft:x,actualBoundingBoxRight:b}=this.ctx.measureText(h),T=Math.ceil(u),k=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(b-x))),P=Math.min(this.size-this.buffer,T+Math.ceil(p)),O=k+2*this.buffer,$=P+2*this.buffer,V=Math.max(O*$,0),G=new Uint8ClampedArray(V),Y={data:G,width:O,height:$,glyphWidth:k,glyphHeight:P,glyphTop:T,glyphLeft:0,glyphAdvance:l};if(k===0||P===0)return Y;const{ctx:X,buffer:te,gridInner:se,gridOuter:ae}=this;this.lang&&(X.lang=this.lang),X.clearRect(te,te,k,P),X.fillText(h,te,te+T);const fe=X.getImageData(te,te,k,P);ae.fill(P2,0,V),se.fill(0,0,V);for(let ue=0;ue0?We*We:0,se[Ie]=We<0?We*We:0}}ree(ae,0,0,O,$,O,this.f,this.v,this.z),ree(se,te,te,k,P,O,this.f,this.v,this.z);for(let ue=0;ueb.y!=te.y>b.y&&b.x<(te.x-X.x)*(b.y-X.y)/(te.y-X.y)+X.x&&(k=!k),P=Math.min(P,sh(b,X,te))}}return(k?1:-1)*Math.sqrt(P)}(this.p,x),this.max=this.d+this.h*Math.SQRT2}}const wLe=Object.keys,V$=Number.POSITIVE_INFINITY,SLe=Math.sqrt(2);function Iy(h,l,u,p,x,b){const T=L$(h)&&h.collisionPadding?h.collisionPadding:[0,0,0,0],k={top:h.top-T[1],bottom:h.bottom+T[3],left:h.left-T[0],right:h.right+T[2],scaled:!1};return p!==void 0&&function(P,O){P.top*=O,P.bottom*=O,P.left*=O,P.right*=O,P.scaled=!0}(k,p),b&&(k.left+=b[0],k.right+=b[0],k.top+=b[1],k.bottom+=b[1]),u&&function(P,O,$){if(!O)return;const V=Xn(O),G=new Ft($?$[0]:0,$?$[1]:0),Y=new Ft(P.left,P.top),X=new Ft(P.right,P.top),te=new Ft(P.left,P.bottom),se=new Ft(P.right,P.bottom);Y._rotateAround(V,G),X._rotateAround(V,G),te._rotateAround(V,G),se._rotateAround(V,G),P.left=Math.min(Y.x,X.x,te.x,se.x),P.right=Math.max(Y.x,X.x,te.x,se.x),P.top=Math.min(Y.y,X.y,te.y,se.y),P.bottom=Math.max(Y.y,X.y,te.y,se.y)}(k,u,x),l?{top:Math.min(l.top,k.top),bottom:Math.max(l.bottom,k.bottom),left:Math.min(l.left,k.left),right:Math.max(l.right,k.right),scaled:l.scaled||k.scaled}:k}function lee(h,[l,u]){let p=0,x=0;if(u===V$){l<0&&(l=0);const b=l/SLe;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":p=-b;break;case"top-left":case"bottom-left":p=b;break;case"left":p=l;break;case"right":p=-l}}else{switch(l=Math.abs(l),u=Math.abs(u),h){case"top-right":case"top-left":case"top":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":p=-l;break;case"top-left":case"bottom-left":case"left":p=l}}return[p,x]}function TLe(h,l,u,p,x,b,T,k,P,O,$,V,G,Y,X){const te=h.layers[0],se=te.appearances;if(se.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const ae={iconBBox:null,iconVerticalBBox:null},fe={textBBox:null,textVerticalBBox:null},{baseIconRotate:ue,baseTextRotate:Te,iconScaleFactor:Ae}=function(We,ze,He){const Ve=We.get("icon-rotate").evaluate(ze,{},He),qe=We.get("text-rotate").evaluate(ze,{},He),[bt,Et]=We.get("icon-size-scale-range");return{baseIconRotate:Ve,baseTextRotate:qe,iconScaleFactor:pe(1,bt,Et)}}(p,x,b);l&&(ae.iconBBox=Iy(l,ae.iconBBox,ue),u)&&(ae.iconVerticalBBox=Iy(u,ae.iconVerticalBBox,ue+90));const Ie=_R(V.horizontal);Ie&&(fe.textBBox=Iy(Ie,fe.textBBox,Te,1,Y)),V.vertical&&(fe.textVerticalBBox=Iy(V.vertical,fe.textVerticalBBox,Te+90,1,Y));for(const We of se)We.hasIconLayoutProperties()&&jLe(ae,h,te,We,x,b,k,ue,T,P,l,O,Ae,$,X),We.hasTextLayoutProperties()&&ELe(fe,te,We,x,b,Y,Te,G,Ie,V.vertical);return{iconBBox:ae.iconBBox,iconVerticalBBox:ae.iconVerticalBBox,textBBox:fe.textBBox,textVerticalBBox:fe.textVerticalBBox}}function jLe(h,l,u,p,x,b,T,k,P,O,$,V,G,Y,X){const{appearanceIconOffset:te,appearanceIconRotate:se,appearanceIconSize:ae}=cee(p,u,x,b,T,k,P,O.iconScaleFactor);let fe=null,ue=null,Te=null;p.hasLayoutProperty("icon-image")?Te=function(Ie,We,ze,He,Ve,qe,bt,Et){let It=null;const Dt=We.getAppearanceValueAndResolveTokens(ze,"icon-image",He,Ve,Et);if(Dt){const Pt=Ie.getResolvedImageFromTokens(Dt),Ht=ze.hasLayoutProperty("icon-size")?ze.getUnevaluatedLayoutProperty("icon-size"):We._unevaluatedLayout._values["icon-size"],vt=R2(Pt,Lv(Ie.zoom,Ht,Ie.worldview,Et),Ht,Ve,Ie.zoom,He,Ie.pixelRatio,bt,Ie.worldview,Et);It=qe.get(vt.iconPrimary.toString())}return It}(l,u,p,x,b,V,G,X):$&&(Te=$.imagePrimary),Te&&(fe=fR(Te,null,te,Y),l.allowVerticalPlacement&&(ue=fR(Te,null,te,Y)));const Ae=P>0?ae/P:1;fe&&(h.iconBBox=Iy(fe,h.iconBBox,se,Ae!==1?Ae:void 0)),ue&&(h.iconVerticalBBox=Iy(ue,h.iconVerticalBBox,se+90,Ae!==1?Ae:void 0))}function cee(h,l,u,p,x,b,T,k){const P=h.hasLayoutProperty("icon-offset")?l.getAppearanceValueAndResolveTokens(h,"icon-offset",u,p,[]):null,O=P&&Array.isArray(P)?P:x,$=h.hasLayoutProperty("icon-rotate")?l.getAppearanceValueAndResolveTokens(h,"icon-rotate",u,p,[]):null,V=typeof $=="number"?$:b,G=h.hasLayoutProperty("icon-size")?l.getAppearanceValueAndResolveTokens(h,"icon-size",u,p,[]):null;return{appearanceIconOffset:O,appearanceIconRotate:V,appearanceIconSize:typeof G=="number"?G*k:T}}function ELe(h,l,u,p,x,b,T,k,P,O){const{appearanceTextOffset:$,appearanceTextRotate:V,appearanceTextSize:G}=uee(u,l,p,x,b,T,k),Y=G/k,X=[($[0]-b[0])*Y,($[1]-b[1])*Y],te=X[0]!==0||X[1]!==0;P&&(h.textBBox=Iy(P,h.textBBox,V,Y,$,te?X:void 0)),O&&(h.textVerticalBBox=Iy(O,h.textVerticalBBox,V+90,Y,$,te?X:void 0))}function uee(h,l,u,p,x,b,T){const k=h.hasLayoutProperty("text-offset")?l.getAppearanceValueAndResolveTokens(h,"text-offset",u,p,[]):null,P=k&&Array.isArray(k)?[k[0]*Za,k[1]*Za]:x,O=h.hasLayoutProperty("text-rotate")?l.getAppearanceValueAndResolveTokens(h,"text-rotate",u,p,[]):null,$=typeof O=="number"?O:b,V=h.hasLayoutProperty("text-size")?l.getAppearanceValueAndResolveTokens(h,"text-size",u,p,[]):null;return{appearanceTextOffset:P,appearanceTextRotate:$,appearanceTextSize:typeof V=="number"?V:T}}function vR(h,l,u,p,x,b,T,k,P){if(!l||!l.usvg)return;const O=HJ(p),$=HJ(x),V=b!=="both"&&b!=="width"||!qJ(p)?1:$.width/O.width,G=b!=="both"&&b!=="height"||!GJ(p)?1:$.height/O.height;u.scaleSelf(V,G);const Y=u.toString();T.set(Y,u),k.set(Y,l);const{imagePosition:X}=B$(Y,l,1);P.set(Y,X)}function dee(h,l,u,p,x,b,T,k,P,O){if(!h)return;const $=function(V,G,Y,X,te,se,ae){if(V.kind==="camera")return V.maxSize;if(V.kind==="composite"){const fe=G.possiblyEvaluate(new fs(V.maxZoom,{worldview:se}),Y,ae).evaluate(te,{},Y,ae),ue=G.possiblyEvaluate(new fs(V.minZoom,{worldview:se}),Y,ae).evaluate(te,{},Y,ae);return Math.max(fe,ue)}return G.possiblyEvaluate(new fs(X,{worldview:se}),Y,ae).evaluate(te,{},Y,ae)}(l,u,p,x,b,P,O);return h.scaleSelf($*k*T)}function R2(h,l,u,p,x,b,T,k,P,O){return{iconPrimary:dee(h.getPrimary(),l,u,p,x,b,T,k,P,O),iconSecondary:dee(h.getSecondary(),l,u,p,x,b,T,k,P,O)}}function kLe(h,l,u){if(!l)return;const p=u.get(h.toString()),x=u.get(l.toString());p&&x&&(p.paddedRect.w===x.paddedRect.w&&p.paddedRect.h===x.paddedRect.h||hr(`Mismatch in icon variant sizes: ${h.toString()} and ${l.toString()}`),p.usvg!==x.usvg&&hr(`Mismatch in icon variant image types: ${h.id} and ${l.id}`))}function hee(h,l,u,p){if(!h)return;const x=l.get(u.toString());if(x&&(h.imagePrimary=x),p){const b=l.get(p.toString());h.imageSecondary=b}}function ALe(h,l){for(const u in h.horizontal)fee(h.horizontal[u],l);fee(h.vertical,l)}function fee(h,l){if(h){for(const u of h.positionedLines)for(const p of u.positionedGlyphs)if(p.image!==null){const x=p.image.toString();p.rect=l.get(x).paddedRect}}}function q$(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 NLe(h,l,u,p,x,b,T,k,P){const O=_R(b.horizontal)||b.vertical,$=u.get("icon-text-fit-padding").evaluate(p,{},x);let V,G=l;return l&&P!=="none"&&(h.allowVerticalPlacement&&b.vertical&&(V=M$(l,b.vertical,P,$,k,T)),O&&(G=M$(l,O,P,$,k,T))),{defaultShapedIcon:G,verticallyShapedIcon:V}}function mee(h,l){return h*l/24}function CLe(h,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe,ue,Te,Ae,Ie,We){let ze=T.textMaxSize.evaluate(l,{},G);ze===void 0?ze=k*T.textScaleFactor:ze*=T.textScaleFactor;const He=h.layers[0].layout,Ve=mee(k,T.textScaleFactor),qe=_R(u.horizontal)||u.vertical,bt=h.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Et=h.getAppearanceFeatureData(l.index);(se!=="none"||bt)&&Et&&(Et.textShaping=qe,Et.iconTextFitPadding=He.get("icon-text-fit-padding").evaluate(l,{},G),Et.fontScale=Ve,Et.textScaleFactor=T.textScaleFactor);const It=Y.name==="globe",Dt=h.tilePixelRatio*ze/24,Pt=(tr=h.overscaling,h.zoom>18&&tr>2&&(tr>>=1),Math.max(fr/(512*tr),1)*He.get("symbol-spacing")),Ht=He.get("text-padding")*h.tilePixelRatio,vt=He.get("icon-padding")*h.tilePixelRatio,Rt=Xn(He.get("text-max-angle")),Bt=He.get("icon-rotation-alignment")==="map"&&ue!=="point",Yt=Pt/2;var tr;h.hasAnyIconTextFit===!1&&se!=="none"&&(h.hasAnyIconTextFit=!0);const wr=l.properties?+l.properties[bn]:null,ur=wr&&h.elevationFeatureIdToIndex?h.elevationFeatureIdToIndex.get(wr):65535,cr=(rr,_r,Rr)=>{if(_r.x<0||_r.x>=fr||_r.y<0||_r.y>=fr)return;let Wr=null;if(It){const{x:Dr,y:fn,z:Wn}=Y.projectTilePoint(_r.x,_r.y,Rr);Wr={anchor:new Gp(Dr,fn,Wn,0,void 0),up:Y.upVector(Rr,_r.x,_r.y)}}(function(Dr,fn,Wn,mn,es,En,ji,ms,ns,$s,vi,Xa,_i,Ri,aa,Li,Oo,Qa,An,Ol,Gi,oo,Fl,Fo,Ei,gl,lo,FR,Kw,Jl,mz,Yw){const Hp=Dr.addToLineVertexArray(fn,mn);let Wp,yd,xd,$v,Zw,Rn,co,Mi=0,Ba=0,vd=0,nu=0,su=-1,iu=-1;const oh={};let BR=Kf("");const rf=Wn?Wn.anchor:fn,Xw=FR!=="none";let Qw=0,Ta=0;if(ns._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Hi=ns.layout.get("text-offset").evaluate(Gi,{},Ei);Qw=Hi[0]*Za,Ta=Hi[1]*Za}else Qw=ns.layout.get("text-radial-offset").evaluate(Gi,{},Ei)*Za,Ta=V$;if(Dr.allowVerticalPlacement&&es.vertical){const Hi=es.vertical;if(aa)Rn=W$(Hi),ms&&(co=W$(ms));else{const Bl=ns.layout.get("text-rotate").evaluate(Gi,{},Ei)+90;xd=bR($s,rf,fn,vi,Xa,_i,Hi,Ri,Bl,Li,Yw),ms&&($v=bR($s,rf,fn,vi,Xa,_i,ms,Qa,Bl,null,mz))}}if(En){const Hi=ns.layout.get("icon-rotate").evaluate(Gi,{},Ei),Bl=U$(En,Hi,Fl,Xw,oo.iconScaleFactor),ec=ms?U$(ms,Hi,Fl,Xw,oo.iconScaleFactor):void 0;yd=bR($s,rf,fn,vi,Xa,_i,En,Qa,Hi,null,Jl);const ch=function(nf,K2,Jw,GMe,HMe,Mte,Dte,WMe,SJt,gz){const Ote=nf.layers[0],Fte=Ote.appearances;let e1=K2.length;if(Jw&&(e1=Math.max(e1,Jw.length)),Fte.length===0)return e1;const[KMe,YMe]=GMe.get("icon-size-scale-range"),ZMe=pe(1,KMe,YMe);for(const VR of Fte)if(VR.hasLayoutProperty("icon-image")){const Bte=Ote.getAppearanceValueAndResolveTokens(VR,"icon-image",Mte,Dte,gz);if(Bte){const $te=nf.getResolvedImageFromTokens(Bte);if($te){const zte=VR.hasLayoutProperty("icon-size")?VR.getUnevaluatedLayoutProperty("icon-size"):HMe._values["icon-size"],XMe=R2($te,Lv(nf.zoom,zte,nf.worldview,gz),zte,Dte,nf.zoom,Mte,nf.pixelRatio,ZMe,nf.worldview,gz),Ute=WMe.get(XMe.iconPrimary.toString());Ute&&(e1=Math.max(e1,xLe(Ute)))}}}return e1}(Dr,Bl,ec,ns.layout,ns._unevaluatedLayout,Gi,Ei,Dr.iconAtlasPositions,0,Fo);Mi=4*ch;const $R=ns.layout.get("icon-size").evaluate(Gi,{},Ei,Fo),zR=oo.compositeIconSizes?oo.compositeIconSizes[0].evaluate(Gi,{},Ei,Fo):0,pz=oo.compositeIconSizes?oo.compositeIconSizes[1].evaluate(Gi,{},Ei,Fo):0,UR=H$(Dr.layerIds[0],Dr.iconSizeData,$R,oo.iconScaleFactor,zR,pz);Dr.addSymbols(Dr.icon,Bl,UR,Ol,An,Gi,void 0,Wn,fn,Hp.lineStartIndex,Hp.lineLength,-1,Fo,Ei,gl,lo,Dr.symbolInstances.length,ch),su=Dr.icon.placedSymbolArray.length-1,ec&&(Ba=4*ch,Dr.addSymbols(Dr.icon,ec,UR,Ol,An,Gi,ru.vertical,Wn,fn,Hp.lineStartIndex,Hp.lineLength,-1,Fo,Ei,gl,lo,Dr.symbolInstances.length,ch),iu=Dr.icon.placedSymbolArray.length-1)}for(const Hi in es.horizontal){const Bl=Hi,ec=es.horizontal[Bl];Wp||(BR=Kf(ec.text),aa?Zw=W$(ec):Wp=bR($s,rf,fn,vi,Xa,_i,ec,Ri,ns.layout.get("text-rotate").evaluate(Gi,{},Ei),Li,Yw));const ch=ec.positionedLines.length===1;if(vd+=pee(Dr,Wn,fn,ec,ji,ns,aa,Gi,Li,Hp,es.vertical?ru.horizontal:ru.horizontalOnly,ch?wLe(es.horizontal):[Bl],oh,su,oo,Fo,Ei,Dr.symbolInstances.length,gl),ch)break}es.vertical&&(nu+=pee(Dr,Wn,fn,es.vertical,ji,ns,aa,Gi,Li,Hp,ru.vertical,["vertical"],oh,iu,oo,Fo,Ei,Dr.symbolInstances.length,gl));let fa=-1;const $a=(Hi,Bl)=>Hi?Math.max(Hi,Bl):Bl;fa=$a(Zw,fa),fa=$a(Rn,fa),fa=$a(co,fa);const lh=fa>-1?1:0;Dr.glyphOffsetArray.length>=65535&&hr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Gi.sortKey!==void 0&&Dr.addToSortKeyRanges(Dr.symbolInstances.length,Gi.sortKey),Dr.symbolInstances.emplaceBack(fn.x,fn.y,rf.x,rf.y,rf.z,oh.right>=0?oh.right:-1,oh.center>=0?oh.center:-1,oh.left>=0?oh.left:-1,oh.vertical>=0?oh.vertical:-1,su,iu,BR,Wp!==void 0?Wp:Dr.collisionBoxArray.length,Wp!==void 0?Wp+1:Dr.collisionBoxArray.length,xd!==void 0?xd:Dr.collisionBoxArray.length,xd!==void 0?xd+1:Dr.collisionBoxArray.length,yd!==void 0?yd:Dr.collisionBoxArray.length,yd!==void 0?yd+1:Dr.collisionBoxArray.length,$v||Dr.collisionBoxArray.length,$v?$v+1:Dr.collisionBoxArray.length,vi,vd,nu,Mi,Ba,lh,0,Qw,Ta,fa,0,Xw?1:0,Kw)})(h,_r,Wr,rr,u,p,b,x,h.layers[0],h.collisionBoxArray,l.index,l.sourceLayerIndex,h.index,Ht,fe,O,0,vt,Bt,ae,l,T,$,V,G,X,te,se,ur,Te,Ae,Ie)};if(ue==="line")for(const rr of eR(l.geometry,0,0,fr,fr)){const _r=yLe(rr,Pt,Rt,u.vertical||qe,p,24,Dt,h.overscaling,fr);for(const Rr of _r)qe&&ILe(h,qe.text,Yt,Rr)||cr(rr,Rr,G)}else if(ue==="line-center"){for(const rr of l.geometry)if(rr.length>1){const _r=gLe(rr,Rt,u.vertical||qe,p,24,Dt);_r&&cr(rr,_r,G)}}else if(l.type==="Polygon")for(const rr of p2(l.geometry,0)){const _r=_Le(rr,16);cr(rr[0],new Gp(_r.x,_r.y,0,0,void 0),G)}else if(l.type==="LineString")for(const rr of l.geometry)cr(rr,new Gp(rr[0].x,rr[0].y,0,0,void 0),G);else if(l.type==="Point")for(const rr of l.geometry)for(const _r of rr)cr([_r],new Gp(_r.x,_r.y,0,0,void 0),G)}const G$=255,Mv=G$*qp;function pee(h,l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe){const ue=oee(0,p,P,b,T,k,x,h.allowVerticalPlacement,void 0,X.textScaleFactor),Te=b.layout.get("text-size").evaluate(k,{},se),Ae=X.compositeTextSizes?X.compositeTextSizes[0].evaluate(k,{},se):0,Ie=X.compositeTextSizes?X.compositeTextSizes[1].evaluate(k,{},se):0,We=H$(h.layerIds[0],h.textSizeData,Te,X.textScaleFactor,Ae,Ie);h.addSymbols(h.text,ue,We,P,T,k,$,l,u,O.lineStartIndex,O.lineLength,Y,te,se,fe,!1,ae,ue.length);for(const ze of V)G[ze]=h.text.placedSymbolArray.length-1;return 4*ue.length}function H$(h,l,u,p,x,b){const T=l;let k=null;return T.kind==="source"?(k=[qp*u*p],k[0]>Mv&&hr(`${h}: Value for "text-size" is >= ${G$}. Reduce your "text-size".`)):T.kind==="composite"&&(k=[qp*x*p,qp*b*p],(k[0]>Mv||k[1]>Mv)&&hr(`${h}: Value for "text-size" is >= ${G$}. Reduce your "text-size".`)),k}function _R(h){for(const l in h)return h[l];return null}function bR(h,l,u,p,x,b,T,k,P,O,$){let V,G,Y,X;if(V=$?$.top:T.top,G=$?$.bottom:T.bottom,Y=$?$.left:T.left,X=$?$.right:T.right,L$(T)&&T.collisionPadding){const te=T.collisionPadding;Y-=te[0],V-=te[1],X+=te[2],G+=te[3]}if(P){const te=new Ft(Y,V),se=new Ft(X,V),ae=new Ft(Y,G),fe=new Ft(X,G),ue=Xn(P);let Te=new Ft(0,0);O&&(Te=new Ft(O[0],O[1])),te._rotateAround(ue,Te),se._rotateAround(ue,Te),ae._rotateAround(ue,Te),fe._rotateAround(ue,Te),Y=Math.min(te.x,se.x,ae.x,fe.x),X=Math.max(te.x,se.x,ae.x,fe.x),V=Math.min(te.y,se.y,ae.y,fe.y),G=Math.max(te.y,se.y,ae.y,fe.y)}return h.emplaceBack(l.x,l.y,l.z,u.x,u.y,Y,V,X,G,k,p,x,b),h.length-1}function W$(h){L$(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 ILe(h,l,u,p){const x=h.compareText;if(l in x){const b=x[l];for(let T=b.length-1;T>=0;T--)if(p.dist(b[T])ue&&(Te(Ie,It,ze,He,bt,Et),Te(It,We,bt,Et,Ve,qe))}Te(V,G,p,b,x,b),Te(G,Y,x,b,x,T),Te(Y,X,x,T,p,T),Te(X,V,p,T,p,b),te-=ue,se-=ue,ae+=ue,fe+=ue;const Ae=1/Math.max(ae-te,fe-se);return{scale:Ae,x:te*Ae,y:se*Ae,x2:ae*Ae,y2:fe*Ae,projection:l}}function yee(h,{x:l,y:u},p=0){return new Ft(((l-p)*h.scale-h.x)*fr,(u*h.scale-h.y)*fr)}const PLe=I(new Float32Array(16));class Py{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 Je(0,0)}projectTilePoint(l,u,p){return{x:l,y:u,z:0}}locationPoint(l,u,p,x=!0){return l._coordinatePoint(l.locationCoordinate(u,p),x)}pixelsPerMeter(l,u){return ut(1,l)*u}pixelSpaceConversion(l,u,p){return 1}farthestPixelDistance(l){return gee(l,l.pixelsPerMeter)}pointCoordinate(l,u,p,x){const b=l.horizonLineFromTop(!1),T=new Ft(u,Math.max(b,p));return l.rayIntersectionCoordinate(l.pointRayIntersection(T,x))}pointCoordinate3D(l,u,p){const x=new Ft(u,p);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 p=l.horizonLineFromTop();return u.y0?u<-zw+p&&(u=-zw+p):u>zw-p&&(u=zw-p);const T=b/Math.pow(SR(u),x);let k=T*Math.sin(x*l),P=b-T*Math.cos(x*l);return k=.5*(k/Math.PI+.5),P=.5*(P/Math.PI+.5),{x:k,y:this.southernCenter?P:1-P,z:0}}unproject(l,u){l=(2*l-.5)*Math.PI,this.southernCenter&&(u=1-u),u=(2*(1-u)-.5)*Math.PI;const{n:p,f:x}=this,b=x-u,T=Math.sign(b),k=Math.sign(p)*Math.sqrt(l*l+b*b);let P=Math.atan2(l,Math.abs(b))*T;b*p<0&&(P-=Math.PI*Math.sign(l)*T);const O=pe(Da(P/p)+this.center[0],-180,180),$=pe(Da(2*Math.atan(Math.pow(x/k,1/p))-zw),-85.051129,Nt);return new Je(O,this.southernCenter?-$:$)}}class xee extends Py{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:Ot(l),y:Ut(u),z:0}}unproject(l,u){const p=st(l),x=_t(u);return new Je(p,x)}}const vee=Xn(Nt);class OLe extends Py{project(l,u){const p=(u=Xn(u))*u,x=p*p;return{x:.5*((l=Xn(l))*(.8707-.131979*p+x*(x*(.003971*p-.001529*x)-.013791))/Math.PI+.5),y:1-.5*(u*(1.007226+p*(.015085+x*(.028874*p-.044475-.005916*x)))/Math.PI+1),z:0}}unproject(l,u){l=(2*l-.5)*Math.PI;let p=u=(2*(1-u)-1)*Math.PI,x=25,b=0,T=p*p;do{T=p*p;const O=T*T;b=(p*(1.007226+T*(.015085+O*(.028874*T-.044475-.005916*O)))-u)/(1.007226+T*(.045255+O*(.259866*T-.311325-.005916*11*O))),p=pe(p-b,-vee,vee)}while(Math.abs(b)>1e-6&&--x>0);T=p*p;const k=pe(Da(l/(.8707+T*(T*(T*T*T*(.003971-.001529*T)-.013791)-.131979))),-180,180),P=Da(p);return new Je(k,P)}}const _ee=Xn(Nt);class FLe extends Py{project(l,u){u=Xn(u),l=Xn(l);const p=Math.cos(u),x=2/Math.PI,b=Math.acos(p*Math.cos(l/2)),T=Math.sin(b)/b,k=.5*(l*x+2*p*Math.sin(l/2)/T)||0,P=.5*(u+Math.sin(u)/T)||0;return{x:.5*(k/Math.PI+.5),y:1-.5*(P/Math.PI+1),z:0}}unproject(l,u){let p=l=(2*l-.5)*Math.PI,x=u=(2*(1-u)-1)*Math.PI,b=25;const T=1e-6;let k=0,P=0;do{const O=Math.cos(x),$=Math.sin(x),V=2*$*O,G=$*$,Y=O*O,X=Math.cos(p/2),te=Math.sin(p/2),se=2*X*te,ae=te*te,fe=1-Y*X*X,ue=fe?1/fe:0,Te=fe?Math.acos(O*X)*Math.sqrt(1/fe):0,Ae=.5*(2*Te*O*te+2*p/Math.PI)-l,Ie=.5*(Te*$+x)-u,We=.5*ue*(Y*ae+Te*O*X*G)+1/Math.PI,ze=ue*(se*V/4-Te*$*te),He=.125*ue*(V*te-Te*$*Y*se),Ve=.5*ue*(G*X+Te*ae*O)+.5,qe=ze*He-Ve*We;k=(Ie*ze-Ae*Ve)/qe,P=(Ae*He-Ie*We)/qe,p=pe(p-k,-Math.PI,Math.PI),x=pe(x-P,-_ee,_ee)}while((Math.abs(k)>T||Math.abs(P)>T)&&--b>0);return new Je(Da(p),Da(x))}}class bee extends Py{constructor(l){super(l),this.center=l.center||[0,0],this.parallels=l.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Xn(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(l,u){const{scale:p,cosPhi:x}=this;return{x:Xn(l)*x*p+.5,y:-Math.sin(Xn(u))/x*p+.5,z:0}}unproject(l,u){const{scale:p,cosPhi:x}=this,b=-(u-.5)/p,T=pe(Da((l-.5)/p)/x,-180,180),k=Math.asin(pe(b*x,-1,1)),P=pe(Da(k),-85.051129,Nt);return new Je(T,P)}}class BLe extends xee{constructor(l){super(l),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(l,u,p){const x=l2(l,u,p);return or(x,x,c2(lm(p))),{x:x[0],y:x[1],z:x[2]}}locationPoint(l,u,p){const x=Be(u.lat,u.lng),b=ft([],x),T=p?l._centerAltitude+p:l.elevation?l.elevation.getAtPointOrZero(l.locationCoordinate(u),l._centerAltitude):l._centerAltitude;Ze(x,x,b,ut(1,0)*fr*T);const k=I(new Float64Array(16));return D(k,l.pixelMatrix,l.globeMatrix),or(x,x,k),new Ft(x[0],x[1])}pixelsPerMeter(l,u){return ut(1,0)*u}pixelSpaceConversion(l,u,p){const x=ut(1,l)*u,b=sn(ut(1,45)*u,x,p);return this.pixelsPerMeter(l,u)/b}createTileMatrix(l,u,p){const x=zB(lm(p.canonical));return D(new Float64Array(16),l.globeMatrix,x)}createInversionMatrix(l,u){const{center:p}=l,x=c2(lm(u));return H(x,x,Xn(p.lng)),q(x,x,Xn(p.lat)),z(x,x,[l._pixelsPerMercatorPixel,l._pixelsPerMercatorPixel,1]),Float32Array.from(x)}pointCoordinate(l,u,p,x){return OX(l,u,p,!0)||new Pr(0,0)}pointCoordinate3D(l,u,p){const x=this.pointCoordinate(l,u,p,0);return[x.x,x.y,x.z]}isPointAboveHorizon(l,u){return!OX(l,u.x,u.y,!1)}farthestPixelDistance(l){const u=function(x,b){const T=x.cameraToCenterDistance,k=x._centerAltitude*b,P=x._camera,O=x._camera.forward(),$=me([],Ue([],O,-T),[0,0,k]),V=x.worldSize/(2*Math.PI),G=[0,0,-V],Y=x.width/x.height,X=Math.tan(x.fovAboveCenter),te=Ue([],P.up(),X),se=Ue([],P.right(),X*Y),ae=ft([],me([],me([],O,te),se)),fe=[];let ue;if(new Mn($,ae).closestPointOnSphere(G,V,fe)){const Te=me([],fe,G),Ae=qr([],Te,$);ue=Math.cos(x.fovAboveCenter)*Le(Ae)}else{const Te=qr([],$,G),Ae=qr([],G,$);ft(Ae,Ae);const Ie=Le(Te)-V;ue=Math.sqrt(Ie*(Ie+2*V));const We=Math.acos(ue/(V+Ie))-Math.acos(kt(O,Ae));ue*=Math.cos(We)}return 1.01*ue}(l,this.pixelsPerMeter(l.center.lat,l.worldSize)),p=zp(l.zoom);if(p>0){const x=gee(l,ut(1,l.center.lat)*l.worldSize),b=l.worldSize/(2*Math.PI),T=Math.max(l.width,l.height)/l.worldSize*Math.PI;return sn(u,x+b*(1-Math.cos(T)),Math.pow(p,10))}return u}upVector(l,u,p){return l2(u,p,l,1)}upVectorScale(l){return{metersToTile:DP(FP(lm(l)))}}}function wee(h){const l=h.parallels,u=!!l&&Math.abs(l[0]+l[1])<.01;switch(h.name){case"mercator":return new xee(h);case"equirectangular":return new MLe(h);case"naturalEarth":return new OLe(h);case"equalEarth":return new LLe(h);case"winkelTripel":return new FLe(h);case"albers":return u?new bee(h):new RLe(h);case"lambertConformalConic":return u?new bee(h):new DLe(h);case"globe":return new BLe(h)}throw new Error(`Invalid projection name: ${h.name}`)}class $Le{constructor(l,u){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=u,this.appearances=l;const p=l.map(x=>function(b){if(!b.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const T=b.condition.expression;return{featureDependent:!kp(T),stateDependent:!dy(T),zoomDependent:!Qd(T,["zoom"]),pitchDependent:!Qd(T,["pitch"]),brightnessDependent:!Qd(T,["brightness","measure-light"]),worldviewDependent:!Qd(T,["worldview"])}}(x));this.anyFeatureDependent=p.some(x=>x.featureDependent),this.anyStateDependent=p.some(x=>x.stateDependent)}update(l,u){const p=this.lastParams,x=!p||p.zoom!==l.zoom||p.pitch!==(l.pitch||0)||p.brightness!==(l.brightness||0)||p.worldview!==l.worldview;this.lastParams={zoom:l.zoom,pitch:l.pitch||0,brightness:l.brightness||0,worldview:l.worldview};const b=u&&this.anyStateDependent;if(!x&&!b&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!b){const T=this.evaluateAllFeatures(l);return T===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=T,{kind:"all-features",appearanceIndex:T})}return{kind:"per-feature"}}evaluateAllFeatures(l){for(let u=0;u{for(let x=0;xT-k),b=new Map;for(const T of x){const k=p.get(T);b.set(T,new Os(k))}return u&&(this.cachedBatchIndices=x,this.cachedBatchSegments=b),{batchIndices:x,batchSegments:b}}snapshotSymbolVertexData(l,u){const p=l*Vw;return this.layoutVertexArray.uint16.slice(p,p+u*Vw)}restoreSymbolVertexData(l,u){this.layoutVertexArray.uint16.set(u,l*Vw)}updateSymbolVertexData(l,u,p,x,b,T,k,P,O,$,V,G,Y){const X=this.layoutVertexArray.uint16,te=l*Vw;X[te]=u,X[te+1]=p,X[te+2]=x,X[te+3]=b,X[te+4]=T,X[te+5]=k,X[te+6]=P,X[te+7]=O,X[te+8]=$,X[te+9]=V,X[te+10]=G,X[te+11]=Y}upload(l,u,p,x,b,T){this.isEmpty()||(p&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,VRe.members,!!T),this.indexBuffer=l.createIndexBuffer(this.indexArray,u),this.dynamicLayoutVertexBuffer=l.createVertexBuffer(this.dynamicLayoutVertexArray,GRe.members,!0),this.opacityVertexBuffer=l.createVertexBuffer(this.opacityVertexArray,ULe,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=l.createVertexBuffer(this.iconTransitioningVertexArray,YRe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,qRe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,HRe.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=l.createVertexBuffer(this.orientationVertexArray,KRe.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=l.createVertexBuffer(this.featureIdArray,WRe.members,!1))),(p||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())}}jr(K$,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class Y${constructor(l,u,p){this.layoutVertexArray=new l,this.layoutAttributes=u,this.indexArray=new p,this.segments=new Os,this.collisionVertexArray=new bv,this.collisionVertexArrayExt=new Yh}upload(l){this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=l.createVertexBuffer(this.collisionVertexArray,ZRe.members,!0),this.collisionVertexBufferExt=l.createVertexBuffer(this.collisionVertexArrayExt,XRe.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}jr(Y$,"CollisionBuffers");class Jh{constructor(l){this.collisionBoxArray=l.collisionBoxArray,this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(T=>T.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=I([]),this.placementViewportMatrix=I([]);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=Lv(this.zoom,u["text-size"],this.worldview,l.availableImages),this.iconSizeData=Lv(this.zoom,u["icon-size"],this.worldview,l.availableImages);const p=this.layers[0].layout,x=p.get("symbol-sort-key"),b=p.get("symbol-z-order");this.lut=l.lut,this.canOverlap=p.get("text-allow-overlap")||p.get("icon-allow-overlap")||p.get("text-ignore-placement")||p.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&x.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=p.get("text-writing-mode").map(T=>ru[T]),this.stateDependentLayerIds=this.layers.filter(T=>T.isStateDependent()).map(T=>T.id),this.sourceID=l.sourceID,this.projection=l.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(l){const u=this.layers[0].getAppearances();if(!u||u.length===0)return!1;const p=Array.isArray(l)?l:[l];return u.some(x=>p.some(b=>x.hasLayoutProperty(b)))}getAppearanceFeatureData(l){return this.featureAppearanceData.get(l)}createArrays(){this.text=new K$(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("text")||l.startsWith("symbol"))),this.icon=new K$(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("icon")||l.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new C$(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new C$(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new CP,this.lineVertexArray=new Tv,this.symbolInstances=new NP}calculateGlyphDependencies(l,u,p,x,b){for(const T of l){const k=T.codePointAt(0);if(k===void 0)break;if(u[k]=!0,x&&b&&k<=65535){const P=A2[T];P&&(u[P.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(l,u,p,x,b,T,k){if(!l.hasLayoutProperty("icon-size"))return k*T;let P=1;const O=l.getUnevaluatedLayoutProperty("icon-size"),$=Lv(this.zoom,O,this.worldview,b),V=Bw($,u);if($.kind!=="constant"&&$.kind!=="camera"||(P=V.uSize),$.kind==="composite"){const{minZoom:G,maxZoom:Y}=$,X=O.possiblyEvaluate(new fs(G,{worldview:this.worldview}),x),te=O.possiblyEvaluate(new fs(Y,{worldview:this.worldview}),x),se=X.evaluate(p,{},x,b);P=se+(te.evaluate(p,{},x,b)-se)*V.uSizeT}return $.kind==="source"&&(P=O.possiblyEvaluate(new fs(this.zoom,{worldview:this.worldview}),x).evaluate(p,{},x,b)),P*T}updateFootprints(l,u){}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const p=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);return!KP(this.activeReplacements,p)&&(this.activeReplacements=p,!0)}getResolvedImageFromTokens(l){return typeof l=="string"?Xl.build(l):l}populate(l,u,p,x){const b=this.layers[0],T=b.layout,k=this.projection.name==="globe",P=T.get("text-font"),O=T.get("text-field"),$=T.get("icon-image"),[V,G]=T.get("icon-size-scale-range"),Y=pe(u.scaleFactor||1,V,G),[X,te]=T.get("text-size-scale-range"),se=pe(u.scaleFactor||1,X,te),ae=(O.value.kind!=="constant"||O.value.value instanceof Zo&&!O.value.value.isEmpty()||O.value.value.toString().length>0)&&(P.value.kind!=="constant"||P.value.value.length>0),fe=$.value.kind!=="constant"||!!$.value.value||Object.keys($.parameters).length>0,ue=this.hasAnyAppearanceLayoutProperty("icon-image"),Te=T.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!ae&&!fe&&!ue)return;const Ae=u.iconDependencies,Ie=u.glyphDependencies,We=u.availableImages,ze=new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),He=Ve=>{const qe=Ve.id.toString();Ae.has(qe)?Ae.get(qe).push(Ve):Ae.set(qe,[Ve])};for(const Ve of l){const{feature:qe,id:bt,index:Et,sourceLayerIndex:It}=Ve,Dt=b._featureFilter.needGeometry,Pt=jn(qe,Dt);if(!b._featureFilter.filter(ze,Pt,p))continue;if(Dt||(Pt.geometry=Kr(qe,p,x)),k&&qe.type!==1&&p.z<=5){const ur=Pt.geometry,cr=.98078528056,rr=(_r,Rr)=>kt(l2(_r.x,_r.y,p,1),l2(Rr.x,Rr.y,p,1)){if(!ur.getLayoutProperty("icon-image"))return;const cr=this.getCombinedIconPrimary(ur,Rt,Pt,p,We,tr,Y);cr&&He(cr)}),Ht){const ur=P.evaluate(Pt,{},p).join(","),cr=T.get("text-rotation-alignment")==="map"&&T.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(ru.vertical)>=0;for(const rr of Ht.sections)if(rr.image){const _r=rr.image.getPrimary().scaleSelf(this.pixelRatio*se),Rr=_r.id.toString(),Wr=Ae.get(Rr)||[];Wr.push(_r),Ae.set(Rr,Wr)}else{const _r=CE(Ht.toString()),Rr=rr.fontStack||ur,Wr=Ie[Rr]=Ie[Rr]||{};this.calculateGlyphDependencies(rr.text,Wr,cr,this.allowVerticalPlacement,_r)}}}if(T.get("symbol-placement")==="line"&&(this.features=function(Ve){const qe={},bt={},Et=[];let It=0;function Dt(Rt){Et.push(Ve[Rt]),It++}function Pt(Rt,Bt,Yt){const tr=bt[Rt];return delete bt[Rt],bt[Bt]=tr,Et[tr].geometry[0].pop(),Et[tr].geometry[0]=Et[tr].geometry[0].concat(Yt[0]),tr}function Ht(Rt,Bt,Yt){const tr=qe[Bt];return delete qe[Bt],qe[Rt]=tr,Et[tr].geometry[0].shift(),Et[tr].geometry[0]=Yt[0].concat(Et[tr].geometry[0]),tr}function vt(Rt,Bt,Yt){const tr=Yt?Bt[0][Bt[0].length-1]:Bt[0][0];return`${Rt}:${tr.x}:${tr.y}`}for(let Rt=0;RtRt.geometry)}(this.features)),T.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 Ve of u.elevationFeatures)this.elevationFeatureIdToIndex.set(Ve.id,this.elevationFeatures.length),this.elevationFeatures.push(Ve)}}else T.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Ve,qe)=>Ve.sortKey-qe.sortKey)}getCombinedIconPrimary(l,u,p,x,b,T,k){let P,O;if(l.hasLayoutProperty("icon-image")){const $=u.getAppearanceValueAndResolveTokens(l,"icon-image",p,x,b);P=this.getResolvedImageFromTokens($)}else{const $=u.getValueAndResolveTokens("icon-image",p,x,b);P=this.getResolvedImageFromTokens($)}if(P){const $=l.hasLayoutProperty("icon-size")?l.getUnevaluatedLayoutProperty("icon-size"):u._unevaluatedLayout._values["icon-size"];O=R2(P,Lv(this.zoom,$,this.worldview,b),$,x,this.zoom,T,this.pixelRatio,k,this.worldview,b).iconPrimary}return O}updateSymbolInstanceIconVertices(l,u,p,x,b,T){const{canonical:k,availableImages:P,globalProperties:O,layer:$,iconScaleFactor:V,featureState:G,layoutIconOffset:Y,layoutIconSize:X,layoutIconRotate:te}=T;if(l.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(u.activeAppearanceIndex===p)return{vertexOffsetDelta:l.numIconVertices,hasChanges:!1};const se=p>=0?$.appearances[p]:null;if(se){const ae=this.getCombinedIconPrimary(se,$,x,k,P,{sortKey:void 0,text:void 0,icon:null,index:l.featureIndex,sourceLayerIndex:l.featureIndex,geometry:[],properties:u.properties,type:"Point",id:u.id},V);if(!ae)return{vertexOffsetDelta:0,hasChanges:!1};const fe=ae.toString(),ue=this.iconAtlasPositions&&this.iconAtlasPositions.get(fe);if(ue){const{appearanceIconOffset:Te,appearanceIconRotate:Ae}=cee(se,$,x,k,Y,te,X,V);let Ie=fR(ue,void 0,Te,$.layout.get("icon-anchor").evaluate(x,G,k));const We=ue.sdf,ze=$.layout.get("icon-text-fit").constantOr("none");ze!=="none"&&u.textShaping&&u.iconTextFitPadding&&u.fontScale&&(Ie=M$(Ie,u.textShaping,ze,u.iconTextFitPadding,Te,u.fontScale));const He=this.calculateEffectiveAppearanceIconSize(se,O.zoom,x,k,P,V,X),Ve=0,qe=1+(Math.min(Mv,Math.round(He*qp))<<1),bt=U$(Ie,Ae,We,ze!=="none",V);u.isUsingAppearanceIconVertexData||(u.isUsingAppearanceIconVertexData=!0,u.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(b,l.numIconVertices));const Et=Math.floor(l.numIconVertices/4),It=Math.min(bt.length,Et);let Dt=b;for(let Ht=0;Ht0||l.numVerticalGlyphVertices>0;if(!Te)return{vertexOffsetDelta:Te?l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices:0,hasChanges:!1};if(u.activeAppearanceIndex===p)return{vertexOffsetDelta:l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices,hasChanges:!1};const Ae=p>=0?P.appearances[p]:null;if(Ae&&u.textShaping){const{appearanceTextOffset:Ie,appearanceTextRotate:We,appearanceTextSize:ze}=uee(Ae,P,x,k,G,X,Y);u.fontScale=mee(ze,u.textScaleFactor);const He=Ae.getUnevaluatedLayoutProperty("text-size");let Ve=this.textSizeData,qe=ae,bt=fe;Ae.hasLayoutProperty("text-size")&&(Ve=Lv(this.zoom,He,this.worldview,ue),qe=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,bt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Et=u.textShaping.bottom-G[1],It=u.textShaping.left-G[0],Dt=u.textShaping.right-G[0];u.textShaping.top=Ie[1]+(u.textShaping.top-G[1]),u.textShaping.bottom=Ie[1]+Et,u.textShaping.left=Ie[0]+It,u.textShaping.right=Ie[0]+Dt;const Pt=oee(0,u.textShaping,Ie,P,!1,x,$,this.allowVerticalPlacement,We),Ht=ze&&Ve.kind==="composite"?He.possiblyEvaluate(new fs(qe,{}),k).evaluate(x,V,k):te,vt=ze&&Ve.kind==="composite"?He.possiblyEvaluate(new fs(bt,{}),k).evaluate(x,V,k):se,Rt=H$(Ae.name,Ve,ze,O,Ht,vt),Bt=Array.isArray(Rt)?Rt[1]:ze,Yt=0,tr=1+(Math.min(Mv,Math.round(Bt*qp))<<1);u.isUsingAppearanceTextVertexData||(u.isUsingAppearanceTextVertexData=!0,u.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(b,l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices));for(let wr=0;wr0){const O=new Set(Object.keys(l).map($=>{const V=Number($);return!isNaN(V)&&Number.isSafeInteger(V)&&String(V)===$?V:$}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(O,b[0],u,P,p,l,k),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(O,b[0],u,P,p,l,k)}}}updateRoadElevation(l){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let u=!1;const p=zt(l),x=1/p;let b=!1,T=!1;for(let k=0;k0||G>0,se=Y>0,ae=this.elevationFeatures[P.elevationFeatureIndex];if(ae){const fe=new Ft(P.tileAnchorX,P.tileAnchorY),ue=.075+ae.pointElevation(fe);P.zOffset!==ue&&(u=!0,P.zOffset=ue),ue!==0&&(this.hasAnyZOffset=!0);const Te=ae.computeSlopeNormal(fe,x),Ae=zi(At(),Se(0,0,1),Te);rn(O,O,Ae),rn($,$,Ae),O[2]*=p,$[2]*=p,O[0]===1&&O[1]===0&&O[2]===0&&$[0]===0&&$[1]===1&&$[2]===0||(b=b||te,T=T||se)}if(te&&(TR(this.text.orientationVertexArray,V,O,$),TR(this.text.orientationVertexArray,G,O,$)),se){const{placedIconSymbolIndex:fe,verticalPlacedIconSymbolIndex:ue}=P;fe>=0&&TR(this.icon.orientationVertexArray,Y,O,$),ue>=0&&TR(this.icon.orientationVertexArray,X,O,$)}}b||(this.text.orientationVertexArray=void 0),T||(this.icon.orientationVertexArray=void 0),u&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const l=(b,T,k)=>{p+=T,p>b.length&&b.resize(p);for(let P=-T;P<0;P++)b.emplace(P+p,k)},u=(b,T,k)=>{x+=T,x>b.length&&b.resize(x);for(let P=-T;P<0;P++)b.emplace(P+x,k)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let p=0,x=0;for(let b=0;b0;if((k>0||P>0)&&(l(this.text.zOffsetVertexArray,k,$),l(this.text.zOffsetVertexArray,P,$)),V){const{placedIconSymbolIndex:G,verticalPlacedIconSymbolIndex:Y}=T;G>=0&&u(this.icon.zOffsetVertexArray,O,$),Y>=0&&u(this.icon.zOffsetVertexArray,T.numVerticalIconVertices,$)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(l,u,p,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(T=>T.appearances&&T.appearances.length>0)),this.icon.upload(l,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(l,u,p,x,b,T=!1){const k={hasLayoutChanges:!1,hasUboChanges:!1};if(!l||!p||!this.featureAppearanceData)return k;const P=u||{},O=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,$=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!O&&!$)return k;const V=this.layers[0],G=V.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===V.appearancesVersion||(this.featureAppearances=new $Le(V.appearances,V.appearancesVersion));const Y=this.featureAppearances.update(x,T);if(Y.kind==="no-changes")return k;let X=1,te=0,se=!1,ae=!1;if(O){const[Ie,We]=G.get("icon-size-scale-range");X=pe(1,Ie,We)}let fe=1,ue=0,Te=!1;if($){const[Ie,We]=G.get("text-size-scale-range");fe=pe(1,Ie,We)}const Ae=new Map;if(b&&p)for(const Ie of p){const We=b.getImage(Ie,V.scope);if(We){const ze=new Mu(Ie.toString());Ae.set(ze.toString(),We)}}for(let Ie=0;IeDt.isActive({globals:x,feature:qe,canonical:l,featureState:Ve})):-1;bt=It>=0?It:-1}const Et=ze.activeAppearanceIndex!==bt;if($){const It=G.get("text-size"),Dt=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Pt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Ht={canonical:l,layer:V,featureState:Ve,availableImages:p,textScaleFactor:fe,imageMap:Ae,layoutTextOffset:G.get("text-offset").evaluate(qe,Ve,l).map(Rt=>Rt*Za),layoutTextSize:It.evaluate(qe,Ve,l),layoutTextRotate:G.get("text-rotate").evaluate(qe,Ve,l),layoutMinZoomSize:It.evaluate(qe,{zoom:Dt},l),layoutMaxZoomSize:It.evaluate(qe,{zoom:Pt},l),layoutTextSizeMinZoom:Dt,layoutTextSizeMaxZoom:Pt},vt=this.updateSymbolInstanceTextVertices(We,ze,bt,qe,ue,Ht);ue+=vt.vertexOffsetDelta,Te=Te||vt.hasChanges}if(O){const It={canonical:l,layer:V,featureState:Ve,availableImages:p,globalProperties:x,iconScaleFactor:X,layoutIconOffset:G.get("icon-offset").evaluate(qe,Ve,l),layoutIconSize:G.get("icon-size").evaluate(qe,Ve,l,p),layoutIconRotate:G.get("icon-rotate").evaluate(qe,Ve,l)},Dt=this.updateSymbolInstanceIconVertices(We,ze,bt,qe,te,It);te+=Dt.vertexOffsetDelta,se=se||Dt.hasChanges}if(Et){const It=We.featureIndex,Dt=x?x.brightness:null,Pt=Ve||{},Ht=bt>=0?V.appearances[bt]:null;this.text.uboBinder&&(this.text.uboBinder.layer=V,ae=this.text.uboBinder.updateFeaturePaintForAppearance(It,qe,Pt,l,p,Dt,Ht)||ae),this.icon.uboBinder&&(this.icon.uboBinder.layer=V,ae=this.icon.uboBinder.updateFeaturePaintForAppearance(It,qe,Pt,l,p,Dt,Ht)||ae)}ze.activeAppearanceIndex=bt}return se&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Te&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:se||Te,hasUboChanges:ae}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=wee(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(l,u){const p=this.lineVertexArray.length;if(l.segment!==void 0)for(const{x,y:b}of u)this.lineVertexArray.emplaceBack(x,b);return{lineStartIndex:p,lineLength:this.lineVertexArray.length-p}}addSymbols(l,u,p,x,b,T,k,P,O,$,V,G,Y,X,te,se,ae,fe){const ue=l.indexArray,Te=l.layoutVertexArray,Ae=l.globeExtVertexArray,Ie=fe,We=l.uboBinder?l.uboBinder.getCurrentBatchIndex():void 0,ze=l.segments.prepareSegment(4*Ie,Te,ue,this.canOverlap?T.sortKey:void 0,We),He=this.glyphOffsetArray.length,Ve=ze.vertexLength,qe=this.allowVerticalPlacement&&k===ru.vertical?Math.PI/2:0,bt=T.text&&T.text.sections;let Et=Te.length,It=-1;for(let Ht=0;Ht=0)){const Ht=4*Dt;for(let vt=0;vt=0?u.rightJustifiedTextSymbolIndex:u.centerJustifiedTextSymbolIndex>=0?u.centerJustifiedTextSymbolIndex:u.leftJustifiedTextSymbolIndex>=0?u.leftJustifiedTextSymbolIndex:u.verticalPlacedTextSymbolIndex>=0?u.verticalPlacedTextSymbolIndex:x),T=D$(this.textSizeData,l,b)/Za;return this.tilePixelRatio*T}getSymbolInstanceIconSize(l,u,p){const x=this.icon.placedSymbolArray.get(p),b=D$(this.iconSizeData,l,x);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(l,u,p,x){l.emplaceBack(u,-p,-p,x),l.emplaceBack(u,p,-p,x),l.emplaceBack(u,p,p,x),l.emplaceBack(u,-p,p,x)}_updateTextDebugCollisionBoxes(l,u,p,x,b,T,k){for(let P=x;P0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(l,u){const p=l.placedSymbolArray.get(u),x=p.vertexStartIndex+4*p.numGlyphs;for(let b=p.vertexStartIndex;bx[k]-x[P]||b[P]-b[k]),T}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let l=0;lthis.symbolInstances.get(u).zOffset-this.symbolInstances.get(l).zOffset)}addToSortKeyRanges(l,u){const p=this.sortKeyRanges[this.sortKeyRanges.length-1];p&&p.sortKey===u?p.symbolInstanceEnd=l+1:this.sortKeyRanges.push({sortKey:u,symbolInstanceStart:l,symbolInstanceEnd:l+1})}sortFeatures(l){if(this.sortFeaturesByY&&this.sortedAngle!==l)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(l),this.sortedAngle=l,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const u of this.symbolInstanceIndexes){const p=this.symbolInstances.get(u);this.featureSortOrder.push(p.featureIndex);const{rightJustifiedTextSymbolIndex:x,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:T,verticalPlacedTextSymbolIndex:k,placedIconSymbolIndex:P,verticalPlacedIconSymbolIndex:O}=p;x>=0&&this.addIndicesForPlacedSymbol(this.text,x),b>=0&&b!==x&&this.addIndicesForPlacedSymbol(this.text,b),T>=0&&T!==b&&T!==x&&this.addIndicesForPlacedSymbol(this.text,T),k>=0&&this.addIndicesForPlacedSymbol(this.text,k),P>=0&&this.addIndicesForPlacedSymbol(this.icon,P),O>=0&&this.addIndicesForPlacedSymbol(this.icon,O)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(l,u){const p=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const x of this.symbolsByBatch.values())for(const b of x){const T=this.symbolInstances.get(b.index);b.rotatedY=0|Math.round(l*T.tileAnchorX+u*T.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let x=0;xb.rotatedY-T.rotatedY||T.featureIndex-b.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(l,u){for(const p of l){const x=p.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){p.primitiveOffset=this.text.indexArray.length,p.primitiveLength=0;continue}p.primitiveOffset=this.text.indexArray.length;const T=this.text.indexArray.length;for(const{index:k}of b){const P=this.symbolInstances.get(k),{rightJustifiedTextSymbolIndex:O,centerJustifiedTextSymbolIndex:$,leftJustifiedTextSymbolIndex:V,verticalPlacedTextSymbolIndex:G}=P;O>=0&&this.addIndicesForPlacedSymbol(this.text,O),$>=0&&$!==O&&this.addIndicesForPlacedSymbol(this.text,$),V>=0&&V!==$&&V!==O&&this.addIndicesForPlacedSymbol(this.text,V),G>=0&&this.addIndicesForPlacedSymbol(this.text,G)}p.primitiveLength=this.text.indexArray.length-T}}rebuildIconSegmentIndices(l,u){for(const p of l){const x=p.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){p.primitiveOffset=this.icon.indexArray.length,p.primitiveLength=0;continue}p.primitiveOffset=this.icon.indexArray.length;const T=this.icon.indexArray.length;for(const{index:k}of b){const P=this.symbolInstances.get(k),{placedIconSymbolIndex:O,verticalPlacedIconSymbolIndex:$}=P;O>=0&&this.addIndicesForPlacedSymbol(this.icon,O),$>=0&&this.addIndicesForPlacedSymbol(this.icon,$)}p.primitiveLength=this.icon.indexArray.length-T}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const l=Math.sin(this.sortedAngle),u=Math.cos(this.sortedAngle),p=this.getOrCreateSortedSymbolsByBatch(l,u),x=Array.from(p.keys()).sort((b,T)=>b-T);for(const b of x){const T=p.get(b);for(const{index:k}of T){const P=this.symbolInstances.get(k);this.featureSortOrder.push(P.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),p),this.rebuildIconSegmentIndices(this.icon.segments.get(),p),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(l){const u=this.symbolInstances.get(this.text.symbolInstanceIndices[l]).elevationFeatureIndex;let p;return this.elevationFeatures&&up in h?String(h[p]):"")}let Tee,jee,Z$;jr(Jh,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Jh.addDynamicAttributes=Uw;class Eee{constructor(l){this.type=l.property.overrides?l.property.overrides.runtimeType:zh,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}}jr(Eee,"FormatSectionOverride",{omit:["defaultValue"]});const X$=()=>Z$||(Z$={layout:Tee||(Tee=new fi({"symbol-placement":new sr(at.layout_symbol["symbol-placement"]),"symbol-spacing":new sr(at.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new sr(at.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Qt(at.layout_symbol["symbol-sort-key"]),"symbol-z-order":new sr(at.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new sr(at.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new sr(at.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new sr(at.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new sr(at.layout_symbol["icon-ignore-placement"]),"icon-optional":new sr(at.layout_symbol["icon-optional"]),"icon-rotation-alignment":new sr(at.layout_symbol["icon-rotation-alignment"]),"icon-size":new Qt(at.layout_symbol["icon-size"]),"icon-size-scale-range":new sr(at.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Qt(at.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Qt(at.layout_symbol["icon-text-fit-padding"]),"icon-image":new Qt(at.layout_symbol["icon-image"]),"icon-image-use-theme":new sr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Qt(at.layout_symbol["icon-rotate"]),"icon-padding":new sr(at.layout_symbol["icon-padding"]),"icon-keep-upright":new sr(at.layout_symbol["icon-keep-upright"]),"icon-offset":new Qt(at.layout_symbol["icon-offset"]),"icon-anchor":new Qt(at.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new sr(at.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new sr(at.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new sr(at.layout_symbol["text-rotation-alignment"]),"text-field":new Qt(at.layout_symbol["text-field"]),"text-font":new Qt(at.layout_symbol["text-font"]),"text-size":new Qt(at.layout_symbol["text-size"]),"text-size-scale-range":new sr(at.layout_symbol["text-size-scale-range"]),"text-max-width":new Qt(at.layout_symbol["text-max-width"]),"text-line-height":new Qt(at.layout_symbol["text-line-height"]),"text-letter-spacing":new Qt(at.layout_symbol["text-letter-spacing"]),"text-justify":new Qt(at.layout_symbol["text-justify"]),"text-radial-offset":new Qt(at.layout_symbol["text-radial-offset"]),"text-variable-anchor":new sr(at.layout_symbol["text-variable-anchor"]),"text-anchor":new Qt(at.layout_symbol["text-anchor"]),"text-max-angle":new sr(at.layout_symbol["text-max-angle"]),"text-writing-mode":new sr(at.layout_symbol["text-writing-mode"]),"text-rotate":new Qt(at.layout_symbol["text-rotate"]),"text-padding":new sr(at.layout_symbol["text-padding"]),"text-keep-upright":new sr(at.layout_symbol["text-keep-upright"]),"text-transform":new Qt(at.layout_symbol["text-transform"]),"text-offset":new Qt(at.layout_symbol["text-offset"]),"text-allow-overlap":new sr(at.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new sr(at.layout_symbol["text-ignore-placement"]),"text-optional":new sr(at.layout_symbol["text-optional"]),visibility:new sr(at.layout_symbol.visibility)})),paint:jee||(jee=new fi({"icon-opacity":new Qt(at.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qt(at.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qt(at.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qt(at.paint_symbol["text-emissive-strength"]),"icon-color":new Qt(at.paint_symbol["icon-color"]),"icon-halo-color":new Qt(at.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qt(at.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qt(at.paint_symbol["icon-halo-blur"]),"icon-translate":new sr(at.paint_symbol["icon-translate"]),"icon-translate-anchor":new sr(at.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new sr(at.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Qt(at.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qt(at.paint_symbol["text-occlusion-opacity"]),"text-color":new Qt(at.paint_symbol["text-color"],{runtimeType:Ml,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new Qt(at.paint_symbol["text-halo-color"]),"text-halo-width":new Qt(at.paint_symbol["text-halo-width"]),"text-halo-blur":new Qt(at.paint_symbol["text-halo-blur"]),"text-translate":new sr(at.paint_symbol["text-translate"]),"text-translate-anchor":new sr(at.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new sr(at.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new sr(at.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new sr(at.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new sr(at.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Qt(at.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"})}))},Z$);class jR extends pl{constructor(l,u,p,x){super(l,X$(),u,p,x,l.layout?l.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=I([]),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 p=this.layout.get("text-writing-mode");if(p){const x=[];for(const b of p)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,p,x){return this._saturation===l&&this._contrast===u&&this._brightnessMin===p&&this._brightnessMax===x||(this._colorAdjustmentMatrix=function(b,T,k,P){b=ni(b),T=Un(T);const O=A(),$=b/3,V=1-2*$,G=[V,$,$,0,$,V,$,0,$,$,V,0,0,0,0,1],Y=.5-.5*T,X=P-k;return D(O,[X,0,0,0,0,X,0,0,0,0,X,0,k,k,k,1],[T,0,0,0,0,T,0,0,0,0,T,0,Y,Y,Y,1]),D(O,O,G),O}(l,u,p,x),this._saturation=l,this._contrast=u,this._brightnessMin=p,this._brightnessMax=x),this._colorAdjustmentMatrix}getValueAndResolveTokens(l,u,p,x){const b=this.layout.get(l).evaluate(u,{},p,x),T=this._unevaluatedLayout._values[l];return T.isDataDriven()||cv(T.value)||!b?b:See(u.properties,b)}getAppearanceValueAndResolveTokens(l,u,p,x,b){const T=l.getLayoutProperty(u);if(!T)return;const k=T.evaluate(p,{},x,b),P=l.getUnevaluatedLayoutProperties()._values[u];return P.isDataDriven()||cv(P.value)||!k||typeof k!="string"?k:See(p.properties,k)}createBucket(l){return new Jh(l)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const l of X$().paint.overridableProperties){if(!jR.hasPaintOverride(this.layout,l))continue;const u=this.paint.get(l),p=new Eee(u),x=new sw(p,u.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let b=null;b=u.value.kind==="constant"||u.value.kind==="source"?new yy("source",x):new Np("composite",x,u.value.zoomStops,u.value.interpolationType),this.paint._values[l]=new Rp(u.property,b,u.parameters)}}_handleOverridablePaintPropertyUpdate(l,u,p){return!(!this.layout||u.isDataDriven()||p.isDataDriven())&&jR.hasPaintOverride(this.layout,l)}static hasPaintOverride(l,u){const p=l.get("text-field"),x=X$().paint.properties[u];let b=!1;const T=k=>{for(const P of k)if(x.overrides&&x.overrides.hasOverride(P))return void(b=!0)};if(p.value.kind==="constant"&&p.value.value instanceof Zo)T(p.value.value.sections);else if(p.value.kind==="source"){const k=O=>{b||(O instanceof Mr&&Vi(O.value)===B0?T(O.value.sections):O instanceof wp?T(O.sections):O.eachChild(k))},P=p.value;P._styleExpression&&k(P._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(l,u,p){return{config:new re(this,{zoom:u,lut:p}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let kee,Aee,Nee,Cee;var ER=On([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function kR(h,l,u,p,x,b,T,k){const P=[h,l,1,u,p,1,x,b,1],O=[T,k,1],$=w([],P),[V,G,Y]=Tr(O,O,$);return j(P,P,[V,0,0,0,G,0,0,0,Y])}function Iee(h,l,u,p,x,b,T,k){const P=function(O,$,V,G,Y,X,te,se){const ae=kR(0,0,1,0,1,1,0,1),fe=kR(O,$,V,G,Y,X,te,se);return j(fe,fe,w([],ae))}(h,l,u,p,x,b,T,k);return[P[2]/P[8]/fr,P[5]/P[8]/fr]}function AR(h){return[h[0],Math.min(Math.max(h[1],-85.051129),Nt)]}class Pee extends F0{constructor(l,u,p,x){super(),this.id=l,this.dispatcher=p,this.coordinates=u.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(x),this.options=u,this._dirty=!1}load(l,u){if(this._loaded=u||!1,this.fire(new ud("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return l&&(this.coordinates=l),this._loaded=!0,void this._finishLoading();this._imageRequest=ty(this.map._requestManager.transformRequest(this.url,D0.Image),(p,x)=>{this._imageRequest=null,this._loaded=!0,p?this.fire(new ry(p)):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 j2(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 ud("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 j2||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(l){if(this.coordinates=l,this._boundsArray=void 0,this._unsupportedCoords=!1,!l.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let u=l[0][1],p=l[0][1];for(const b of l)b[1]>p&&(p=b[1]),b[1]Nt?this.onNorthPole=!0:x<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const b=l.map(Pr.fromLngLat);this.tileID=function(T){let k=1/0,P=1/0,O=-1/0,$=-1/0;for(const te of T)k=Math.min(k,te.x),P=Math.min(P,te.y),O=Math.max(O,te.x),$=Math.max($,te.y);const V=Math.max(O-k,$-P),G=Math.max(0,Math.floor(-Math.log2(V))),Y=Math.pow(2,G);let X=Math.floor((k+O)/2*Y);return X>1&&(X-=1),new Nv(G,X,Math.floor((P+$)/2*Y))}(b),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new ud("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof j2||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(l){for(const se in this.tiles){const ae=this.tiles[se];ae.state!=="loaded"&&(ae.state="loaded",ae.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const u=Dv(new Nv(0,0,0),this.map.transform.projection),p=[u.projection.project(this.coordinates[0][0],this.coordinates[0][1]),u.projection.project(this.coordinates[1][0],this.coordinates[1][1]),u.projection.project(this.coordinates[2][0],this.coordinates[2][1]),u.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(se){const ae=se[1].x-se[0].x,fe=se[1].y-se[0].y,ue=se[2].x-se[1].x,Te=se[2].y-se[1].y,Ae=se[3].x-se[2].x,Ie=se[3].y-se[2].y,We=se[0].x-se[3].x,ze=se[0].y-se[3].y,He=ae*Te-ue*fe,Ve=ue*Ie-Ae*Te,qe=Ae*ze-We*Ie,bt=We*fe-ae*ze;return He>0&&Ve>0&&qe>0&&bt>0||He<0&&Ve<0&&qe<0&&bt<0}(p))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const x=Dv(this.tileID,this.map.transform.projection),[b,T,k,P]=this.coordinates.map(se=>{const ae=x.projection.project(se[0],se[1]);return yee(x,ae)._round()});this.perspectiveTransform=Iee(b.x,b.y,T.x,T.y,k.x,k.y,P.x,P.y);const O=this._boundsArray=new Mo;O.emplaceBack(b.x,b.y,0,0),O.emplaceBack(T.x,T.y,fr,0),O.emplaceBack(P.x,P.y,0,fr),O.emplaceBack(k.x,k.y,fr,fr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=l.createVertexBuffer(O,ER.members),this.boundsSegments=Os.simpleSegment(0,0,4,2);const $=[],V=function(se){return[AR(se[0]),AR(se[1]),AR(se[2]),AR(se[3])]}(this.coordinates),[G,Y,X,te]=function(se){let ae=se[0][0],fe=ae,ue=se[0][1],Te=ue;for(let Ae=1;Aefe&&(fe=se[Ae][0]),se[Ae][1]Te&&(Te=se[Ae][1]);return[ae,ue,fe-ae,Te-ue]}(V);{const se=new Mo,[ae,fe,ue,Te]=function(Pt){let Ht=Pt[0].x,vt=Ht,Rt=Pt[0].y,Bt=Rt;for(let Yt=1;Ytvt&&(vt=Pt[Yt].x),Pt[Yt].yBt&&(Bt=Pt[Yt].y);return[Ht,Rt,vt-Ht,Bt-Rt]}(p),Ae=Pt=>[(Pt.x-ae)/ue,(Pt.y-fe)/Te],[Ie,We,ze,He]=p.map(Ae),Ve=function(Pt,Ht,vt,Rt,Bt,Yt,tr,wr){const ur=kR(0,0,1,0,1,1,0,1);return j(ur,ur,w([],kR(Pt,Ht,vt,Rt,Bt,Yt,tr,wr)))}(Ie[0],Ie[1],We[0],We[1],ze[0],ze[1],He[0],He[1]);this.elevatedGlobePerspectiveTransform=Iee(Ie[0],Ie[1],We[0],We[1],ze[0],ze[1],He[0],He[1]);const qe=(Pt,Ht)=>{$.push(Pt.lng);const vt=Math.round((Pt.lng-G)/X*fr),Rt=Math.round((Pt.lat-Y)/te*fr),Bt=Ae(Ht),Yt=Tr([],[Bt[0],Bt[1],1],Ve),tr=Math.round(Yt[0]/Yt[2]*fr),wr=Math.round(Yt[1]/Yt[2]*fr);se.emplaceBack(vt,Rt,tr,wr)},bt=p[3].x-p[0].x,Et=p[3].y-p[0].y,It=p[2].x-p[1].x,Dt=p[2].y-p[1].y;for(let Pt=0;Pt<65;Pt++){const Ht=Pt/64,vt=[p[0].x+Ht*bt,p[0].y+Ht*Et],Rt=[p[1].x+Ht*It,p[1].y+Ht*Dt],Bt=Rt[0]-vt[0],Yt=Rt[1]-vt[1];for(let tr=0;tr<65;tr++){const wr=tr/64,ur={x:vt[0]+Bt*wr,y:vt[1]+Yt*wr};qe(u.projection.unproject(ur.x,ur.y),ur)}}this.elevatedGlobeVertexBuffer=l.createVertexBuffer(se,ER.members)}{this.maxLongitudeTriangleSize=0;let se=[],ae=new Pi;const fe=(ue,Te,Ae)=>{ae.emplaceBack(ue,Te,Ae);const Ie=$[ue],We=$[Te],ze=$[Ae],He=Math.min(Math.min(Ie,We),ze),Ve=Math.max(Math.max(Ie,We),ze)-He;Ve>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Ve),se.push(He+Ve/2)};for(let ue=0;ue<64;ue++)for(let Te=0;Te<64;Te++){const Ae=65*ue+Te,Ie=Ae+1,We=Ae+65,ze=We+1;fe(Ae,We,Ie),fe(Ie,We,ze)}[se,ae]=function(ue,Te){const Ae=Array.from({length:ue.length},(ze,He)=>He);Ae.sort((ze,He)=>ue[ze]-ue[He]);const Ie=[],We=new Pi;for(let ze=0;ze{T.segments.push({vertexOffset:0,primitiveOffset:V,vertexLength:u.segments[0].vertexLength,primitiveLength:G,sortKey:void 0,vaos:{}})},P=.51*this.maxLongitudeTriangleSize;if(Math.abs(p[0]-x)<=P){const V=Ui(p,0,p.length,x+P);return V===p.length||k(V,ks(p,V+1,p.length,x+360-P)-V),T}x0}}let Lee,Mee,Dee,Oee,Fee,Bee,$ee;class zee extends pl{constructor(l,u,p,x){super(l,{layout:Lee||(Lee=new fi({visibility:new sr(at["layout_raster-particle"].visibility)})),paint:Mee||(Mee=new fi({"raster-particle-array-band":new sr(at["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new sr(at["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new by(at["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new sr(at["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new sr(at["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new sr(at["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new sr(at["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new sr(at["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Qt({type:"string",default:"default","property-type":"data-driven"})}))},u,p,x),this._updateColorRamp(),this.lastInvalidatedAt=Zl.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=u2({expression:l,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:u}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Zl.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class GLe extends pl{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 J$(h,l,u){const p=[0,0,1],x=pr([]);return Gn(x,x,u?-Xn(h)+Math.PI:Xn(h)),yn(x,x,-Xn(l)),rn(p,p,x),ft(p,p)}class NR{constructor(l,u,p,x){this.message=(l?`${l}: `:"")+p,x&&(this.identifier=x),u!=null&&u.__line__&&(this.line=u.__line__)}}function ez(h,l){const u=h.indexOf("://")===-1;try{return new URL(h,u&&l?"http://example.com":void 0),!0}catch{return!1}}class Uee{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 Vee{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new t2,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(l){const u=16*l,p=this.instancedDataArray.float32;let x=Math.floor(p[u+2]);const b=1.05*(p[u+2]-x);return x/=100,[p[u]%1*1.05,p[u+1]%1*1.05,b,x]}tileCoordinatesForInstance(l){const u=16*l,p=this.instancedDataArray.float32;let x=p[u+0];return x=x>fr?x-fr:x,new Ft(Math.trunc(x),Math.trunc(p[u+1]))}translationForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+4],p[u+5],p[u+6]]}rotationScaleForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+7],p[u+8],p[u+9],p[u+10],p[u+11],p[u+12],p[u+13],p[u+14],p[u+15]]}transformForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+7],p[u+8],p[u+9],p[u+4],p[u+10],p[u+11],p[u+12],p[u+5],p[u+13],p[u+14],p[u+15],p[u+6],0,0,0,1]}}class tz{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaledZ=this.canonical.z+Math.log2(l.overscaling),this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.projection=l.projection,this.index=l.index,this.worldview=l.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=l.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,x){this.tileToMeter=zt(p);const b=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const T=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?u.elevationFeatures:void 0;for(const{feature:k,id:P,index:O,sourceLayerIndex:$}of l){const V=P??(k.properties&&k.properties.hasOwnProperty("id")?k.properties.id:void 0),G=jn(k,b);if(!this.layers[0]._featureFilter.filter(new fs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),G,p))continue;const Y={id:V,sourceLayerIndex:$,index:O,geometry:b?G.geometry:Kr(k,p,x),properties:k.properties,type:k.type,patterns:{}},X=this.addFeature(Y,Y.geometry,G,T,p);X&&u.featureIndex.insert(k,Y.geometry,O,$,this.index,this.instancesPerModel[X].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const l=this.layers[0].modelManager,u=this.layers[0].scope;let p=0;for(const x of this.modelUris){const b=l.getModel(x,u);if(!b)continue;const T=this.instancesPerModel[x];if(T){const k=.5*lt(b.aabb.max,b.aabb.min)*T.maxScale+T.maxXYTranslationDistance,P=Math.min(fr,Math.max(k/this.tileToMeter,256));p=Math.max(P,p)}}return p}update(l,u,p,x){for(const b in this.instancesPerModel){const T=this.instancesPerModel[b];for(const k in l)T.idToFeaturesIndex.hasOwnProperty(k)&&(this.evaluate(T.features[T.idToFeaturesIndex[k]],l[k],T,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let l=!1;for(const u in this.instancesPerModel){const p=this.instancesPerModel[u];for(const x of p.features){const b=this.layers[0],T=x.feature,k=this.canonical,P=b.paint.get("model-rotation").evaluate(T,{},k),O=b.paint.get("model-scale").evaluate(T,{},k),$=b.paint.get("model-translation").evaluate(T,{},k);$r(x.rotation,P)&&$r(x.scale,O)&&$r(x.translation,$)||(this.evaluate(x,x.featureStates,p,!0),l=!0)}}return l}updateReplacement(l,u,p,x){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const b=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);if(KP(this.activeReplacements,b))return!1;this.activeReplacements=b;let T=!1;for(const k in this.instancesPerModel){const P=this.instancesPerModel[k],O=P.instancedDataArray;for(const $ of P.features){const V=$.instancedDataOffset,G=$.instancedDataCount;for(let Y=0;Yfr;te=se?te-fr:te;const ae=Math.floor(te),fe=Math.floor(O.float32[X+1]);let ue=!1;for(const Te of this.activeReplacements)if(!TQ(Te,p,YP.Model,x)&&!(Te.min.x>ae||ae>Te.max.x||Te.min.y>fe||fe>Te.max.y)&&(ue=NQ(AQ(ae,fe,l.canonical,Te.footprintTileId.canonical),Te.footprint),ue))break;O.float32[X]=ue?te+fr:te,T=T||ue!==se}}}return T}isEmpty(){for(const l in this.instancesPerModel)if(this.instancesPerModel[l].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(l){if(!this.uploaded)for(const u in this.instancesPerModel){const p=this.instancesPerModel[u];p.instancedDataArray.length<0||p.instancedDataArray.length===0||(p.instancedDataBuffer?p.instancedDataBuffer.updateData(p.instancedDataArray):p.instancedDataBuffer=l.createVertexBuffer(p.instancedDataArray,uRe.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(l){for(const p in this.instancesPerModel){const x=this.instancesPerModel[p];x.instancedDataArray.length!==0&&x.instancedDataBuffer&&x.instancedDataBuffer.destroy()}const u=this.layers[0].modelManager;if(l&&u&&this.modelUris&&this.modelsRequested)for(const p of this.modelUris)u.removeModel(p,"",!0)}addFeature(l,u,p,x,b){const T=this.layers[0],k=T.layout.get("model-id"),P=T.layout.get("model-allow-density-reduction"),O=k.evaluate(p,{},this.canonical);if(!O)return hr(`modelId is not evaluated for layer ${T.id} and it is not going to get rendered.`),O;(ez(O,!1)||this.styleDefinedModelURLs[O]!==void 0)&&(this.modelUris.includes(O)||this.modelUris.push(O)),this.instancesPerModel[O]||(this.instancesPerModel[O]=new Vee);const $=this.instancesPerModel[O],V=$.instancedDataArray,G=new Uee(p,V.length);let Y;x&&(Y=Vs.getElevationFeature(l,x));for(const X of u)for(const te of X){if(te.x<0||te.x>=fr||te.y<0||te.y>=fr)continue;if(this.lookupDim!==0&&P){const ae=(this.lookupDim-1)/fr,fe=this.lookupDim*(te.y*ae|0)+te.x*ae|0;if(this.lookup){if(this.lookup[fe]!==0)continue;this.lookup[fe]=1}}this.instanceCount++;const se=V.length;if(V.resize(se+1),x){$.instancesRoadElevation||($.instancesRoadElevation=[]);const ae=Y?Y.pointElevation(new Ft(te.x,te.y)):0;$.instancesRoadElevation.push(ae)}$.instancesEvaluatedElevation.push(0),V.float32[16*se]=te.x,V.float32[16*se+1]=te.y}return G.instancedDataCount=$.instancedDataArray.length-G.instancedDataOffset,G.instancedDataCount>0&&(l.id&&($.idToFeaturesIndex[l.id]=$.features.length),$.features.push(G),this.evaluate(G,{},$,!1)),O}getModelUris(){return this.modelUris}evaluate(l,u,p,x){const b=this.layers[0],T=l.feature,k=this.canonical,P=l.rotation=b.paint.get("model-rotation").evaluate(T,u,k),O=l.scale=b.paint.get("model-scale").evaluate(T,u,k),$=l.translation=b.paint.get("model-translation").evaluate(T,u,k),V=Object.assign({},b.paint.get("model-color").evaluate(T,u,k));V.a=b.paint.get("model-color-mix-intensity").evaluate(T,u,k);const G=[];this.maxVerticalOffset<$[2]&&(this.maxVerticalOffset=$[2]);const Y=$[0]*$[0]+$[1]*$[1],X=Y>0?Math.sqrt(Y):0;p.maxScale=Math.max(Math.max(p.maxScale,O[0]),Math.max(O[1],O[2])),p.maxXYTranslationDistance=Math.max(p.maxXYTranslationDistance,X),this.maxScale=Math.max(Math.max(this.maxScale,O[0]),Math.max(O[1],O[2])),fJ(G,P,O);const te=Math.round(100*V.a)+V.b/1.05;for(let se=0;se10?this.tileToMeter:zt(k,Ae)),ue[fe+4]=$[0],ue[fe+5]=$[1],ue[fe+6]=$[2]+(p.instancesRoadElevation?p.instancesRoadElevation[ae]:0)+Te,ue[fe+7]=G[0],ue[fe+8]=G[1],ue[fe+9]=G[2],ue[fe+10]=G[4],ue[fe+11]=G[5],ue[fe+12]=G[6],ue[fe+13]=G[8],ue[fe+14]=G[9],ue[fe+15]=G[10],p.instancesEvaluatedElevation[ae]=$[2]}}}jr(tz,"ModelBucket",{omit:["layers"]}),jr(Vee,"PerModelAttributes"),jr(Uee,"ModelFeature");class qw{constructor(l,u,p){this._demTile=l,this._dem=this._demTile.dem,this._scale=u,this._offset=p}static create(l,u,p){const x=p||l.findDEMTileFor(u);if(!x||!x.dem)return;const b=x.dem,T=x.tileID,k=1<O.fqid),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.modelTraits|=Dw.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,x&&(this.modelTraits|=Dw.HasMapboxMeshFeatures),b&&(this.modelTraits|=Dw.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=T,this.worldview=P,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const O of u)this.nodesInfo.push(new Wee(O)),Gee(O,k.featureIndexArray.length,k.grid),k.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,k.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(l,u){for(const p of this.getNodesInfo()){const x=p.node;x.footprint&&u.push({footprint:x.footprint,id:l})}}updateAppearances(l,u,p,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(l){const u=Object.keys(l).length!==0;if(u&&!this.stateDependentLayers.length)return;const p=u?this.stateDependentLayers:this.layers;if(!jo(l,this.states))for(const x of p)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 p of u){const x=p.node;this.uploaded?this.updatePbrBuffer(x):v$(x,l,!0)}for(const p of u)lR(p.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(l){let u=!1;if(!l.meshes)return u;for(const p of l.meshes)p.pbrBuffer&&(p.pbrBuffer.updateData(p.featureArray),u=!0);return u}needsReEvaluation(l,u,p){const x=l.transform.projectionOptions,b=l.style.getBrightness(),T=this.brightness!==b;if(!this.uploaded||this.dirty||x.name!==this.projection.name||z2(p.paint.get("model-color").value,T)||z2(p.paint.get("model-color-mix-intensity").value,T)||z2(p.paint.get("model-roughness").value,T)||z2(p.paint.get("model-emissive-strength").value,T)||z2(p.paint.get("model-height-based-emissive-strength-multiplier").value,T)){this.projection=x,this.brightness=b;const k=this.getNodesInfo();for(const P of k)P.state=null;return!0}return!1}evaluateTransform(l,u){if(l.transform.zoom===this.zoom)return;this.zoom=l.transform.zoom;const p=this.getNodesInfo(),x=this.id.canonical;for(const b of p){const T=b.feature;b.evaluatedTranslation=u.paint.get("model-translation").evaluate(T,{},x),b.evaluatedScale=u.paint.get("model-scale").evaluate(T,{},x)}}evaluate(l,u){const p=this.getNodesInfo();for(const x of p){if(!x.node.meshes)continue;const b=x.feature,T=u&&u[b.id];if(jo(T,x.state))continue;x.state=structuredClone(T);const k=x.node.meshes&&x.node.meshes[0].featureData,P=x.evaluatedColor[2],O=x.evaluatedRMEA[2],$=this.id.canonical;if(x.hasTranslucentParts=!1,k){for(let V=0;V=Ie)continue;const Ht=rz[Pt],vt=Math.abs(Ht);vt>qe&&(Ve=Ht,qe=vt,bt=Dt,Et=It)}if(qe>.1){const It=1-(Ie+.5*Math.abs(bt*Et))/X;let Dt=u._dem.get(ze,We)+Ve*It;const Pt=u._dem.get(ze+bt,We+Et),Ht=u._dem.get(ze-bt,We-Et,!0);(Dt-Pt)*(Dt-Ht)>0&&(Dt=(Pt+Ht)/2),rz[He]=u._dem.set(ze,We,Dt),Ov[He]=Ie}}}}}k&&(u._demTile.needsDEMTextureUpload=!0,u._dem._timestamp=Zl.now())}setFilter(l){this.filter=l?gw(l):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(l=>this.filter.filter(new fs(this.id.overscaledZ,{worldview:this.worldview}),l.feature,this.id.canonical)):this.nodesInfo}destroy(){const l=this.getNodesInfo();for(const u of l)lR(u.node),_$(u.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=u.updateTime;const p=u.getReplacementRegionsForTile(l.toUnwrapped());for(const x of this.getNodesInfo()){const b=x.node.footprint;x.hiddenByReplacement=!!b&&!p.find(T=>T.footprint===b)}}getHeightAtTileCoord(l,u){const p=[],x=[0,0,0],b=I([]);for(const T of this.getNodesInfo()){const k=T.node.meshes[0],P=k.transformedAabb;if(lP.max[0]||u>P.max[1])continue;if(T.node.hidden===!0)return{height:1/0,maxHeight:T.feature.properties.height,hidden:!1,verticalScale:T.evaluatedScale[2]};M(b,T.node.globalMatrix),x[0]=l,x[1]=u,or(x,x,b);const O=(x[0]-k.aabb.min[0])/(k.aabb.max[0]-k.aabb.min[0])*Pv|0,$=Math.min(63,(x[1]-k.aabb.min[1])/(k.aabb.max[1]-k.aabb.min[1])*Pv|0)*Pv+Math.min(63,O),V=k.heightmap[$];if(!(V<0&&T.node.footprint))return T.hiddenByReplacement?void 0:{height:V,maxHeight:T.feature.properties.height,hidden:!1,verticalScale:T.evaluatedScale[2]};if(T.node.footprint.grid.query(new Ft(l,u),new Ft(l,u),p),p.length>0)return{height:void 0,maxHeight:T.feature.properties.height,hidden:T.hiddenByReplacement,verticalScale:T.evaluatedScale[2]}}}}function z2(h,l){return h instanceof yy&&!h.isLightConstant&&l}function HLe(h,l,u,p,x,b,T,k){let P=(61440&l|(61440&l)>>4)>>8,O=(3840&l|(3840&l)>>4)>>4,$=240&l|(240&l)>>4;u[3]>0&&(P=sn(P,255*u[0],u[3]),O=sn(O,255*u[1],u[3]),$=sn($,255*u[2],u[3]));const V=P<<8|O,G=$<<8|Math.floor(255*p[3]),Y=function(Ie){const We=pe(Ie,0,2);return Math.min(Math.round(.5*We*255),255)}(p[2])<<8|15*p[0]<<4|15*p[1],X=pe(x[0],0,1),te=pe(x[1],0,1),se=pe(x[2],0,1),ae=pe(x[3],0,1);let fe,ue,Te,Ae;if(X!==te&&T!==b&&te!==X){const Ie=T-b;ue=1/(Ie*(te-X)),Te=-(b+Ie*X)/(Ie*(te-X));const We=pe(x[4],-1,1);Ae=Math.pow(10,We),fe=255*se<<8|255*ae}else fe=65535,ue=0,Te=1,Ae=1;if(h.emplaceBack(V,G,Y,fe,ue,Te,Ae),k){const Ie=k.length;k.clear();for(let We=0;We>16&65535,$=b?P>>16&65535:65535&P,V=(15&$)<8?15&$:0,G=h.evaluatedRMEA[V],Y=h.evaluatedColor[V],X=h.emissionHeightBasedParams[V];let te;if(k&&V===2&&p.lights&&(te=new Tw,te.resize(10*p.lights.length)),HLe(T.featureArray,O,Y,G,X,T.aabb.min[2],T.aabb.max[2],te),te&&k){k=!1;const se=p.meshes[p.lightMeshIndex];se.featureArray=te,se.featureArray._trim()}}T.featureArray._trim(),x++}}jr(CR,"Tiled3dModelBucket",{omit:["layers"]}),jr(Wee,"Tiled3dModelFeature");const KLe=["id","tile","layer","source","sourceLayer","state"];class Fv{constructor(l,u,p,x,b){this.type="Feature",this._vectorTileFeature=l,this._z=u,this._x=p,this._y=x,this.properties=l?l.properties:{},this.id=b}clone(){const l=new Fv(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 KLe)this[u]!==void 0&&(l[u]=this[u]);return l}}class Bv extends F0{constructor(l,u,p,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 cJ(this.map._requestManager.transformRequest(l,D0.Model).url,u)}async loadModel(l,u,p){try{const x=await this.loadGLTFFromURI(u.uri,p);if(p.aborted)return;const b=this._modelsInfo.get(l);if(!b)return;const T=w$(x),k=b.modelSpec,P=new mJ(l,k.uri,k.position,k.orientation,T);Bv.applyModelSpecification(P,k),P.computeBoundsAndApplyParent(),this.models.push(P),b.model=P}catch(x){if(x instanceof Error&&x.name==="AbortError")return;const b=x instanceof Error?x.message:"Unknown error";this.fire(new ry(new Error(`Could not load model ${l} from ${u.uri}: ${b}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const l=this._abortController.signal,u=[];for(const p in this._options.models){const x=this._options.models[p],b=this._modelsInfo.get(p);if(b&&b.model){b.modelSpec=x;const T=b.model;T.position=x.position!=null?new Je(x.position[0],x.position[1]):new Je(0,0),T.orientation=x.orientation!=null?x.orientation:[0,0,0],Bv.applyModelSpecification(T,x),T.computeBoundsAndApplyParent(),this.models.push(T)}else b?b.modelSpec=x:(this._modelsInfo.set(p,{modelSpec:x,model:null}),u.push(this.loadModel(p,x,l)))}u.length!==0?(await Promise.allSettled(u),l.aborted||this.fire(new ud("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new ud("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(l,u){u.nodeOverrides&&Bv.convertNodeOverrides(l,u.nodeOverrides),u.materialOverrides&&Bv.convertMaterialOverrides(l,u.materialOverrides),u.nodeOverrideNames&&(l.nodeOverrideNames=[...u.nodeOverrideNames]),u.materialOverrideNames&&(l.materialOverrideNames=[...u.materialOverrideNames]),u.featureProperties&&(l.featureProperties=u.featureProperties)}static convertNodeOverrides(l,u){if(Array.isArray(u)&&u.every(p=>typeof p=="string")){l.nodeOverrideNames=[];for(const p of u)l.nodeOverrideNames.push(p)}else Object.entries(u).forEach(([p,x])=>{const b={orientation:[0,0,0]};if(x.hasOwnProperty("orientation")){const T=x.orientation;T&&(b.orientation=T)}l.nodeOverrides.set(p,b)})}static convertMaterialOverrides(l,u){if(Array.isArray(u)&&u.every(p=>typeof p=="string")){l.materialOverrideNames=[];for(const p of u)l.materialOverrideNames.push(p)}else Object.entries(u).forEach(([p,x])=>{const b={color:new as(1,1,1),colorMix:0,emissionStrength:0,opacity:1},T=x["model-color"];T!==void 0&&(b.color.r=T[0],b.color.g=T[1],b.color.b=T[2]);const k=x["model-color-mix-intensity"];k!==void 0&&(b.colorMix=k);const P=x["model-emissive-strength"];P!==void 0&&(b.emissionStrength=P);const O=x["model-opacity"];O!==void 0&&(b.opacity=O),l.materialOverrides.set(p,b)})}onAdd(l){this.map=l,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const l of this._modelsInfo.values())if(l.model==null)return!1;return!0}getModels(){return this.models}loadTile(l,u){}serialize(){return this._options}setProperty(l,u){return!1}reload(){this.cancelModelRequests();const l=Lp(this.id,this.scope);this.map.style.clearSource(l),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(l){this.cancelModelRequests()}setModels(l){this.models=[];const u=new Map;for(const p in l){const x=l[p],b=this._modelsInfo.get(p);b&&b.modelSpec.uri===x.uri&&u.set(p,b)}if(this._modelsInfo.size!==u.size){this.cancelModelRequests();for(const[p,x]of u)x.model||u.delete(p)}this._modelsInfo=u,this._options.models=l,this.load()}}function nz(h,l,u,p){const x=1<P>=Ae.vertexArrayOffset&&PTe.polygon).flat());const se=Y?k:null,[ae,fe]=KQ(b,p,V,$,O,T,se,G,X,b.center.lat,h.tileID.canonical),ue=h.queryGeometry;return WQ(ae,fe,ue.isPointQuery()?ue.screenBounds:ue.screenGeometry)}},building:class extends pl{constructor(h,l,u,p){super(h,{layout:bJ||(bJ=new fi({visibility:new sr(at.layout_building.visibility),"building-facade":new Qt(at.layout_building["building-facade"]),"building-facade-floors":new Qt(at.layout_building["building-facade-floors"]),"building-facade-unit-width":new Qt(at.layout_building["building-facade-unit-width"]),"building-facade-window":new Qt(at.layout_building["building-facade-window"]),"building-roof-shape":new Qt(at.layout_building["building-roof-shape"]),"building-height":new Qt(at.layout_building["building-height"]),"building-base":new Qt(at.layout_building["building-base"]),"building-flood-light-wall-radius":new Qt(at.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Qt(at.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Qt(at.layout_building["building-flip-roof-orientation"])})),paint:wJ||(wJ=new fi({"building-opacity":new sr(at.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new sr(at.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new sr(at.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new sr(at.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new sr(at.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new sr(at.paint_building["building-vertical-scale"]),"building-cast-shadows":new sr(at.paint_building["building-cast-shadows"]),"building-color":new Qt(at.paint_building["building-color"]),"building-emissive-strength":new Qt(at.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new sr(at.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new sr(at.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new sr(at.paint_building["building-front-cutoff"]),"building-flood-light-color":new sr(at.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new sr(at.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new sr(at.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Qt({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Qt({type:"string",default:"default","property-type":"data-driven"})}))},l,u,p),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new _J(h)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(h){return!0}queryRadius(h){return 0}queryIntersectsFeature(h,l,u,p,x,b,T,k,P,O){let $=this.layout.get("building-height").evaluate(l,u);const V=this.layout.get("building-base").evaluate(l,u),G=h.tile.getBucket(this).getFootprint(l);if(G){if(G.hiddenFlags!==0)return!1;$=G.height}const[Y,X]=KQ(b,p,V,$,new Ft(0,0),T,null,[0,0],1,b.center.lat,h.tileID.canonical),te=h.queryGeometry;return WQ(Y,X,te.isPointQuery()?te.screenBounds:te.screenGeometry)}},line:class extends pl{constructor(h,l,u,p){const x=PJ();super(h,x,l,u,p),x.layout&&(this.layout=new Wh(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 J0,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(k2)return k2;const u=PJ();return k2=new URe(u.paint.properties["line-width"].specification),k2.useIntegerZoom=!0,k2})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,h)}createBucket(h){return new uR(h)}getProgramIds(){const h=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&h.push("lineBlendComposite"),h}getDefaultProgramParams(h,l,u){if(h==="lineBlendComposite")return{};const p=CJ(this);return{config:new re(this,{zoom:l,lut:u}),defines:p,overrideFog:!1}}queryRadius(h){const l=h,u=RJ(Ey("line-width",this,l),Ey("line-gap-width",this,l)),p=Ey("line-offset",this,l);return u/2+Math.abs(p)+LP(this.paint.get("line-translate"))}queryIntersectsFeature(h,l,u,p,x,b){if(h.queryGeometry.isAboveHorizon)return!1;const T=IX(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),k=h.pixelToTileUnitsFactor/2*RJ(this.paint.get("line-width").evaluate(l,u),this.paint.get("line-gap-width").evaluate(l,u)),P=this.paint.get("line-offset").evaluate(l,u);return P&&(p=function(O,$){const V=[],G=new Ft(0,0);for(let Y=0;Y=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 Kee{constructor(l){this._stringToNumber={},this._numberToString=[];for(let u=0;u=0&&G[3]>=0&&O.insert(P,G[0],G[1],G[2],G[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new ds(new dR(this.rawTileData)).layers,this.sourceLayerCoder=new Kee(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const l in this.vtLayers)this.vtFeatures[l]=[]}return this.vtLayers}query(l,u){const{tilespaceGeometry:p,transform:x,tileTransform:b,pixelPosMatrix:T,availableImages:k,worldview:P}=u;this.loadVTLayers(),this.serializedLayersCache.clear();const O=u.queryRadius?u.queryRadius:0,$=p.bufferedTilespaceBounds,V=this.grid.query($.min.x,$.min.y,$.max.x,$.max.y,(te,se,ae,fe)=>im(p.bufferedTilespaceGeometry,te-O,se-O,ae+O,fe+O));V.sort(QLe);let G=null;x.elevation&&V.length>0&&(G=qw.create(x.elevation,this.tileID));const Y={};let X;for(let te=0;te(fe||(fe=Kr(ue,this.tileID.canonical,b)),Te.queryIntersectsFeature(p,ue,Ae,fe,this.z,x,T,G,Ie,u.scope)))}return Y}loadMatchingFeature(l,u,p,x,b,T){const{featureIndex:k,bucketIndex:P,sourceLayerIndex:O,layoutVertexArrayOffset:$}=u,V=this.bucketLayerIDs[P],G=p.layers,Y=Object.keys(G);if(Y.length&&!zr(Y,V))return;const X=p.sourceCache,te=this.sourceLayerCoder.decode(O),se=this.vtLayers[te].feature(k),ae=this.getId(se,te);for(let fe=0;fe`${k.key}: ${k.message}`).join(", ");return void hr(`Failed to create expression for promoteId: ${T}`)}this.promoteIdExpression=b.value}p=this.promoteIdExpression.evaluate({zoom:0},l)}else p=l.properties[x];typeof p=="boolean"&&(p=Number(p))}return p}}function Zee(h,l,u,p,x){return Gt(h,(b,T)=>{const k=l instanceof Wh?l.get(T):null;return k&&k.evaluate?k.evaluate(u,p,void 0,x):k})}function QLe(h,l){return l-h}function Xee(h,l){const u={};if(!l)return u;for(const p of h){const x=p.layerIds.map(b=>l.getLayer(b)).filter(Boolean);if(x.length!==0){p.layers=x,p.stateDependentLayerIds&&(p.stateDependentLayers=p.stateDependentLayerIds.map(b=>x.filter(T=>T.id===b)[0]));for(const b of x)u[b.fqid]=p}}return u}jr(Yee,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const ih=32,hm=33,Ry=new Uint16Array(8184);for(let h=0;h<2046;h++){let l=h+2,u=0,p=0,x=0,b=0,T=0,k=0;for(1&l?x=b=T=ih:u=p=k=ih;(l>>=1)>1;){const O=u+x>>1,$=p+b>>1;1&l?(x=u,b=p,u=T,p=k):(u=x,p=b,x=T,b=k),T=O,k=$}const P=4*h;Ry[P+0]=u,Ry[P+1]=p,Ry[P+2]=x,Ry[P+3]=b}const fm=new Uint16Array(2178),Ly=new Uint8Array(1089),IR=new Uint16Array(1089);function Qee(h){return h===0?-.03125:h===32?.03125:0}const Jee={Other:0,Symbol:1,FillExtrusion:2},ete={type:2,extent:fr,loadGeometry:()=>[[new Ft(0,0),new Ft(8193,0),new Ft(8193,8193),new Ft(0,8193),new Ft(0,0)]]};class JLe{constructor(){this.tasks={},this.taskQueue=[],mt(["process"],this),this.invoker=new XLe(this.process),this.nextId=0}add(l,u){const p=this.nextId++,x=function({type:b,renderSourceType:T,zoom:k}){k=k||0;const P=T===Jee.Symbol;return b==="message"?0:b!=="maybePrepare"||P?b!=="parseTile"||P?b==="parseTile"&&P?300-k:b==="maybePrepare"&&P?400-k:500:200-k:100-k}(u);if(x===0){try{l()}finally{}return null}return this.tasks[p]={fn:l,metadata:u,priority:x,id:p},this.taskQueue.push(p),this.invoker.trigger(),{cancel:()=>{delete this.tasks[p]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(p=>!!this.tasks[p]),!this.taskQueue.length)return;const l=this.pick();if(l===null)return;const u=this.tasks[l];if(delete this.tasks[l],this.taskQueue.length&&this.invoker.trigger(),!u)return;u.fn()}finally{}}pick(){let l=null,u=1/0;for(let x=0;x>16&255)/255,(h>>8&255)/255,(255&h)/255,1)}function dMe(h,l,u){h===1?(l.rgb_color=LR(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 hMe(h,l,u){h===1?l.transform=RR(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(nte(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 nte(h,l){return h.readFields(fMe,{offset:0,opacity:255,rgb_color:sz},l)}function fMe(h,l,u){h===1?l.offset=u.readFloat():h===2?l.opacity=u.readVarint():h===3&&(l.rgb_color=LR(u.readVarint()))}function mMe(h,l,u){h===1?l.transform=RR(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(nte(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 pMe(h,l,u){h===1?l.transform=RR(u,u.readVarint()+u.pos):h===2?l.clip_path_idx=u.readVarint():h===3&&l.children.push(PR(u,u.readVarint()+u.pos))}function gMe(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(PR(u,u.readVarint()+u.pos))}class yMe{static calculate(l={},u=[]){const p=new Map,x=new Map;if(Object.keys(l).length===0)return p;u.forEach(b=>{x.set(b.name,b.rgb_color||new as(0,0,0))});for(const[b,T]of Object.entries(l))x.has(b)?p.set(x.get(b).toString(),T):console.warn(`Ignoring unknown image variable "${b}"`);return p}}function Gw(h,l=255,u){const p=l/255,x=h.toString(),b=u.has(x)?u.get(x).clone():h.clone();return b.a*=p,b.toString()}function U2(h,l){if(!Iu()){const u=document.createElement("canvas");return u.width=h,u.height=l,u}return new OffscreenCanvas(h,l)}let iz,V2=null;function az(h,l,u,p,x){for(const b of p.children)ste(h,l,u,b,x)}function ste(h,l,u,p,x){p.group?(h.save(),function(b,T,k,P,O){const $=P.mask_idx!=null?k.masks[P.mask_idx]:null,V=P.clip_path_idx!=null?k.clip_paths[P.clip_path_idx]:null;if(P.transform&&(T=Hw(P.transform).preMultiplySelf(T)),!function(X,te,se){return X.opacity!==255||te||se}(P,V!=null,$!=null))return void az(b,T,k,P,O);const G=U2(b.canvas.width,b.canvas.height),Y=G.getContext("2d");az(Y,T,k,P,O),V&&dte(Y,T,k,V),$&&hte(Y,T,k,$,O),b.globalAlpha=P.opacity/255,b.drawImage(G,0,0)}(h,l,u,p.group,x),h.restore()):p.path&&(h.save(),function(b,T,k,P,O){b.setTransform(T),P.paint_order===1?(ite(b,k,P,O),ote(b,k,P,O)):(ote(b,k,P,O),ite(b,k,P,O))}(h,l,u,p.path,x),h.restore())}function ite(h,l,u,p){const x=u.fill;if(!x)return;const b=x.opacity/255;switch(h.save(),h.beginPath(),fte(u,h),x.paint){case"rgb_color":h.fillStyle=Gw(x.rgb_color,x.opacity,p);break;case"linear_gradient_idx":{const T=l.linear_gradients[x.linear_gradient_idx];T.transform&&h.setTransform(Hw(T.transform).preMultiplySelf(h.getTransform())),h.fillStyle=lte(h,T,b,p);break}case"radial_gradient_idx":{const T=l.radial_gradients[x.radial_gradient_idx];T.transform&&h.setTransform(Hw(T.transform).preMultiplySelf(h.getTransform())),h.fillStyle=cte(h,T,b,p)}}h.fill(ate(u)),h.restore()}function ate(h){return h.rule===1?"nonzero":h.rule===2?"evenodd":void 0}function ote(h,l,u,p){const x=u.stroke;if(!x)return;const b=mte(u);h.lineWidth=x.width,h.miterLimit=x.miterlimit,h.setLineDash(x.dasharray),h.lineDashOffset=x.dashoffset;const T=x.opacity/255;switch(x.paint){case"rgb_color":h.strokeStyle=Gw(x.rgb_color,x.opacity,p);break;case"linear_gradient_idx":h.strokeStyle=lte(h,l.linear_gradients[x.linear_gradient_idx],T,p,!0);break;case"radial_gradient_idx":h.strokeStyle=cte(h,l.radial_gradients[x.radial_gradient_idx],T,p,!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 lte(h,l,u,p,x=!1){if(l.stops.length===1){const G=l.stops[0];return Gw(G.rgb_color,G.opacity*u,p)}const{x1:b,y1:T,x2:k,y2:P}=l;let O=new DOMPoint(b,T),$=new DOMPoint(k,P);if(x){const G=Hw(l.transform);O=G.transformPoint(O),$=G.transformPoint($)}const V=h.createLinearGradient(O.x,O.y,$.x,$.y);for(const G of l.stops)V.addColorStop(G.offset,Gw(G.rgb_color,G.opacity*u,p));return V}function cte(h,l,u,p,x=!1){if(l.stops.length===1){const ae=l.stops[0];return Gw(ae.rgb_color,ae.opacity*u,p)}const b=Hw(l.transform),{fx:T,fy:k,fr:P,cx:O,cy:$,r:V}=l;let G=new DOMPoint(T,k),Y=new DOMPoint(O,$),X=P,te=V;if(x){G=b.transformPoint(G),Y=b.transformPoint(Y);const ae=(b.a+b.d)/2;X=P*ae,te=l.r*ae}const se=h.createRadialGradient(G.x,G.y,X,Y.x,Y.y,te);for(const ae of l.stops)se.addColorStop(ae.offset,Gw(ae.rgb_color,ae.opacity*u,p));return se}function ute(h,l,u,p){const x=p.transform?Hw(p.transform).preMultiplySelf(l):l,b=U2(h.canvas.width,h.canvas.height),T=b.getContext("2d");for(const P of p.children)if(P.group)ute(T,x,u,P.group);else if(P.path){const O=P.path,$=new Path2D;$.addPath(mte(O),x),T.fill($,ate(O))}const k=p.clip_path_idx!=null?u.clip_paths[p.clip_path_idx]:null;k&&dte(T,x,u,k),h.globalCompositeOperation="source-over",h.drawImage(b,0,0)}function dte(h,l,u,p){const x=U2(h.canvas.width,h.canvas.height);ute(x.getContext("2d"),l,u,p),h.globalCompositeOperation="destination-in",h.drawImage(x,0,0)}function hte(h,l,u,p,x){if(p.children.length===0)return;const b=p.mask_idx!=null?u.masks[p.mask_idx]:null;b&&hte(h,l,u,b,x);const T=h.canvas.width,k=h.canvas.height,P=U2(T,k),O=P.getContext("2d"),$=p.width,V=p.height,G=p.left,Y=p.top,X=new Path2D,te=new Path2D;te.rect(G,Y,$,V),X.addPath(te,l),O.clip(X);for(const fe of p.children)ste(O,l,u,fe,x);const se=O.getImageData(0,0,T,k),ae=se.data;if(p.mask_type===1)for(let fe=0;fel[T])return null}else{const k=1/p[T];let P=(h[T]-u[T])*k,O=(l[T]-u[T])*k;if(P>O){const $=P;P=O,O=$}if(P>x&&(x=P),Ob)return null}return x}function yte(h,l,u,p,x,b,T,k,P,O,$){const V=p-h,G=x-l,Y=b-u,X=T-h,te=k-l,se=P-u,ae=$[1]*se-$[2]*te,fe=$[2]*X-$[0]*se,ue=$[0]*te-$[1]*X,Te=V*ae+G*fe+Y*ue;if(Math.abs(Te)<1e-15)return null;const Ae=1/Te,Ie=O[0]-h,We=O[1]-l,ze=O[2]-u,He=(Ie*ae+We*fe+ze*ue)*Ae;if(He<0||He>1)return null;const Ve=We*Y-ze*G,qe=ze*V-Ie*Y,bt=Ie*G-We*V,Et=($[0]*Ve+$[1]*qe+$[2]*bt)*Ae;return Et<0||He+Et>1?null:(X*Ve+te*qe+se*bt)*Ae}function xte(h,l,u){return(h-l)/(u-l)}function vte(h,l,u,p,x,b,T,k,P){const O=1<{const fe=se?1:0,ue=(Y+1)*te-fe,Te=X*te,Ae=(X+1)*te-fe;ae[0]=Y*te,ae[1]=Te,ae[2]=ue,ae[3]=Ae};let V=new pte(P);const G=[];for(let Y=0;Y=1;P/=2){const Y=k[k.length-1];V=new pte(P);for(let X=0;X0;){const{idx:X,t:te,nodex:se,nodey:ae,depth:fe}=Y.pop();if(this.leaves[X]){vte(se,ae,fe,l,u,p,x,V,G);const Te=1<=Pt[2])return te}continue}let ue=0;for(let Te=0;Te=O[$[ze]]&&($.splice(ze,0,Te),We=!0);We||($[ue]=Te),ue++}}for(let Te=0;Te=this.dim+1||u<-1||u>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(u+1)*this.stride+(l+1)}static pack(l,u){const p=[0,0,0,0],x=DR.getUnpackVector(u);let b=Math.floor((l+x[3])/x[2]);return p[2]=b%256,b=Math.floor(b/256),p[1]=b%256,b=Math.floor(b/256),p[0]=b,p}getPixels(){return new rQ({width:this.stride,height:this.stride},this.pixels)}backfillBorder(l,u,p){if(this.dim!==l.dim)throw new Error("dem dimension mismatch");let x=u*this.dim,b=u*this.dim+this.dim,T=p*this.dim,k=p*this.dim+this.dim;switch(u){case-1:x=b-1;break;case 1:b=x+1}switch(p){case-1:T=k-1;break;case 1:k=T+1}const P=-u*this.dim,O=-p*this.dim;for(let $=T;$=1;p--){const x=p===1?1:0,b=p===2?1:0;for(let T=0;T>>1^-(1&h[l]);return h}function IMe(h,l){switch(l){case"uint32":return h;case"uint16":for(let u=0;u>4|(61440&p)>>8|(240&x)<<4|61440&x,h[u+1]=15&p|(3840&p)>>4|(15&x)<<8|(3840&x)<<4}return h;case"uint8":for(let u=0;u>6|(192&x)>>4|(192&b)>>2|192&T,h[u+1]=(48&p)>>4|(48&x)>>2|48&b|(48&T)<<2,h[u+2]=(12&p)>>2|12&x|(12&b)<<2|(12&T)<<4,h[u+3]=3&p|(3&x)<<2|(3&b)<<4|(3&T)<<6}return h;default:throw new Error(`Invalid pixel format, "${l}"`)}}jr(DR,"DEMData"),jr(_te,"DemMinMaxQuadTree",{omit:["dem"]});var gd=Uint8Array,q2=Uint16Array,PMe=Int32Array,wte=new gd([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]),Ste=new gd([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]),RMe=new gd([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Tte=function(h,l){for(var u=new q2(31),p=0;p<31;++p)u[p]=l+=1<>1|(21845&Fa)<<1;kte[Fa]=((65280&(Ww=(61680&(Ww=(52428&Ww)>>2|(13107&Ww)<<2))>>4|(3855&Ww)<<4))>>8|(255&Ww)<<8)>>1}var G2=function(h,l,u){for(var p=h.length,x=0,b=new q2(l);x>P]=O;return T},H2=new gd(288);for(Fa=0;Fa<144;++Fa)H2[Fa]=8;for(Fa=144;Fa<256;++Fa)H2[Fa]=9;for(Fa=256;Fa<280;++Fa)H2[Fa]=7;for(Fa=280;Fa<288;++Fa)H2[Fa]=8;var Ate=new gd(32);for(Fa=0;Fa<32;++Fa)Ate[Fa]=5;var DMe=G2(H2,9),OMe=G2(Ate,5),lz=function(h){for(var l=h[0],u=1;ul&&(l=h[u]);return l},ef=function(h,l,u){var p=l/8|0;return(h[p]|h[p+1]<<8)>>(7&l)&u},cz=function(h,l){var u=l/8|0;return(h[u]|h[u+1]<<8|h[u+2]<<16)>>(7&l)},FMe=function(h){return(h+7)/8|0},BMe=["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"],tf=function(h,l,u){var p=new Error(l||BMe[h]);if(p.code=h,Error.captureStackTrace&&Error.captureStackTrace(p,tf),!u)throw p;return p},$Me=new gd(0),zMe=typeof TextDecoder<"u"&&new TextDecoder;try{zMe.decode($Me,{stream:!0})}catch{}const UMe={gzip_data:"gzip"};class ah extends Error{constructor(l){super(l),this.name="MRTError"}}const VMe={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Nte={uint32:1,uint16:2,uint8:4},qMe={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let uz;class OR{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 ah(`Layer '${l}' not found`);return u}getHeaderLength(l){const u=new Uint8Array(l),p=new DataView(l);if(u[0]!==13)throw new ah("File is not a valid MRT.");return p.getUint32(1,!0)}parseHeader(l){const u=new Uint8Array(l),p=this.getHeaderLength(l);if(u.length= ${p} but got buffer of length ${u.length}`);const x=new uz(u.subarray(0,p)).readFields(bMe,{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 ah(`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 Cte(b,{cacheSize:this._cacheSize});return this}createDecodingTask(l){const u=[],p=this.getLayer(l.layerName);for(let x of l.blockIndices){const b=p.dataIndex[x],T=b.firstByte-l.firstByte,k=b.lastByte-l.firstByte;if(p._blocksInProgress.has(x))continue;const P={layerName:p.name,firstByte:T,lastByte:k,pixelFormat:p.pixelFormat,blockIndex:x,blockShape:[b.bands.length].concat(p.bandShape),buffer:p.buffer,codec:b.codec.codec,filters:b.filters.map(O=>O.filter)};p._blocksInProgress.add(x),u.push(P)}return new Ite(u,()=>{u.forEach(x=>p._blocksInProgress.delete(x.blockIndex))},(x,b)=>{if(u.forEach(T=>p._blocksInProgress.delete(T.blockIndex)),x)throw x;b.forEach(T=>{this.getLayer(T.layerName).processDecodedData(T)})})}}class Cte{constructor({version:l,name:u,units:p,tileSize:x,pixelFormat:b,buffer:T,dataIndex:k},P){if(this.version=l,this.version!==1)throw new ah(`Cannot parse raster layer encoded with MRT version ${l}`);this.name=u,this.units=p,this.tileSize=x,this.buffer=T,this.pixelFormat=VMe[b],this.dataIndex=k,this.bandShape=[x+2*T,x+2*T,Nte[this.pixelFormat]],this._decodedBlocks=new MR(P?P.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Nte[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:l})=>l).flat()}processDecodedData(l){const u=l.blockIndex.toString();this._decodedBlocks.get(u)||this._decodedBlocks.put(u,l.data)}getBlockForBand(l){let u=0;switch(typeof l){case"string":for(const[p,x]of this.dataIndex.entries()){for(const[b,T]of x.bands.entries())if(T===l)return{bandIndex:u+b,blockIndex:p,blockBandIndex:b};u+=x.bands.length}break;case"number":for(const[p,x]of this.dataIndex.entries()){if(l>=u&&lthis.cacheSize)throw new ah(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:u,lastByte:p,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:p}=this.getBlockForBand(l);if(u<0)throw new ah(`Band not found: ${JSON.stringify(l)}`);const x=this._decodedBlocks.get(u.toString());if(!x)throw new ah(`Data for band ${JSON.stringify(l)} of layer "${this.name}" not decoded.`);const b=this.dataIndex[u],T=this.bandShape.reduce((O,$)=>O*$,1),k=p*T,P=x.subarray(k,k+T);return{data:P,bytes:new Uint8Array(P.buffer).subarray(P.byteOffset,P.byteOffset+P.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}OR.setPbf=function(h){uz=h};class Ite{constructor(l,u,p){this.tasks=l,this._onCancel=u,this._onComplete=p,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(l,u){this._finalized||(this._onComplete(l,u),this._finalized=!0)}}OR.performDecoding=function(h,l){const u=new Uint8Array(h);return Promise.all(l.tasks.map(p=>{const{layerName:x,firstByte:b,lastByte:T,pixelFormat:k,blockShape:P,blockIndex:O,filters:$,codec:V}=p,G=u.subarray(b,T+1),Y=new Uint32Array(P[0]*P[1]*P[2]);let X;if(V!=="gzip_data")throw new ah(`Unhandled codec: ${V}`);return X=function(te,se){if(!globalThis.DecompressionStream&&se==="gzip_data")return Promise.resolve((Ae=function(ze){ze[0]==31&&ze[1]==139&&ze[2]==8||tf(6,"invalid gzip data");var He=ze[3],Ve=10;4&He&&(Ve+=2+(ze[10]|ze[11]<<8));for(var qe=(He>>3&1)+(He>>4&1);qe>0;qe-=!ze[Ve++]);return Ve+(2&He)}(ae=te),Ae+8>ae.length&&tf(6,"invalid gzip data"),function(ze,He,Ve,qe){var bt=ze.length;if(!bt||He.f&&!He.l)return Ve||new gd(0);var Et=!Ve,It=Et||He.i!=2,Dt=He.i;Et&&(Ve=new gd(3*bt));var Pt=function(Ei){var gl=Ve.length;if(Ei>gl){var lo=new gd(Math.max(2*gl,Ei));lo.set(Ve),Ve=lo}},Ht=He.f||0,vt=He.p||0,Rt=He.b||0,Bt=He.l,Yt=He.d,tr=He.m,wr=He.n,ur=8*bt;do{if(!Bt){Ht=ef(ze,vt,1);var cr=ef(ze,vt+1,3);if(vt+=3,!cr){var rr=ze[(ms=FMe(vt)+4)-4]|ze[ms-3]<<8,_r=ms+rr;if(_r>bt){Dt&&tf(0);break}It&&Pt(Rt+rr),Ve.set(ze.subarray(ms,_r),Rt),He.b=Rt+=rr,He.p=vt=8*_r,He.f=Ht;continue}if(cr==1)Bt=DMe,Yt=OMe,tr=9,wr=5;else if(cr==2){var Rr=ef(ze,vt,31)+257,Wr=ef(ze,vt+10,15)+4,Dr=Rr+ef(ze,vt+5,31)+1;vt+=14;for(var fn=new gd(Dr),Wn=new gd(19),mn=0;mn>4)<16)fn[mn++]=ms;else{var $s=0,vi=0;for(ms==16?(vi=3+ef(ze,vt,3),vt+=2,$s=fn[mn-1]):ms==17?(vi=3+ef(ze,vt,7),vt+=3):ms==18&&(vi=11+ef(ze,vt,127),vt+=7);vi--;)fn[mn++]=$s}}var Xa=fn.subarray(0,Rr),_i=fn.subarray(Rr);tr=lz(Xa),wr=lz(_i),Bt=G2(Xa,tr),Yt=G2(_i,wr)}else tf(1);if(vt>ur){Dt&&tf(0);break}}It&&Pt(Rt+131072);for(var Ri=(1<>4;if((vt+=15&$s)>ur){Dt&&tf(0);break}if($s||tf(2),Oo<256)Ve[Rt++]=Oo;else{if(Oo==256){Li=vt,Bt=null;break}var Qa=Oo-254;Oo>264&&(Qa=ef(ze,vt,(1<<(Gi=wte[mn=Oo-257]))-1)+Ete[mn],vt+=Gi);var An=Yt[cz(ze,vt)&aa],Ol=An>>4;if(An||tf(3),vt+=15&An,_i=MMe[Ol],Ol>3){var Gi=Ste[Ol];_i+=cz(ze,vt)&(1<ur){Dt&&tf(0);break}It&&Pt(Rt+131072);var oo=Rt+Qa;if(Rt<_i){var Fl=0-_i,Fo=Math.min(_i,oo);for(Fl+Rt<0&&tf(3);RtEi.length)&&(lo=Ei.length),new gd(Ei.subarray(0,lo))}(Ve,0,Rt):Ve.subarray(0,Rt)}(ae.subarray(Ae,-8),{i:2},new gd(((ue=ae)[(Te=ue.length)-4]|ue[Te-3]<<8|ue[Te-2]<<16|ue[Te-1]<<24)>>>0),fe)));var ae,fe,ue,Te,Ae;const Ie=UMe[se];if(!Ie)throw new Error(`Unhandled codec: ${se}`);const We=new globalThis.DecompressionStream(Ie);return new Response(new Blob([te]).stream().pipeThrough(We)).arrayBuffer().then(ze=>new Uint8Array(ze))}(G,V).then(te=>(function(se,ae){se.readFields(kMe,ae)}(new uz(te),Y),new qMe[k](Y.buffer))),X.then(te=>{for(let se=$.length-1;se>=0;se--)switch($[se]){case"delta_filter":NMe(te,P);break;case"zigzag_filter":CMe(te);break;case"bitshuffle_filter":IMe(te,k);break;default:throw new ah(`Unhandled filter "${$[se]}"`)}return{layerName:x,blockIndex:O,data:te}}).catch(te=>{throw te})}))},jr(Ite,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),jr(OR,"MapboxRasterTile"),jr(Cte,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const Pte=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class dz{static from(l){if(!(l instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[u,p]=new Uint8Array(l,0,2);if(u!==219)throw new Error("Data does not appear to be in a KDBush format.");const x=p>>4;if(x!==1)throw new Error(`Got v${x} data when expected v1.`);const b=Pte[15&p];if(!b)throw new Error("Unrecognized array type.");const[T]=new Uint16Array(l,2,1),[k]=new Uint32Array(l,4,1);return new dz(k,T,b,l)}constructor(l,u=64,p=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=p,this.IndexArrayType=l<65536?Uint16Array:Uint32Array;const b=Pte.indexOf(this.ArrayType),T=2*l*this.ArrayType.BYTES_PER_ELEMENT,k=l*this.IndexArrayType.BYTES_PER_ELEMENT,P=(8-k%8)%8;if(b<0)throw new Error(`Unexpected typed array class: ${p}.`);x&&x instanceof ArrayBuffer?(this.data=x,this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+P,2*l),this._pos=2*l,this._finished=!0):(this.data=new ArrayBuffer(8+T+k+P),this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+P,2*l),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+b]),new Uint16Array(this.data,2,1)[0]=u,new Uint32Array(this.data,4,1)[0]=l)}add(l,u){const p=this._pos>>1;return this.ids[p]=p,this.coords[this._pos++]=l,this.coords[this._pos++]=u,p}finish(){const l=this._pos>>1;if(l!==this.numItems)throw new Error(`Added ${l} items when expected ${this.numItems}.`);return hz(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(l,u,p,x){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:T,nodeSize:k}=this,P=[0,b.length-1,0],O=[];for(;P.length;){const $=P.pop()||0,V=P.pop()||0,G=P.pop()||0;if(V-G<=k){for(let se=G;se<=V;se++){const ae=T[2*se],fe=T[2*se+1];ae>=l&&ae<=p&&fe>=u&&fe<=x&&O.push(b[se])}continue}const Y=G+V>>1,X=T[2*Y],te=T[2*Y+1];X>=l&&X<=p&&te>=u&&te<=x&&O.push(b[Y]),($===0?l<=X:u<=te)&&(P.push(G),P.push(Y-1),P.push(1-$)),($===0?p>=X:x>=te)&&(P.push(Y+1),P.push(V),P.push(1-$))}return O}within(l,u,p){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:x,coords:b,nodeSize:T}=this,k=[0,x.length-1,0],P=[],O=p*p;for(;k.length;){const $=k.pop()||0,V=k.pop()||0,G=k.pop()||0;if(V-G<=T){for(let se=G;se<=V;se++)Lte(b[2*se],b[2*se+1],l,u)<=O&&P.push(x[se]);continue}const Y=G+V>>1,X=b[2*Y],te=b[2*Y+1];Lte(X,te,l,u)<=O&&P.push(x[Y]),($===0?l-p<=X:u-p<=te)&&(k.push(G),k.push(Y-1),k.push(1-$)),($===0?l+p>=X:u+p>=te)&&(k.push(Y+1),k.push(V),k.push(1-$))}return P}}function hz(h,l,u,p,x,b){if(x-p<=u)return;const T=p+x>>1;Rte(h,l,T,p,x,b),hz(h,l,u,p,T-1,1-b),hz(h,l,u,T+1,x,1-b)}function Rte(h,l,u,p,x,b){for(;x>p;){if(x-p>600){const O=x-p+1,$=u-p+1,V=Math.log(O),G=.5*Math.exp(2*V/3),Y=.5*Math.sqrt(V*G*(O-G)/O)*($-O/2<0?-1:1);Rte(h,l,u,Math.max(p,Math.floor(u-$*G/O+Y)),Math.min(x,Math.floor(u+(O-$)*G/O+Y)),b)}const T=l[2*u+b];let k=p,P=x;for(W2(h,l,p,u),l[2*x+b]>T&&W2(h,l,p,x);kT;)P--}l[2*p+b]===T?W2(h,l,p,P):(P++,W2(h,l,P,x)),P<=u&&(p=P+1),u<=P&&(x=P-1)}}function W2(h,l,u,p){fz(h,u,p),fz(l,2*u,2*p),fz(l,2*u+1,2*p+1)}function fz(h,l,u){const p=h[l];h[l]=h[u],h[u]=p}function Lte(h,l,u,p){const x=h-u,b=l-p;return x*x+b*b}a.$=dy,a.A=class{constructor(h,l,u){this.target=h,this.parent=l,this.mapId=u,this.callbacks={},this.cancelCallbacks={},mt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new JLe}send(h,l,u,p,x=!1,b){const T=Math.round(1e18*Math.random()).toString(36).substring(0,10);u&&(u.metadata=b,this.callbacks[T]=u);const k=new Set;return this.target.postMessage({id:T,type:h,hasCallback:!!u,targetMapId:p,mustQueue:x,sourceMapId:this.mapId,data:qh(l,k)},k),{cancel:()=>{u&&delete this.callbacks[T],this.target.postMessage({id:T,type:"",targetMapId:p,sourceMapId:this.mapId})}}}receive(h){const l=h.data;if(!l)return;const u=l.id;if(u&&(!l.targetMapId||this.mapId===l.targetMapId))if(l.type===""){const p=this.cancelCallbacks[u];delete this.cancelCallbacks[u],p&&p.cancel()}else if(l.mustQueue||wn(self)){const p=this.callbacks[u],x=this.scheduler.add(()=>this.processTask(u,l),p&&p.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(nm(l.error)):u(null,nm(l.data)))}else{const u=new Set,p=l.hasCallback?(b,T)=>{this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:b?qh(b):null,data:qh(T,u)},u)}:()=>{},x=nm(l.data);if(this.parent[l.type])this.parent[l.type](l.sourceMapId,x,p);else if(this.parent.getWorkerSource){const b=l.type.split("."),{source:T,scope:k}=x;this.parent.getWorkerSource(l.sourceMapId,{type:b[0],source:T,scope:k,uid:0})[b[1]](x,p)}else p(new Error(`Could not find function ${l.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},a.B=ry,a.C=ud,a.D=Mu,a.E=F0,a.F=Lp,a.G=2,a.H=C2,a.I=Tc,a.J=QJ,a.K=Mb,a.L=xP,a.M=V0,a.N=q0,a.O=nw,a.P=Ft,a.Q=rw,a.R=D0,a.S=yE,a.T=dm,a.U=cv,a.V=NR,a.W=pw,a.X=rm,a.Y=vE,a.Z=Qd,a._=kp,a.a=function(h){return Vn.API_CDN_URL_REGEX.test(h)},a.a$=dR,a.a0=Ya,a.a1=G0,a.a2=Db,a.a3=Wj,a.a4=FE,a.a5=class extends NR{},a.a6=xE,a.a7=tP,a.a8=at,a.a9=function(h){const l=h.value;return l?Db(l)?ez(l,!0)?[]:[new NR(h.key,l,`invalid url "${l}"`)]:[new NR(h.key,l,`string expected, "${V0(l)}" found`)]:[]},a.aA=EJ,a.aB=function(h){let l=1/0,u=1/0,p=-1/0,x=-1/0;for(const b of h)l=Math.min(l,b.x),u=Math.min(u,b.y),p=Math.max(p,b.x),x=Math.max(x,b.y);return{min:new Ft(l,u),max:new Ft(p,x)}},a.aC=pe,a.aD=D,a.aE=Kt,a.aF=Me,a.aG=Ql,a.aH=Ot,a.aI=br,a.aJ=function(h,l){const u={};for(let p=0;p=0?l.slice(u+1):""}catch{return""}},a.aN=class{constructor(h){this.entries={},this.scheduler=h}request(h,l,u,p){const x=this.entries[h]=this.entries[h]||{callbacks:[]};if(x.result){const[b,T]=x.result;return this.scheduler?this.scheduler.add(()=>{p(b,T)},l):p(b,T),()=>{}}return x.callbacks.push(p),x.cancel||(x.cancel=u((b,T)=>{x.result=[b,T];for(const k of x.callbacks)this.scheduler?this.scheduler.add(()=>{k(b,T)},l):k(b,T);setTimeout(()=>delete this.entries[h],3e3)})),()=>{x.result||(x.callbacks=x.callbacks.filter(b=>b!==p),x.callbacks.length||(x.cancel(),delete this.entries[h]))}}},a.aO=function(h,l,u){const p=JSON.stringify(h.request);return h.data&&(this.deduped.entries[p]={result:[null,h.data]}),this.deduped.request(p,{type:"parseTile",renderSourceType:h.renderSourceType,zoom:h.tileZoom},x=>{const b=ey(h.request,(T,k,P)=>{T?qj(T)?x(null,null):x(T):k&&x(null,{rawData:k,vectorTile:u?void 0:new ds(new dR(k)),responseHeaders:new Map(P.entries())})});return()=>{b.cancel(),x(null,null)}},l)},a.aP=function(h){return h?{cacheControl:h.get("cache-control"),expires:h.get("expires")}:{cacheControl:void 0,expires:void 0}},a.aQ=function(h){$j++,$j>Eb&&(h.getActor().send("enforceCacheSizeLimit",jb),$j=0)},a.aR=Dl,a.aS=Ree,a.aT=zee,a.aU=Je,a.aV=Pee,a.aW=function(h,l){const u=document.createElement("video");u.muted=!0,u.onloadstart=function(){l(null,u)};for(let p=0;p{}}},a.aX=j2,a.aY=Bv,a.aZ=mt,a.a_=OR,a.aa=mw,a.ab=fi,a.ac=sr,a.ad=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return vr(h.expression.evaluate(l))}interpolate(h,l,u){return{x:sn(h.x,l.x,u),y:sn(h.y,l.y,u),z:sn(h.z,l.z,u),azimuthal:sn(h.azimuthal,l.azimuthal,u),polar:sn(h.polar,l.polar,u)}}},a.ae=fs,a.af=Np,a.ag=Pr,a.ah=or,a.ai=Le,a.aj=Fe,a.ak=Wh,a.al=zp,a.am=sn,a.an=fr,a.ao=dd,a.ap=Xn,a.aq=as,a.ar=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return function([u,p]){const x=vr([1,u,p]);return{x:x.x,y:x.y,z:x.z}}(h.expression.evaluate(l))}interpolate(h,l,u){return{x:sn(h.x,l.x,u),y:sn(h.y,l.y,u),z:sn(h.z,l.z,u)}}},a.as=function(h,l,u=0,p=!0){const x=new Ft(u,u),b=h.sub(x),T=l.add(x),k=[b,new Ft(T.x,b.y),T,new Ft(b.x,T.y)];return p&&k.push(b.clone()),k},a.at=function(h,l){const u=[];for(let p=0;pthis.buckets[V].layers.some(G=>T.has(G.fqid))),P=Object.keys(this.buckets).some(V=>this.buckets[V].layers.some(G=>G.hasTransition&&G.hasTransition())),O=this._firstPrepareComplete&&b!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(l));const $=this._lastUpdatedBrightness!==p;this._lastAvailableImagesCount=b,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||p||this._hasAppearances||k||P||O)&&(!(this._hasAppearances||k||P||O)&&this._lastUpdatedBrightness&&p&&Math.abs(this._lastUpdatedBrightness-p)<.001||(this.updateBuckets(l,$,void 0,O||k||P,T,x),this._lastUpdatedBrightness=p))}evaluateQueryRenderedFeaturePadding(){let h=0;for(const l in this.buckets){const u=this.buckets[l];u.evaluateQueryRenderedFeaturePadding&&(h=Math.max(h,u.evaluateQueryRenderedFeaturePadding()))}return h}queryRenderedFeatures(h,l,u,p,x,b,T){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const k=this.evaluateQueryRenderedFeaturePadding(),P=function(O,$){const V=J([],[.5*O.width,.5*-O.height,1]);return F(V,V,[1,-1,0]),D(V,V,O.calculateProjMatrix($.toUnwrapped())),Float32Array.from(V)}(x,this.tileID);return this.latestFeatureIndex.query(h,{tilespaceGeometry:l,pixelPosMatrix:P,transform:p,availableImages:u,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:k,scope:T})}querySourceFeatures(h,l){const u=this.latestFeatureIndex;if(!u||!u.rawTileData)return;const p=u.loadVTLayers(),x=l?l.sourceLayer:"",b=p._geojsonTileLayer||p[x];if(!b)return;const T=gw(l&&l.filter),{z:k,x:P,y:O}=this.tileID.canonical,$={z:k,x:P,y:O};for(let V=0;Vu)p=!1;else if(l)if(this.expirationTimeu.appearances&&u.appearances.length>0))return!0;return!1}updateBuckets(h,l,u,p,x,b){if(!this.latestFeatureIndex||!h.style)return;const T=b||h.style.listImages(),k=h.style.getBrightness(),P=x||new Set;for(const O in this.buckets){if(!h.style.hasLayer(O))continue;const $=this.buckets[O],V=$.layers[0],G=V.sourceLayer||"_geojsonTileLayer",Y=h.style.getLayerSourceCache(V),X=$.layers.some(Ae=>P.has(Ae.fqid)),te=(p||X)&&$ instanceof Jh?h.style.getOwnLayer(O):void 0;let se=u&&u[G]||{};Y&&!u&&(se=Y._state.getState(G,void 0));const ae=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},fe=Object.keys(se).length>0&&!l;$.hasAppearances=$.layers.some(Ae=>Ae.appearances&&Ae.appearances.length>0);const ue=fe?$.stateDependentLayers:$.layers;if(fe&&$.stateDependentLayers.length!==0||l||X||p){const Ae=this.latestFeatureIndex.loadVTLayers()[G];if($.update(se,Ae,T,ae,ue,l,k,this.tileID.canonical),(p||X)&&!l&&$ instanceof Jh&&te&&te.type==="symbol"){const Ie=$;Ie.text&&Ie.text.uboBinder&&Ie.text.uboBinder.updateDynamicExpressions(te,Ae,this.tileID.canonical,T,se,k),Ie.icon&&Ie.icon.uboBinder&&Ie.icon.uboBinder.updateDynamicExpressions(te,Ae,this.tileID.canonical,T,se,k)}if($ instanceof Jh){const Ie=$,We=h.context;Ie.text&&Ie.text.uboBinder&&Ie.text.uboBinder.upload(We),Ie.icon&&Ie.icon.uboBinder&&Ie.icon.uboBinder.upload(We)}}if(fe&&$.stateDependentLayers.length!==0||l||$.hasAppearances){const Ae={zoom:h.transform.zoom,pitch:h.transform.pitch,brightness:h.style.getBrightness()||0,worldview:h.worldview},Ie=$.updateAppearances(this.tileID.canonical,se,T,Ae,h.imageManager,fe&&$.stateDependentLayers.length!==0);if(Ie&&Ie.hasUboChanges){const We=h.context;$ instanceof Jh&&$.text&&$.text.uboBinder&&$.text.uboBinder.upload(We),$ instanceof Jh&&$.icon&&$.icon.uboBinder&&$.icon.uboBinder.upload(We)}}($ instanceof uR||$ instanceof GP)&&h._terrain&&h._terrain.enabled&&Y&&$.uploadPending()&&h._terrain._clearRenderCacheForTile(Y.id,this.tileID);const Te=h&&h.style&&h.style.getOwnLayer(O);Te&&(this.queryPadding=Math.max(this.queryPadding,Te.queryRadius($)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;te--){const se=4*te,ae=Ry[se+0],fe=Ry[se+1],ue=Ry[se+2],Te=Ry[se+3],Ae=ae+ue>>1,Ie=fe+Te>>1,We=Ae+Ie-fe,ze=Ie+ae-Ae,He=fe*hm+ae,Ve=Te*hm+ue,qe=Ie*hm+Ae,bt=Math.hypot((fm[2*He+0]+fm[2*Ve+0])/2-fm[2*qe+0],(fm[2*He+1]+fm[2*Ve+1])/2-fm[2*qe+1])>=16;Ly[qe]=Ly[qe]||(bt?1:0),te<1022&&(Ly[qe]=Ly[qe]||Ly[(fe+ze>>1)*hm+(ae+We>>1)]||Ly[(Te+ze>>1)*hm+(ue+We>>1)])}const $=new Mo,V=new Pi;let G=0;function Y(te,se){const ae=se*hm+te;return IR[ae]===0&&($.emplaceBack(fm[2*ae+0],fm[2*ae+1],te*fr/ih,se*fr/ih),IR[ae]=++G),IR[ae]-1}function X(te,se,ae,fe,ue,Te){const Ae=te+ae>>1,Ie=se+fe>>1;if(Math.abs(te-ue)+Math.abs(se-Te)>1&&Ly[Ie*hm+Ae])X(ue,Te,te,se,Ae,Ie),X(ae,fe,ue,Te,Ae,Ie);else{const We=Y(te,se),ze=Y(ae,fe),He=Y(ue,Te);V.emplaceBack(We,ze,He)}}return X(0,0,ih,ih,ih,0),X(ih,ih,0,0,0,ih),{vertices:$,indices:V}}(this.tileID.canonical,l);p=b.vertices,x=b.indices}else{p=new Mo,x=new Pi;for(const{x:T,y:k}of u)p.emplaceBack(T,k,0,0);const b=Iw(p.int16.subarray(0,4*p.length),void 0,4);for(let T=0;T0&&(T=M(new Float64Array(16),l.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(h,p,l,x,T,b),this._makeGlobeTileDebugTextBuffer(h,p,l,x,T,b)}_globePoint(h,l,u,p,x,b,T){let k=l2(h,l,u);if(b){const P=1<.5?G=-1:V<-.5&&(G=1);let Y=(h/fr+u.x)/P+G,X=(l/fr+u.y)/P;Y=(Y-O)*p._pixelsPerMercatorPixel+O,X=(X-$)*p._pixelsPerMercatorPixel+$;const te=[Y*p.worldSize,X*p.worldSize,0];or(te,te,b),k=$p(k,te,T)}return or(k,k,x)}_makeGlobeTileDebugBorderBuffer(h,l,u,p,x,b){const T=new Ec,k=new Op,P=new rh,O=(V,G,Y,X,te)=>{const se=(Y-V)/(te-1),ae=(X-G)/(te-1),fe=T.length;for(let ue=0;ueO*V+G;for(let V=0;V1)return!1;const u=l.getSource().maxzoom,p=1<1)return l;const x=p.getSource().maxzoom,b=1<{const k=this.getAtTileOffset(h,x,b,T),P=p.upVector(h.canonical,x.x,x.y);return Ue(P,P,k*p.upVectorScale(h.canonical,l,u).metersToTile),P}}getForTilePoints(h,l,u,p){if(this.isUsingMockSource())return!1;const x=qw.create(this,h,p);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,p=l.tileID,x=1<0&&(p+=(h[x]-0)*(h[x]-0)),l[x]<0&&(p+=(0-l[x])*(0-l[x]));return p},a.cL=function(h){return h*h*h*h*h},a.cM=pt,a.cN=45,a.cO=Aw,a.cP=function(h,l,u){const p=Math.sqrt(h*h+l*l+u*u),x=p>0?Math.acos(u/p)*yi:0;let b=h!==0||l!==0?Math.atan2(-l,-h)*yi+90:0;return b<0&&(b+=360),[p,b,x]},a.cQ=Se,a.cR=vr,a.cS=zt,a.cT=me,a.cU=ys,a.cV=ke,a.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)]},a.cX=cJ,a.cY=w$,a.cZ=mJ,a.c_=ez,a.ca=2,a.cb=7,a.cc=6,a.cd=xt,a.ce=ye,a.cf=we,a.cg=0,a.ch=1,a.ci=4,a.cj=5,a.ck=Cw,a.cl=kc,a.cm=dJ,a.cn=Nv,a.co=$X,a.cp=function(h,l,u,p,x,b,T,k,P){if(P.name==="globe")return $X(h,l,new Nv(u,p,x),!1);const O=Dv({z:u,x:p,y:x},P);return new ys([(b+O.x/O.scale)*l,l*(O.y/O.scale),T],[(b+O.x2/O.scale)*l,l*(O.y2/O.scale),k])},a.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},a.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},a.cs=function(h){const l=Math.round((h+45+360)%360/90)%4;return _c[l]},a.ct=Nt,a.cu=Zt,a.cv=6,a.cw=function(h){const l=I(new Float64Array(16));D(l,h.pixelMatrix,h.globeMatrix);const u=[0,$e,0],p=[0,Ke,0];return or(u,u,l),or(p,p,l),[u[0]>0&&u[0]<=h.width&&u[1]>0&&u[1]<=h.height&&!VB(h,new Je(h.center.lat,90)),p[0]>0&&p[0]<=h.width&&p[1]>0&&p[1]<=h.height&&!VB(h,new Je(h.center.lat,-90))]},a.cx=function(h,l){const{scale:u}=h.tileTransform,p=u*fr/(h.tileSize*Math.pow(2,l.zoom-h.tileID.overscaledZ+h.tileID.canonical.z));return function(x,b,T){var k=b[1],P=b[2],O=b[3],$=T[0],V=T[1];return x[0]=b[0]*$,x[1]=k*$,x[2]=P*V,x[3]=O*V,x}(new Float32Array(4),l.inverseAdjustmentMatrix,[p,p])},a.cy=sR,a.cz=de,a.d=function(h){return Vn.API_TILEJSON_REGEX.test(h)},a.d$=JIe,a.d0=Ti,a.d1=class{static calculate(h,l,u){const p=new Set,x=new Map,b=new Set,T=new Set;for(const P of Object.values(h))for(const[O,$]of Object.entries(P.floors)){b.add(O),$.isDefault&&T.add(O),$.conflicts&&x.set(O,$.conflicts);const V=O===l,G=$.connections&&l&&$.connections.has(l);(V||G)&&p.add(O)}const k=P=>{const O=x.get(P)||new Set;for(const $ of p)if((x.get($)||new Set).has(P)||O.has($))return!0;return!1};if(u)for(const P of u)b.has(P)&&(k(P)||p.add(P));for(const P of T)p.has(P)||k(P)||p.add(P);return p}},a.d2=pR,a.d3=z$,a.d4=us,a.d5=function(){return{API_URL:Vn.API_URL,DRACO_URL:Vn.DRACO_URL,MESHOPT_URL:Vn.MESHOPT_URL,MESHOPT_SIMD_URL:Vn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Vn.BUILDING_GEN_URL}},a.d6=pP,a.d7=Fj,a.d8=Kf,a.d9=gr,a.dA=DP,a.dB=Ec,a.dC=Pi,a.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]},a.dE=v,a.dF=function(h,l){var u=Math.sin(l),p=Math.cos(l);return h[0]=p,h[1]=u,h[2]=0,h[3]=-u,h[4]=p,h[5]=0,h[6]=0,h[7]=0,h[8]=1,h},a.dG=Tr,a.dH=UX,a.dI=Un,a.dJ=ni,a.dK=Q$,a.dL=function(h,l){const u=[0,0,0];return or(u,u,c2(lm(l.canonical))),or(u,u,h),u},a.dM=h=>({u_matrix:new d(h),u_texsize:new $u(h),u_pixels_to_tile_units:new E(h),u_device_pixel_ratio:new wa(h),u_width_scale:new wa(h),u_floor_width_scale:new wa(h),u_image:new kv(h),u_units_to_pixels:new $u(h),u_tile_units_to_pixels:new wa(h),u_alpha_discard_threshold:new wa(h),u_trim_offset:new $u(h),u_trim_fade_range:new $u(h),u_trim_gradient_mix_range:new $u(h),u_trim_color:new Aw(h),u_zbias_factor:new wa(h),u_tile_to_meter:new wa(h),u_ground_shadow_factor:new Av(h),u_pattern_transition:new wa(h)}),a.dN=h=>({u_matrix:new d(h),u_pixels_to_tile_units:new E(h),u_device_pixel_ratio:new wa(h),u_width_scale:new wa(h),u_floor_width_scale:new wa(h),u_units_to_pixels:new $u(h),u_dash_image:new kv(h),u_gradient_image:new kv(h),u_image_height:new wa(h),u_texsize:new $u(h),u_tile_units_to_pixels:new wa(h),u_alpha_discard_threshold:new wa(h),u_trim_offset:new $u(h),u_trim_fade_range:new $u(h),u_trim_gradient_mix_range:new $u(h),u_trim_color:new Aw(h),u_zbias_factor:new wa(h),u_tile_to_meter:new wa(h),u_ground_shadow_factor:new Av(h)}),a.dO=h=>({u_camera_to_center_distance:new wa(h),u_extrude_scale:new E(h),u_device_pixel_ratio:new wa(h),u_matrix:new d(h),u_inv_rot_matrix:new d(h),u_merc_center:new $u(h),u_tile_id:new Av(h),u_zoom_transition:new wa(h),u_up_dir:new Av(h),u_emissive_strength:new wa(h)}),a.dP=ZE,a.dQ=QRe,a.dR=class{constructor(h,l,u,p){this.context=h,this.format=p,this.size=u,this.texture=h.gl.createTexture();const[x,b,T]=this.size,{gl:k}=h;k.bindTexture(k.TEXTURE_3D,this.texture),h.pixelStoreUnpackFlipY.set(!1),h.pixelStoreUnpack.set(1),h.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in l&&l.data&&k.texImage3D(k.TEXTURE_3D,0,this.format,x,b,T,0,p$(this.format),g$(this.format),l.data)}bind(h,l){const{context:u}=this,{gl:p}=u;p.bindTexture(p.TEXTURE_3D,this.texture),h!==this.minFilter&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MAG_FILTER,h),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MIN_FILTER,h),this.minFilter=h),l!==this.wrapS&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_S,l),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_T,l),this.wrapS=l)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}},a.dS=HX,a.dT=(h,l,u,p,x,b)=>{const T=h.transform,k=T.projection.name==="globe";let P;if(b.paint.get("circle-pitch-alignment")==="map")if(k){const $=UX(T.zoom,l.canonical)*T._pixelsPerMercatorPixel;P=Float32Array.from([$,0,0,$])}else P=T.calculatePixelsToTileUnitsMatrix(u);else P=new Float32Array([T.pixelsToGLUnits[0],0,0,T.pixelsToGLUnits[1]]);const O={u_camera_to_center_distance:h.transform.getCameraToCenterDistance(T.projection),u_matrix:h.translatePosMatrix(l.projMatrix,u,b.paint.get("circle-translate"),b.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Zl.devicePixelRatio,u_extrude_scale:P,u_inv_rot_matrix:iPe,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:b.paint.get("circle-emissive-strength")};if(k){O.u_inv_rot_matrix=p,O.u_merc_center=x,O.u_tile_id=[l.canonical.x,l.canonical.y,1<{const $=h.transform,V=$.pitch<15?kJ(.07,.7,pe((14-$.zoom)/5,0,1)):.07,G=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:NJ(h,l,u,p),u_texsize:l.imageAtlasTexture?l.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:$.calculatePixelsToTileUnitsMatrix(l),u_device_pixel_ratio:x,u_width_scale:b,u_floor_width_scale:T,u_image:0,u_tile_units_to_pixels:AJ(l,$),u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:k,u_trim_fade_range:u.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:u.paint.get("line-trim-color").toPremultipliedRenderColor(G?null:u.lut).toArray01(),u_zbias_factor:V,u_tile_to_meter:zt(l.tileID.canonical,0),u_ground_shadow_factor:P,u_pattern_transition:O}},a.dX=(h,l,u,p,x,b,T,k,P,O)=>{const $=h.transform,V=$.calculatePixelsToTileUnitsMatrix(l),G=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Y=$.pitch<15?kJ(.07,.7,pe((14-$.zoom)/5,0,1)):.07;return{u_matrix:NJ(h,l,u,p),u_pixels_to_tile_units:V,u_device_pixel_ratio:b,u_width_scale:T,u_floor_width_scale:k,u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:x,u_texsize:IJ(u)&&l.lineAtlasTexture?l.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:AJ(l,h.transform),u_alpha_discard_threshold:0,u_trim_offset:P,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(G?null:u.lut).toArray01(),u_zbias_factor:Y,u_tile_to_meter:zt(l.tileID.canonical,0),u_ground_shadow_factor:O}},a.dY=it,a.dZ=u2,a.d_=jt,a.da=function(h){const l=h.indexOf(gv);return l>=0?h.slice(0,l):h},a.db=function(h){return h.indexOf(gv)>=0},a.dc=function(h){const l=h.lastIndexOf(gv);return l>=0?h.slice(l+1):""},a.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},a.de=function(h,l,u,p){return h.type==="custom"?new GLe(h,l):new ZLe[h.type](h,l,u,p)},a.df=Mt,a.dg=gw,a.dh=SP,a.di=class extends Fv{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}},a.dj=LE,a.dk=function(h){return h({pluginStatus:ml,pluginURL:Yc}),LE.on("pluginStateChange",h),h},a.dl=FB,a.dm=class extends Bu{constructor(h){super(h),this.current=g}set(h,l,u){if(this.fetchUniformLocation(h,l)){for(let p=0;p<9;p++)if(u[p]!==this.current[p]){this.current=u,this.gl.uniformMatrix3fv(this.location,!1,u);break}}}},a.dn=hl,a.dp=function(h,l,u){const p=zp(u.zoom),x=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return p===0&&!x&&!b},a.dq=function(h){const l=h.pixelsPerMeter,u=l/ut(1,h.center.lat),p=I(new Float64Array(16));return F(p,p,[h.point.x,h.point.y,0]),z(p,p,[u,u,l]),Float32Array.from(p)},a.dr=OP,a.ds=function(h){const l=80.051129;h=pe(h,-80.051129,l)/l*90;const u=Math.pow(Math.abs(Math.sin(Xn(h))),3);return Math.round(u*(Xe.length-1))},a.dt=function(h,l,u,p){const x=l.getNorth(),b=l.getSouth(),T=l.getWest(),k=l.getEast(),P=1<0){const X=180/p;j(Y,Y,[X/O+1,0,0,0,X/$+1,0,-.5*X/V,.5*X/G,1])}return Y[2]=P,Y[5]=h.x,Y[8]=h.y,Y},a.du=c2,a.dv=lm,a.dw=function(h,l,u){const p=I(new Float64Array(16)),x=(l/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,l=!1){const u=EQ(new Ft(0,0),new Ft(fr,fr),h),p=[];if(l&&!s$(u,this._globalClipBounds))return p;for(const x of this._activeRegions){if(x.hiddenByOverlap||!s$(u,x))continue;const b=zPe(x.min,x.max,h);p.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 p}setSources(h){this._setSources(h.map(l=>({getSourceId:()=>l.cache.id,getFootprints:()=>{const u=[];for(const p of l.cache.getVisibleCoordinates()){const x=l.cache.getTile(p).buckets[l.layer];x&&x.updateFootprints(p.toUnwrapped(),u)}return u},getOrder:()=>l.order,getClipMask:()=>l.clipMask,getClipScope:()=>l.clipScope})))}_addSource(h){const l=h.getFootprints();if(l.length===0)return;const u=h.getOrder(),p=h.getClipMask(),x=h.getClipScope();for(const b of l){if(!b.footprint)continue;const T=EQ(b.footprint.min,b.footprint.max,b.id);this._activeRegions.push({min:T.min,max:T.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:b.id,footprint:b.footprint,order:u,clipMask:p,clipScope:x})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((l,u)=>l.priority-u.priority||WP(l.min,u.min)||WP(l.max,u.max)||l.order-u.order||l.clipMask-u.clipMask||function(p,x){const b=(T,k)=>T+k;return p.length-x.length||p.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],p=this._prevRegions[l];h=u.priority!==p.priority||!jQ(u,p)||u.order!==p.order||u.clipMask!==p.clipMask||!jo(u.clipScope,p.clipScope),this._activeRegions[l].hiddenByOverlap=p.hiddenByOverlap,++l}}if(h){++this._updateTime;for(const u of this._activeRegions)u.order!==x2&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,u.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,u.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,u.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,u.max.y));const l=u=>{const p=this._activeRegions;if(u>=p.length)return u;const x=p[u].priority;for(;u1){let u=0,p=l(u);for(;u!==p;){let x=u;const b=u;for(;x!==p;){const T=this._activeRegions[x];T.hiddenByOverlap=!1;for(let k=0;k=0;l--)this._addSource(h[l]);this._computeReplacement()}},a.eH=Mo,a.eI=ER,a.eJ=Op,a.eK=x2,a.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 Ec,p=new Pi,x=[],b=h+1+2,T=l[0]+1,k=l[0]+1+(1+l.length),P=(O,$,V)=>{let G=O===b-1?O-2:O===0?O:O-1;return G+=V?24575:0,[G,$]};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},a.ec=FX,a.ed=zB,a.ee=Ou,a.ef=H,a.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},a.eh=Mp,a.ei=wv,a.ej=function(h,l,u,p,x){return pe((h-l)/(u-l)*(x-p)+p,p,x)},a.ek=Gn,a.el=function(h,l){var u=l[0],p=l[1],x=l[2],b=l[3],T=l[4],k=l[5],P=l[6],O=l[7],$=l[8],V=$*T-k*O,G=-$*b+k*P,Y=O*b-T*P,X=u*V+p*G+x*Y;return X?(h[0]=V*(X=1/X),h[1]=(-$*p+x*O)*X,h[2]=(k*p-x*T)*X,h[3]=G*X,h[4]=($*u-x*P)*X,h[5]=(-k*u+x*b)*X,h[6]=Y*X,h[7]=(-O*u+p*P)*X,h[8]=(T*u-p*b)*X,h):null},a.em=XI,a.en=2,a.eo=gt,a.ep=At,a.eq=ee,a.er=function(h,l){var u=new m(3);ee(u,l);var p=1/u[0],x=1/u[1],b=1/u[2],T=l[0]*p,k=l[1]*x,P=l[2]*b,O=l[4]*p,$=l[5]*x,V=l[6]*b,G=l[8]*p,Y=l[9]*x,X=l[10]*b,te=T+$+X,se=0;return te>0?(se=2*Math.sqrt(te+1),h[3]=.25*se,h[0]=(V-Y)/se,h[1]=(G-P)/se,h[2]=(k-O)/se):T>$&&T>X?(se=2*Math.sqrt(1+T-$-X),h[3]=(V-Y)/se,h[0]=.25*se,h[1]=(k+O)/se,h[2]=(G+P)/se):$>X?(se=2*Math.sqrt(1+$-T-X),h[3]=(G-P)/se,h[0]=(k+O)/se,h[1]=.25*se,h[2]=(V+Y)/se):(se=2*Math.sqrt(1+X-T-$),h[3]=(k-O)/se,h[0]=(G+P)/se,h[1]=(V+Y)/se,h[2]=.25*se),h},a.es=function(h,l){var u=2*Math.acos(l[3]),p=Math.sin(u/2);return p>f?(h[0]=l[0]/p,h[1]=l[1]/p,h[2]=l[2]/p):(h[0]=1,h[1]=0,h[2]=0),u},a.et=nz,a.eu=oR,a.ev=aR,a.ew=[1,1,1],a.ex=qw,a.ey=function(h,l,u,p){var x=l[0],b=l[1],T=l[2],k=l[3];return h[0]=x+p*(u[0]-x),h[1]=b+p*(u[1]-b),h[2]=T+p*(u[2]-T),h[3]=k+p*(u[3]-k),h},a.ez=Dw,a.f=bc,a.f0=qX,a.f1=function(h){const l=[0,0,0],u=I(new Float64Array(16));return D(u,h.pixelMatrix,h.globeMatrix),or(l,l,u),new Ft(l[0],l[1])},a.f2=ME,a.f3=function(h,l,u=!1){if(ml===jc.deferred||ml===jc.loading||ml===jc.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Yc=Zl.resolveURL(h),ml=jc.deferred,th=l,RE(),u||gP()},a.f4=Eo,a.f5=Lo,a.f6=Oa,a.f7=function(h){const l=TI();if(!l)return;const u=l.delete(yp);h&&u.then(()=>h()).catch(h)},a.f8=jr,a.f9=ky,a.fA=ln,a.fB=function(h){let l=0;if(new Uint32Array(h,0,1)[0]!==sJ){const u=new Uint32Array(h,0,7),[,,p,x,b,T]=u;l=u.byteLength+x+b+T+b,(p!==h.byteLength||l>=h.byteLength)&&hr("Invalid b3dm header information.")}return lJ(h,l)},a.fC=function(h,l){const u=w$(h);for(const p of u){for(const x of p.meshes)xRe(x);p.lights&&(p.lightMeshIndex=p.meshes.length,p.meshes.push(vRe(p.lights,l)))}return u},a.fD=CR,a.fE=wn,a.fF=Hh,a.fG=jc,a.fH=function(h){kb(),Xd!=null&&Xd.then(l=>{l.keys().then(u=>{for(let p=0;phr(x.message))}).catch(u=>hr(u.message))}).catch(l=>hr(l.message))},a.fa=2,a.fb=Vh,a.fc=Dv,a.fd=r2,a.fe=Kee,a.ff=Yee,a.fg=SJ,a.fh=bn,a.fi="hd_road_elevation",a.fj=Vs,a.fk=Gt,a.fl=GP,a.fm=Up,a.fn=B$,a.fo=1,a.fp=Jh,a.fq=function(h,l,u,p,x,b,T,k=1,P,O,$,V){h.createArrays(),h.tilePixelRatio=fr/(512*h.overscaling),h.compareText={},h.iconsNeedLinear=!1;const G=h.layers[0].layout,Y=h.layers[0]._unevaluatedLayout._values,X={};X.scaleFactor=k,X.textSizeScaleRange=G.get("text-size-scale-range"),X.iconSizeScaleRange=G.get("icon-size-scale-range");const[te,se]=X.textSizeScaleRange,[ae,fe]=X.iconSizeScaleRange;X.textScaleFactor=pe(X.scaleFactor,te,se),X.iconScaleFactor=pe(X.scaleFactor,ae,fe);const ue=Y["text-size"],Te=Y["icon-size"];if(h.textSizeData.kind==="composite"){const{minZoom:Ve,maxZoom:qe}=h.textSizeData;X.compositeTextSizes=[ue.possiblyEvaluate(new fs(Ve,{worldview:$}),b),ue.possiblyEvaluate(new fs(qe,{worldview:$}),b)]}if(h.iconSizeData.kind==="composite"){const{minZoom:Ve,maxZoom:qe}=h.iconSizeData;X.compositeIconSizes=[Te.possiblyEvaluate(new fs(Ve,{worldview:$}),b,V),Te.possiblyEvaluate(new fs(qe,{worldview:$}),b,V)]}X.layoutTextSize=ue.possiblyEvaluate(new fs(T+1,{worldview:$}),b),X.layoutIconSize=Te.possiblyEvaluate(new fs(T+1,{worldview:$}),b,V),X.textMaxSize=ue.possiblyEvaluate(new fs(18,{worldview:$}),b);const Ae=G.get("symbol-placement"),Ie=G.get("text-rotation-alignment")==="map"&&Ae!=="point",We=G.get("text-size");let ze=!1;const He=[];for(const Ve of h.features){const qe=G.get("text-font").evaluate(Ve,{},b).join(","),bt=We.evaluate(Ve,{},b)*X.textScaleFactor,Et=X.layoutTextSize.evaluate(Ve,{},b)*X.textScaleFactor,It=X.layoutIconSize.evaluate(Ve,{},b,V)*X.iconScaleFactor,Dt={horizontal:{},vertical:void 0},Pt=Ve.text;let Ht,vt=[0,0];if(Pt){const En=Pt.toString(),ji=G.get("text-letter-spacing").evaluate(Ve,{},b)*Za,ms=G.get("text-line-height").evaluate(Ve,{},b)*Za,ns=TB(En)?ji:0,$s=G.get("text-anchor").evaluate(Ve,{},b),vi=G.get("text-variable-anchor");if(!vi){const Li=G.get("text-radial-offset").evaluate(Ve,{},b);if(Li)vt=lee($s,[Li*Za,V$]);else{const Oo=G.get("text-offset").evaluate(Ve,{},b);vt=[Oo[0]*Za,Oo[1]*Za]}}let Xa=Ie?"center":G.get("text-justify").evaluate(Ve,{},b);const _i=Ae==="point",Ri=_i?G.get("text-max-width").evaluate(Ve,{},b)*Za:1/0,aa=Li=>{h.allowVerticalPlacement&&CE(En)&&(Dt.vertical=P$(Pt,l,u,x,qe,Ri,ms,$s,Li,ns,vt,ru.vertical,!0,Et,bt,P,X.textScaleFactor))};if(!Ie&&vi){const Li=Xa==="auto"?vi.map(Qa=>q$(Qa)):[Xa];let Oo=!1;for(let Qa=0;Qa=0||!CE(En)){const Li=P$(Pt,l,u,x,qe,Ri,ms,$s,Xa,ns,vt,ru.horizontal,!1,Et,bt,P,X.textScaleFactor);Li&&(Dt.horizontal[Xa]=Li)}aa(_i?"left":Xa)}}let Rt,Bt,Yt,tr,wr,ur,cr=!1;const rr=G.get("icon-text-fit").evaluate(Ve,{},b);if(Ve.icon&&Ve.icon.hasPrimary()){const En=R2(Ve.icon,h.iconSizeData,Y["icon-size"],b,h.zoom,Ve,P,X.iconScaleFactor,$,V);Rt=En.iconPrimary,Yt=En.iconSecondary;const ji=Rt.toString();if(Bt=p.get(ji),Bt&&(wr=G.get("icon-offset").evaluate(Ve,{},b),ur=G.get("icon-anchor").evaluate(Ve,{},b),Ht=fR(x.get(ji),Yt?x.get(Yt.toString()):void 0,wr,ur),cr=Bt.sdf,h.sdfIcons===void 0?h.sdfIcons=Bt.sdf:h.sdfIcons!==Bt.sdf&&hr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Bt.pixelRatio!==h.pixelRatio||G.get("icon-rotate").constantOr(1)!==0)&&(h.iconsNeedLinear=!0)),Yt){const ms=Yt.toString();tr=p.get(ms)}}ze=ze||!(!Ve.icon||!Ve.icon.hasSecondary());const _r=_R(Dt.horizontal)||Dt.vertical;h.iconsInText||(h.iconsInText=!!_r&&_r.iconsInText);const Rr=Et*X.textScaleFactor/Za,{defaultShapedIcon:Wr,verticallyShapedIcon:Dr}=NLe(h,Ht,G,Ve,b,Dt,Rr,wr,rr);rr!=="none"&&Ht&&(qJ(Ht)||GJ(Ht))&&(vR(0,Bt,Rt,Ht,Wr,rr,O,p,x),vR(0,tr,Yt,Ht,Wr,rr,O,p,x),Dr&&(vR(0,Bt,Rt,Ht,Dr,rr,O,p,x),vR(0,tr,Yt,Ht,Dr,rr,O,p,x))),Ht=Wr;const{iconBBox:fn,iconVerticalBBox:Wn,textBBox:mn,textVerticalBBox:es}=TLe(h,Ht,Dr,G,Ve,b,It,wr,X,x,ur,Dt,Et,vt,V);He.push({feature:Ve,shapedTextOrientations:Dt,shapedText:_r,shapedIcon:Ht,iconPrimary:Rt,iconSecondary:Yt,iconOffset:wr,iconAnchor:ur,verticallyShapedIcon:Dr,layoutTextSize:Et,layoutIconSize:It,textOffset:vt,isSDFIcon:cr,iconTextFit:rr,iconCollisionBounds:fn,iconVerticalCollisionBounds:Wn,textCollisionBounds:mn,textVerticalCollisionBounds:es})}return{featureData:He,sizes:X,hasAnySecondaryIcon:ze,textAlongLine:Ie,symbolPlacement:Ae}},a.fr=$$,a.fs=F$,a.ft=eee,a.fu=tee,a.fv=function(h,l,u,p,x,b,T,k,P,O){h.iconAtlasPositions=O.iconPositions;const{featureData:$,hasAnySecondaryIcon:V,sizes:G,textAlongLine:Y,symbolPlacement:X}=l;for(const te of $){const{shapedIcon:se,verticallyShapedIcon:ae,feature:fe,shapedTextOrientations:ue,shapedText:Te,layoutTextSize:Ae,textOffset:Ie,isSDFIcon:We,iconPrimary:ze,iconSecondary:He,iconTextFit:Ve,iconOffset:qe,iconCollisionBounds:bt,iconVerticalCollisionBounds:Et,textCollisionBounds:It}=te;hee(se,O.iconPositions,ze,He),hee(ae,O.iconPositions,ze,He),ALe(ue,O.iconPositions),kLe(ze,He,O.iconPositions),(Te||se)&&CLe(h,fe,ue,se,ae,P,G,Ae,0,Ie,We,p,x,T,k,V,Ve,qe,Y,X,bt,Et,It)}u&&h.generateCollisionDebugBuffers(b,h.collisionBoxArray,G.textScaleFactor)},a.fw=uR,a.fx=ds,a.fy=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},a.fz=DR,a.g=Vn,a.h=function(h,l){return Jg(Object.assign(h,{method:"GET"}),l)},a.i=function(h){return Vn.API_STYLE_REGEX.test(h)&&!wc(h)},a.j=function(h){return btoa(encodeURIComponent(h).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(+("0x"+u))))},a.k=Ab,a.l=function(h){return decodeURIComponent(atob(h).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""))},a.m=function(h,l){return Jg(Object.assign(h,{type:"json"}),l)},a.n=ty,a.o=Zl,a.p=function(h,l){return Jg(Object.assign(h,{method:"POST"}),l)},a.q=Jo,a.r=ht,a.s=function(h){try{const l=self[h];return l.setItem("_mapbox_test_",1),l.removeItem("_mapbox_test_"),!0}catch{return!1}},a.t=et,a.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)}()},a.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)},a.w=hr,a.x=class{constructor(h){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(h&&h.maxTextureMemoryMB?h.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(l=>{this.cache.delete(l),this.clearExpiredTextures()})}calculateTextureMemory(h){return h.image?Math.ceil(h.image.width*h.image.height*4*(h.patternPositions.size>0?1.33:1)):0}evictTexture(h){const l=this.textures.get(h);if(l){const u=this.calculateTextureMemory(h);l.destroy(),this.textures.delete(h),this.textureAccessTimes.delete(h),this.textureMemoryUsed-=u}}evictTexturesIfNeeded(h){for(;this.textureMemoryUsed+h>this.maxTextureMemory&&this.textures.size>0;){let l=null,u=1/0;for(const[p]of this.textures.entries()){const x=this.textureAccessTimes.get(p)||0;xthis._layers[gr.id]),ht=nt[0];if(ht.visibility==="none")continue;const it=ht.source||"";let mt=this.familiesBySource[it];mt||(mt=this.familiesBySource[it]=Object.create(null));const Gt=ht.sourceLayer||"_geojsonTileLayer";let Mt=mt[Gt];Mt||(Mt=mt[Gt]=[]),Mt.push(nt)}}}const A=1*f.fa;class C{constructor(he){const pe={},Fe=[];for(const ht in he){const it=he[ht],mt=pe[ht]={};for(const Gt in it.glyphs){const Mt=it.glyphs[+Gt];if(!Mt||Mt.bitmap.width===0||Mt.bitmap.height===0)continue;const gr=Mt.metrics.localGlyph?A:1,zr={x:0,y:0,w:Mt.bitmap.width+2*gr,h:Mt.bitmap.height+2*gr};Fe.push(zr),mt[Gt]=zr}}const{w:Ye,h:et}=f.J(Fe),nt=new f.f9({width:Ye||1,height:et||1});for(const ht in he){const it=he[ht];for(const mt in it.glyphs){const Gt=it.glyphs[+mt];if(!Gt||Gt.bitmap.width===0||Gt.bitmap.height===0)continue;const Mt=pe[ht][mt],gr=Gt.metrics.localGlyph?A:1;f.f9.copy(Gt.bitmap,nt,{x:0,y:0},{x:Mt.x+gr,y:Mt.y+gr},Gt.bitmap)}}this.image=nt,this.positions=pe}}function I(dt,he,pe){dt[he]?pe&&(dt[he].center=pe):dt[he]={floorIds:new Set,center:pe||[0,0],floors:{}}}function M(dt,he,pe,Fe){for(const Ye of he)I(dt,Ye),dt[Ye].floors[pe]=Fe,dt[Ye].floorIds.add(pe)}function D(dt){return{id:dt.properties.id.toString(),center:[dt.properties.center_lon||0,dt.properties.center_lat||0]}}function F(dt,he){const pe=dt.properties.id.toString(),Fe=!!dt.properties.is_default&&dt.properties.is_default,Ye=dt.properties.connected_floor_ids?new Set(dt.properties.connected_floor_ids.toString().split(";")):new Set,et=dt.properties.conflicted_floor_ids?new Set(dt.properties.conflicted_floor_ids.toString().split(";")):new Set,nt=dt.properties.structure_ids?new Set(dt.properties.structure_ids.toString().split(";")):new Set,ht=dt.properties.name.toString(),it=dt.properties.z_index,mt=function(Gt,Mt){const gr=Gt.loadGeometry();if(!gr||gr.length===0)return;const zr=gr.map(Hr=>Hr.map(hr=>f.fb(hr,Mt,Gt.extent)));return zr.length===0?void 0:{type:"Polygon",coordinates:[zr[0]]}}(dt,he);return{id:pe,isDefault:Fe,connections:Ye,conflicts:et,buildings:nt,name:ht,zIndex:it,geometry:mt}}function z(dt,he){return he.every(pe=>dt.properties&&dt.properties[pe]!=null)}function q(dt){return z(dt,["type","id","name"])&&dt.properties.type==="structure"}function H(dt){return z(dt,["type","id","name","z_index"])&&dt.properties.type==="floor"}f.f8(C,"GlyphAtlas");class K{constructor(he){this.tileID=new f.aR(he.tileID.overscaledZ,he.tileID.wrap,he.tileID.canonical.z,he.tileID.canonical.x,he.tileID.canonical.y),this.tileZoom=he.tileZoom,this.uid=he.uid,this.zoom=he.zoom,this.lut=he.lut,this.canonical=he.tileID.canonical,this.pixelRatio=he.pixelRatio,this.tileSize=he.tileSize,this.source=he.source,this.scope=he.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=he.showCollisionBoxes,this.collectResourceTiming=!!he.request&&he.request.collectResourceTiming,this.promoteId=he.promoteId,this.renderSourceType=he.renderSourceType,this.tileTransform=f.fc(he.tileID.canonical,he.projection),this.projection=he.projection,this.worldview=he.worldview,this.localizableLayerIds=he.localizableLayerIds,this.brightness=he.brightness,this.extraShadowCaster=!!he.extraShadowCaster,this.tessellationStep=he.tessellationStep,this.scaleFactor=he.scaleFactor,this.worldview=he.worldview,this.indoor=he.indoor}parse(he,pe,Fe,Ye,et,nt){this.status="parsing",this.data=he,this.collisionBoxArray=new f.fd;const ht=new f.fe(Object.keys(he.layers).sort()),it=new f.ff(this.tileID,this.promoteId);it.bucketLayerIDs=[];const mt={},Gt=new f.fg(256,256),Mt={featureIndex:it,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Gt,availableImages:Fe,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Mt.activeFloors=function(hr,rt,qt,vr){const wn=rt.indoorState.activeFloorsVisible;if(!rt.sourceLayers)return wn?rt.indoorState.activeFloors:void 0;const Cn=function(Jn,ks){if(!Jn)return f.w("No source layers defined in indoor specification"),ks;if(Jn.size===0)return ks;const Ui=Jn.difference(ks);for(const Un of Ui)f.w(`Missing source layer required in indoor specification: ${Un}`);return ks.intersection(ks)}(rt.sourceLayers,new Set(Object.keys(hr.layers))),Qn=rt.indoorState,Ns=function(Jn,ks,Ui,Un,ni){const hi={};for(const Vn of ks){const Oa=Jn.layers[Vn];if(Oa)for(let Lo=0;Lo=Un.maxzoom||Un.visibility==="none")continue;J(Ui,this.zoom,Mt.brightness,Fe,this.worldview,Mt.activeFloors);const ni=mt[Un.id]=Un.createBucket({index:it.bucketLayerIDs.length,layers:Ui,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Qn,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Ye,worldview:this.worldview,localizable:Jn,availableImages:Fe,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});it.bucketLayerIDs.push(Ui.map(Vn=>f.F(Vn.id,Vn.scope)));let hi=ni.prepare?ni.prepare():null;hi!=null?(hi=hi.then(()=>ni.populate(Ns,Mt,this.tileID.canonical,this.tileTransform)),gr.push(hi)):ni.populate(Ns,Mt,this.tileID.canonical,this.tileTransform)}}const Hr=()=>{Gt.trim();const hr=!(!Mt.elevationFeatures||!Mt.elevationFeatures.some(Un=>Un.heightRange.min<0));let rt,qt,vr,wn,Cn,Qn,Ns;const Jn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},ks=()=>{if(rt)return this.status="done",nt(rt);if(this.extraShadowCaster)this.status="done",nt(null,{buckets:Object.values(mt).filter(Un=>!Un.isEmpty()),featureIndex:it,collisionBoxArray:null,hasTunnelGeometry:hr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Mt.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(qt&&vr&&wn&&Ns){const ni=new C(qt),hi=new Map;for(const[Lo,Eo]of vr.entries()){const{imagePosition:bc}=f.fn(Lo,Eo,f.fo);hi.set(Lo,bc)}const Vn={};for(const Lo in mt){const Eo=mt[Lo];Eo instanceof f.fp&&(J(Eo.layers,this.zoom,Mt.brightness,Fe,this.worldview,Mt.activeFloors),Vn[Lo]=f.fq(Eo,qt,ni.positions,vr,hi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Cn,this.worldview,Fe))}const Oa={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(et,vr,Cn,()=>{Oa.iconsPending=!1,Ui(Vn,ni,Oa,void 0,Ns)}),this.rasterizeIfNeeded(et,wn,Qn,()=>{Oa.patternsPending=!1,Ui(Vn,ni,Oa,void 0,Ns)})}},Ui=(Un,ni,hi,Vn,Oa)=>{if(hi.iconsPending||hi.patternsPending)return;const Lo=vr.size>0||wn.size>0,Eo=Object.keys(Un).length>0;if(!Lo&&!Eo)return this.status="done",void nt(null,{buckets:Object.values(mt).filter(wc=>!wc.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:hr,glyphAtlasImage:ni.image,lineAtlas:Gt,imageAtlas:null,brightness:Mt.brightness});const bc=(wc,Kd)=>{for(const Ll in mt){const Sc=mt[Ll];if(Ll in Un)f.fv(Sc,Un[Ll],this.showCollisionBoxes,Fe,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,vr,Kd);else if(Sc.hasPattern&&(Sc instanceof f.fw||Sc instanceof f.fl||Sc instanceof f.e0)){J(Sc.layers,this.zoom,Mt.brightness,Fe,this.worldview,Mt.activeFloors);const Yd=Object.fromEntries(Kd.patternPositions);Sc.addFeatures(Mt,this.tileID.canonical,Yd,Fe,this.tileTransform,this.brightness)}}this.status="done",nt(null,{buckets:Object.values(mt).filter(Ll=>!Ll.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:hr,glyphAtlasImage:ni.image,lineAtlas:Gt,imageAtlas:wc,brightness:Mt.brightness})};if(Lo){const wc=new Map,Kd=f.fr(vr,wc),Ll=f.fr(wn,wc),Sc=new f.fs(Kd,Ll,Oa,this.lut,wc);et.send("checkAtlasCache",{descriptor:Sc,scope:this.scope},(Yd,Hc)=>{let Zd,Iu;if(Yd&&f.w(`[Worker] Error checking atlas cache: ${Yd.message}`),Hc)Zd=new f.ft(Hc.sourceHash),Iu=Hc;else{const Zl=new f.fu(vr,wn,this.lut,Oa);Zd=Zl,Iu=Zl}bc(Zd,Iu)})}else bc(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Un=f.fk(Mt.glyphDependencies,Vn=>Object.keys(Vn).map(Number));Object.keys(Un).length?et.send("getGlyphs",{uid:this.uid,stacks:Un},(Vn,Oa)=>{rt||(rt=Vn,qt=Oa,ks())},void 0,!1,Jn):qt={},Ns=new Map;const ni=Array.from(Mt.iconDependencies.keys()).map(Vn=>f.I.parse(Vn));ni.length?et.send("getImages",{images:ni,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Vn,Oa)=>{if(!rt){rt=Vn,vr=new Map,Cn=this.updateImageMapAndGetImageTaskQueue(vr,Oa.images,Mt.iconDependencies);for(const[Lo,Eo]of Oa.versions.entries())Ns.set(Lo,Eo);ks()}},void 0,!1,Jn):(vr=new Map,Cn=new Map);const hi=Array.from(Mt.patternDependencies.keys()).map(Vn=>f.I.parse(Vn));hi.length?et.send("getImages",{images:hi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Vn,Oa)=>{if(!rt){rt=Vn,wn=new Map,Qn=this.updateImageMapAndGetImageTaskQueue(wn,Oa.images,Mt.patternDependencies);for(const[Lo,Eo]of Oa.versions.entries())Ns.set(Lo,Eo);ks()}},void 0,!1,Jn):(wn=new Map,Qn=new Map)}if(Mt.elevationFeatures&&Mt.elevationFeatures.length>0){const Un=[];for(const hi of Object.values(mt))if(hi instanceof f.fl){const Vn=hi.getUnevaluatedPortalGraph();Vn&&Un.push(Vn)}const ni=f.fm.evaluate(Un);for(const hi of Object.values(mt))if(hi instanceof f.fl){const Vn=he.layers[ht.decode(hi.sourceLayerIndex)];hi.setEvaluatedPortalGraph(ni,Vn,this.tileID.canonical,Mt.availableImages,Mt.brightness)}}ks()};gr.length>0?Promise.allSettled(gr).then(Hr).catch(nt):Hr()}updateParameters(he){this.scaleFactor=he.scaleFactor,this.showCollisionBoxes=he.showCollisionBoxes,this.projection=he.projection,this.brightness=he.brightness,this.tileTransform=f.fc(he.tileID.canonical,he.projection),this.extraShadowCaster=he.extraShadowCaster,this.lut=he.lut,this.worldview=he.worldview,this.indoor=he.indoor}rasterizeIfNeeded(he,pe,Fe,Ye){Array.from(pe.values()).some(et=>et.usvg)?this.rasterize(he,pe,Fe,Ye):Ye()}updateImageMapAndGetImageTaskQueue(he,pe,Fe){const Ye=new Map;for(const et of pe.keys()){const nt=Fe.get(et)||[];for(const ht of nt){const it=ht.toString(),mt=pe.get(ht.id.toString());mt.usvg?Ye.has(it)||(Ye.set(it,ht),he.set(it,Object.assign({},mt))):he.set(it,mt)}}return Ye}rasterize(he,pe,Fe,Ye){this.rasterizeTask=he.send("rasterizeImages",{scope:this.scope,tasks:Fe},(et,nt)=>{if(!et)for(const[ht,it]of nt.entries()){const mt=Object.assign(pe.get(ht),{data:it});pe.set(ht,mt)}Ye()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function J(dt,he,pe,Fe,Ye,et){const nt=new f.ae(he,{brightness:pe,worldview:Ye,activeFloors:et});for(const ht of dt)ht.recalculate(nt,Fe)}class Q extends f.E{constructor({actor:he,layerIndex:pe,availableImages:Fe,availableModels:Ye,isSpriteLoaded:et,tileProvider:nt,brightness:ht,maxUniformBufferBindings:it,maxUniformBlockSizeDwords:mt,disableSymbolUBO:Gt}){super(),this.actor=he,this.layerIndex=pe,this.availableImages=Fe,this.availableModels=Ye,this.loadVectorData=f.aO,this.tileProvider=nt,this.loading={},this.loaded={},this.deduped=new f.aN(he.scheduler),this.isSpriteLoaded=et,this.scheduler=he.scheduler,this.brightness=ht,this.maxUniformBufferBindings=it,this.maxUniformBlockSizeDwords=mt,this.disableSymbolUBO=Gt}loadTileData(he,pe){if(!this.tileProvider)return this.loadVectorData(he,pe);const Fe=new AbortController,{z:Ye,x:et,y:nt}=he.tileID.canonical;return this.tileProvider.loadTile({z:Ye,x:et,y:nt},{request:he.request,signal:Fe.signal}).then(ht=>{if(Fe.signal.aborted)return;if(ht==null){const mt=new Error("Tile not found");return mt.status=404,pe(mt)}if(ht.data===null)return pe(null,null);const it=new Map;ht.expires&&it.set("expires",ht.expires),ht.cacheControl&&it.set("cache-control",ht.cacheControl),pe(null,{rawData:ht.data,responseHeaders:it})}).catch(ht=>{Fe.signal.aborted||pe(ht instanceof Error?ht:new Error(String(ht)))}),()=>Fe.abort()}loadTile(he,pe){const Fe=he.uid,Ye=he&&he.request,et=Ye&&Ye.collectResourceTiming,nt=this.loading[Fe]=new K(he);nt.maxUniformBufferBindings=this.maxUniformBufferBindings,nt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,nt.disableSymbolUBO=this.disableSymbolUBO,nt.abort=this.loadTileData(he,(ht,it)=>{const mt=!this.loading[Fe];if(delete this.loading[Fe],nt.cancelRasterize(),mt||ht||!it)return nt.status="done",mt||(this.loaded[Fe]=nt),pe(ht);const Gt=it.rawData,Mt={},gr=f.aP(it.responseHeaders);gr&&gr.expires&&(Mt.expires=gr.expires),gr&&gr.cacheControl&&(Mt.cacheControl=gr.cacheControl),nt.vectorTile=it.vectorTile||new f.fx(new f.a$(Gt));const zr=()=>{nt.parse(nt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Hr,hr)=>{if(Hr||!hr)return pe(Hr);const rt={};if(et){const qt=m(Ye);qt.length>0&&(rt.resourceTiming=JSON.parse(JSON.stringify(qt)))}pe(null,Object.assign({rawTileData:Gt.slice(0),responseHeaders:it.responseHeaders},hr,Mt,rt))})};this.isSpriteLoaded?zr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(zr,{type:"parseTile",renderSourceType:he.renderSourceType,zoom:he.tileZoom}):zr()}),this.loaded=this.loaded||{},this.loaded[Fe]=nt})}reloadTile(he,pe){const Fe=this.loaded,Ye=he.uid;if(Fe&&Fe[Ye]){const et=Fe[Ye];et.updateParameters(he);const nt=(ht,it)=>{const mt=et.reloadCallback;mt&&(delete et.reloadCallback,et.parse(et.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,mt)),pe(ht,it)};et.status==="parsing"?et.reloadCallback=nt:et.status==="done"&&(et.vectorTile?et.parse(et.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,nt):nt())}else pe(null,void 0)}abortTile(he,pe){const Fe=he.uid,Ye=this.loading[Fe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Fe]),pe()}removeTile(he,pe){const Fe=this.loaded,Ye=he.uid;Fe&&Fe[Ye]&&delete Fe[Ye],pe()}}class ee{constructor(he){this.loading={}}loadTile(he,pe){const Fe=he.uid,{cancel:Ye}=f.b1(he.request,(et,nt,ht)=>{const it=!this.loading[Fe];if(delete this.loading[Fe],it||et||!nt)return pe(et);this.decodeTile(Fe,nt,he.encoding).then(mt=>{const{expires:Gt,cacheControl:Mt}=f.aP(ht);pe(null,Object.assign(mt,{expires:Gt,cacheControl:Mt}))}).catch(mt=>pe(mt))});this.loading[Fe]={cancel:Ye}}async decodeTile(he,pe,Fe){const Ye=await createImageBitmap(new Blob([new Uint8Array(pe)],{type:"image/png"})),et=1-(Ye.width-f.fy(Ye.width))/2,nt=et<1,ht=this.getImageData(Ye,et);return Ye.close(),{dem:new f.fz(he,ht,Fe,nt),borderReady:nt}}reloadTile(he,pe){pe(null,null)}abortTile(he,pe){const Fe=he.uid,Ye=this.loading[Fe];Ye&&(Ye.cancel(),delete this.loading[Fe]),pe()}removeTile(he,pe){pe()}getImageData(he,pe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(he.width,he.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=he.width,this.offscreenCanvas.height=he.height,this.offscreenCanvasContext.drawImage(he,0,0,he.width,he.height);const Fe=this.offscreenCanvasContext.getImageData(-pe,-pe,he.width+2*pe,he.height+2*pe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Fe}}f.a_.setPbf(f.a$);class oe{constructor(he){this._mrt=new f.a_(he.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=he.uid,this.tileID=he.tileID,this.source=he.source}parse(he,pe){const Fe=this._mrt;this.status="parsing",this._entireBuffer=he;try{Fe.parseHeader(he),this._isHeaderLoaded=!0;const Ye=[];for(const et in Fe.layers){const nt=Fe.getLayer(et),ht=nt.getDataRange(nt.getBandList()),it=Fe.createDecodingTask(ht),mt=he.slice(ht.firstByte,ht.lastByte+1),Gt=f.a_.performDecoding(mt,it).then(Mt=>it.complete(null,Mt)).catch(Mt=>it.complete(Mt,null));Ye.push(Gt)}Promise.allSettled(Ye).then(()=>pe(null,Fe)).catch(et=>pe(et))}catch(Ye){pe(Ye)}}}class de{constructor({actor:he}){this.actor=he,this.loading={},this.loaded={}}loadTile(he,pe){const Fe=he.uid,Ye=he.request,et=this.loading[Fe]=new oe(he),{cancel:nt}=f.b1(Ye,(ht,it,mt)=>{const Gt=!this.loading[Fe];if(delete this.loading[Fe],Gt||ht||!it)return et.status="done",Gt||(this.loaded[Fe]=et),pe(ht);et.parse(it,(Mt,gr)=>{if(Mt||!gr)return pe(Mt);pe(null,gr,mt)}),this.loaded[Fe]=et});et.abort=nt}reloadTile(he,pe){pe(null,void 0)}abortTile(he,pe){const Fe=he.uid,Ye=this.loading[Fe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Fe]),pe()}removeTile(he,pe){const Fe=he.uid;this.loaded[Fe]&&delete this.loaded[Fe],pe()}decodeRasterArray(he,pe){f.a_.performDecoding(he.buffer,he.task).then(Fe=>pe(null,Fe)).catch(Fe=>pe(Fe))}}const ye=f.fA.prototype.toGeoJSON;class we{constructor(he){this._feature=he,this.extent=f.an,this.type=he.type,this.properties=he.tags,"id"in he&&!isNaN(he.id)&&(this.id=parseInt(he.id,10))}loadGeometry(){if(this._feature.type===1){const he=[];for(const pe of this._feature.geometry)he.push([new f.P(pe[0],pe[1])]);return he}{const he=[];for(const pe of this._feature.geometry){const Fe=[];for(const Ye of pe)Fe.push(new f.P(Ye[0],Ye[1]));he.push(Fe)}return he}}toGeoJSON(he,pe,Fe){return ye.call(this,he,pe,Fe)}}class Le{constructor(he,pe){this.name=he,this.extent=f.an,this.length=pe.length,this._jsonFeatures=pe}feature(he){return new we(this._jsonFeatures[he])}}class Se{constructor(he){this.layers={},this.extent=f.an;for(const pe of Object.keys(he))this.layers[pe]=new Le(pe,he[pe])}}const ve=64/4096;class me{constructor(){this.features=new Map}clear(){this.features.clear()}load(he=[],pe){for(const Fe of he){const Ye=Fe.id;if(Ye==null)continue;let et=this.features.get(Ye);et&&this.updateCache(et,pe),Fe.geometry?(et=Pe(Fe),this.updateCache(et,pe),this.features.set(Ye,et)):this.features.delete(Ye),this.updateCache(et,pe)}}updateCache(he,pe){for(const{canonical:Fe,uid:Ye}of Object.values(pe)){const{z:et,x:nt,y:ht}=Fe;ke(he,Math.pow(2,et),nt,ht)&&delete pe[Ye]}}getTile(he,pe,Fe){const Ye=Math.pow(2,he),et=[];for(const nt of this.features.values())ke(nt,Ye,pe,Fe)&&et.push(Ze(nt,Ye,pe,Fe));return{features:et}}getFeatures(){return[...this.features.values()]}}function ke({minX:dt,minY:he,maxX:pe,maxY:Fe},Ye,et,nt){return dt<(et+1+ve)/Ye&&he<(nt+1+ve)/Ye&&pe>(et-ve)/Ye&&Fe>(nt-ve)/Ye}function Pe(dt){const{id:he,geometry:pe,properties:Fe}=dt;if(!pe)return;if(pe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Ye,coordinates:et}=pe,nt={id:he,type:1,geometry:[],tags:Fe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},ht=nt.geometry;if(Ye==="Point")Ee(et,ht,nt);else if(Ye==="MultiPoint")for(const it of et)Ee(it,ht,nt);else if(Ye==="LineString")nt.type=2,xe(et,ht,nt);else if(Ye==="MultiLineString")nt.type=2,Ue(et,ht,nt);else if(Ye==="Polygon")nt.type=3,Ue(et,ht,nt,!0);else{if(Ye!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");nt.type=3;for(const it of et)Ue(it,ht,nt,!0)}return nt}function Ee([dt,he],pe,Fe){const Ye=f.aH(dt);let et=f.aL(he);et=et<0?0:et>1?1:et,pe.push(Ye,et),Fe.minX=Math.min(Fe.minX,Ye),Fe.minY=Math.min(Fe.minY,et),Fe.maxX=Math.max(Fe.maxX,Ye),Fe.maxY=Math.max(Fe.maxY,et)}function xe(dt,he,pe,Fe=!1,Ye=!1){const et=[];for(const nt of dt)Ee(nt,et,pe);he.push(et),Fe&&function(nt,ht){let it=0;for(let mt=0,Gt=nt.length,Mt=Gt-2;mt0===ht)for(let mt=0,Gt=nt.length;mt=nt&&Mt>=nt||(mt>=nt?(Gt+=Math.round(Hr*((nt-mt)/zr)),mt=nt):Mt>=nt&&(gr=Gt+Math.round(Hr*((nt-mt)/zr)),Mt=nt),Gt>=nt&&gr>=nt||(Gt>=nt?(mt+=Math.round(zr*((nt-Gt)/Hr)),Gt=nt):gr>=nt&&(Mt=mt+Math.round(zr*((nt-Gt)/Hr)),gr=nt),ht&&mt===ht[ht.length-1][0]&&Gt===ht[ht.length-1][1]||(ht=[[mt,Gt]],Ye.push(ht)),ht.push([Mt,gr])))))}}function wt(dt,he,pe,Fe,Ye){const et=(pe-ve)/he,nt=(Fe-ve)/he,ht=(pe+1+ve)/he,it=(Fe+1+ve)/he;function mt(gr,zr){let Hr=0;return grht&&(Hr|=2),zrit&&(Hr|=8),Hr}let Gt=[];for(let gr=1;gr<=8;gr*=2){let zr=dt[dt.length-2],Hr=dt[dt.length-1],hr=!(mt(zr,Hr)&gr);for(let rt=0;rt>31}function xt(dt,he){const{geometry:pe,type:Fe}=dt;let Ye=0,et=0;if(Fe===1){he.writeVarint(kt(1,pe.length));for(const nt of pe){const ht=nt[0]-Ye,it=nt[1]-et;he.writeVarint(Vt(ht)),he.writeVarint(Vt(it)),Ye+=ht,et+=it}}else for(const nt of pe){if(nt.length===0)continue;he.writeVarint(kt(1,1));const ht=nt.length-(Fe===3?1:0);for(let it=0;itdt},rn=Math.fround||(Lr=new Float32Array(1),dt=>(Lr[0]=+dt,Lr[0]));var Lr;class $r{constructor(he){this.options=Object.assign(Object.create(Tr),he),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(he){const{log:pe,minZoom:Fe,maxZoom:Ye}=this.options;pe&&console.time("total time");const et=`prepare ${he.length} points`;pe&&console.time(et),this.points=he;const nt=[];for(let it=0;it=Fe;it--){const mt=+Date.now();ht=this.trees[it]=this._createTree(this._cluster(ht,it)),pe&&console.log("z%d: %d clusters in %dms",it,ht.numItems,+Date.now()-mt)}return pe&&console.timeEnd("total time"),this}getClusters(he,pe){let Fe=((he[0]+180)%360+360)%360-180;const Ye=Math.max(-90,Math.min(90,he[1]));let et=he[2]===180?180:((he[2]+180)%360+360)%360-180;const nt=Math.max(-90,Math.min(90,he[3]));if(he[2]-he[0]>=360)Fe=-180,et=180;else if(Fe>et){const Mt=this.getClusters([Fe,Ye,180,nt],pe),gr=this.getClusters([-180,Ye,et,nt],pe);return Mt.concat(gr)}const ht=this.trees[this._limitZoom(pe)],it=ht.range(tt(Fe),Tt(nt),tt(et),Tt(Ye)),mt=ht.data,Gt=[];for(const Mt of it){const gr=this.stride*Mt;Gt.push(mt[gr+5]>1?qr(mt,gr,this.clusterProps):this.points[mt[gr+3]])}return Gt}getChildren(he){const pe=this._getOriginId(he),Fe=this._getOriginZoom(he),Ye="No cluster with the specified id.",et=this.trees[Fe];if(!et)throw new Error(Ye);const nt=et.data;if(pe*this.stride>=nt.length)throw new Error(Ye);const ht=this.options.radius/(this.options.extent*Math.pow(2,Fe-1)),it=et.within(nt[pe*this.stride],nt[pe*this.stride+1],ht),mt=[];for(const Gt of it){const Mt=Gt*this.stride;nt[Mt+4]===he&&mt.push(nt[Mt+5]>1?qr(nt,Mt,this.clusterProps):this.points[nt[Mt+3]])}if(mt.length===0)throw new Error(Ye);return mt}getLeaves(he,pe,Fe){const Ye=[];return this._appendLeaves(Ye,he,pe=pe||10,Fe=Fe||0,0),Ye}getTile(he,pe,Fe){const Ye=this.trees[this._limitZoom(he)],et=Math.pow(2,he),{extent:nt,radius:ht}=this.options,it=ht/nt,mt=(Fe-it)/et,Gt=(Fe+1+it)/et,Mt={features:[]};return this._addTileFeatures(Ye.range((pe-it)/et,mt,(pe+1+it)/et,Gt),Ye.data,pe,Fe,et,Mt),pe===0&&this._addTileFeatures(Ye.range(1-it/et,mt,1,Gt),Ye.data,et,Fe,et,Mt),pe===et-1&&this._addTileFeatures(Ye.range(0,mt,it/et,Gt),Ye.data,-1,Fe,et,Mt),Mt.features.length?Mt:null}getClusterExpansionZoom(he){let pe=this._getOriginZoom(he)-1;for(;pe<=this.options.maxZoom;){const Fe=this.getChildren(he);if(pe++,Fe.length!==1)break;he=Fe[0].properties.cluster_id}return pe}_appendLeaves(he,pe,Fe,Ye,et){const nt=this.getChildren(pe);for(const ht of nt){const it=ht.properties;if(it&&it.cluster?et+it.point_count<=Ye?et+=it.point_count:et=this._appendLeaves(he,it.cluster_id,Fe,Ye,et):et1;let Gt,Mt,gr;if(mt)Gt=Nn(pe,it,this.clusterProps),Mt=pe[it],gr=pe[it+1];else{const hr=this.points[pe[it+3]];Gt=hr.properties;const[rt,qt]=hr.geometry.coordinates;Mt=tt(rt),gr=Tt(qt)}const zr={type:1,geometry:[[Math.round(this.options.extent*(Mt*et-Fe)),Math.round(this.options.extent*(gr*et-Ye))]],tags:Gt};let Hr;Hr=mt||this.options.generateId?pe[it+3]:this.points[pe[it+3]].id,Hr!==void 0&&(zr.id=Hr),nt.features.push(zr)}}_limitZoom(he){return Math.max(this.options.minZoom,Math.min(Math.floor(+he),this.options.maxZoom+1))}_cluster(he,pe){const{radius:Fe,extent:Ye,reduce:et,minPoints:nt}=this.options,ht=Fe/(Ye*Math.pow(2,pe)),it=he.data,mt=[],Gt=this.stride;for(let Mt=0;Mtpe&&(rt+=it[vr+5])}if(rt>hr&&rt>=nt){let qt,vr=gr*hr,wn=zr*hr,Cn=-1;const Qn=(Mt/Gt<<5)+(pe+1)+this.points.length;for(const Ns of Hr){const Jn=Ns*Gt;if(it[Jn+2]<=pe)continue;it[Jn+2]=pe;const ks=it[Jn+5];vr+=it[Jn]*ks,wn+=it[Jn+1]*ks,it[Jn+4]=Qn,et&&(qt||(qt=this._map(it,Mt,!0),Cn=this.clusterProps.length,this.clusterProps.push(qt)),et(qt,this._map(it,Jn)))}it[Mt+4]=Qn,mt.push(vr/rt,wn/rt,1/0,Qn,-1,rt),et&&mt.push(Cn)}else{for(let qt=0;qt1)for(const qt of Hr){const vr=qt*Gt;if(!(it[vr+2]<=pe)){it[vr+2]=pe;for(let wn=0;wn>5}_getOriginZoom(he){return(he-this.points.length)%32}_map(he,pe,Fe){if(he[pe+5]>1){const nt=this.clusterProps[he[pe+6]];return Fe?Object.assign({},nt):nt}const Ye=this.points[he[pe+3]].properties,et=this.options.map(Ye);return Fe&&et===Ye?Object.assign({},et):et}}function qr(dt,he,pe){return{type:"Feature",id:dt[he+3],properties:Nn(dt,he,pe),geometry:{type:"Point",coordinates:[(Fe=dt[he],360*(Fe-.5)),Zt(dt[he+1])]}};var Fe}function Nn(dt,he,pe){const Fe=dt[he+5],Ye=Fe>=1e4?`${Math.round(Fe/1e3)}k`:Fe>=1e3?Math.round(Fe/100)/10+"k":Fe,et=dt[he+6],nt=et===-1?{}:Object.assign({},pe[et]);return Object.assign(nt,{cluster:!0,cluster_id:dt[he+3],point_count:Fe,point_count_abbreviated:Ye})}function tt(dt){return dt/360+.5}function Tt(dt){const he=Math.sin(dt*Math.PI/180),pe=.5-.25*Math.log((1+he)/(1-he))/Math.PI;return pe<0?0:pe>1?1:pe}function Zt(dt){const he=(180-360*dt)*Math.PI/180;return 360*Math.atan(Math.exp(he))/Math.PI-90}function ar(dt,he,pe,Fe){let Ye=Fe;const et=he+(pe-he>>1);let nt,ht=pe-he;const it=dt[he],mt=dt[he+1],Gt=dt[pe],Mt=dt[pe+1];for(let gr=he+3;grYe)nt=gr,Ye=zr;else if(zr===Ye){const Hr=Math.abs(gr-et);HrFe&&(nt-he>3&&ar(dt,he,nt,Fe),dt[nt+2]=Ye,pe-nt>3&&ar(dt,nt,pe,Fe))}function Wt(dt,he,pe,Fe,Ye,et){let nt=Ye-pe,ht=et-Fe;if(nt!==0||ht!==0){const it=((dt-pe)*nt+(he-Fe)*ht)/(nt*nt+ht*ht);it>1?(pe=Ye,Fe=et):it>0&&(pe+=nt*it,Fe+=ht*it)}return nt=dt-pe,ht=he-Fe,nt*nt+ht*ht}function Kt(dt,he,pe,Fe){const Ye={id:dt??null,type:he,geometry:pe,tags:Fe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(he==="Point"||he==="MultiPoint"||he==="LineString")At(Ye,pe);else if(he==="Polygon")At(Ye,pe[0]);else if(he==="MultiLineString")for(const et of pe)At(Ye,et);else if(he==="MultiPolygon")for(const et of pe)At(Ye,et[0]);return Ye}function At(dt,he){for(let pe=0;pe0&&(nt+=Fe?(Ye*Gt-mt*et)/2:Math.sqrt(Math.pow(mt-Ye,2)+Math.pow(Gt-et,2))),Ye=mt,et=Gt}const ht=he.length-3;he[2]=1,ar(he,0,ht,pe),he[ht+2]=1,he.size=Math.abs(nt),he.start=0,he.end=he.size}function Bn(dt,he,pe,Fe){for(let Ye=0;Ye1?1:pe}function gs(dt,he,pe,Fe,Ye,et,nt,ht){if(Fe/=he,et>=(pe/=he)&&nt=Fe)return null;const it=[];for(const mt of dt){const Gt=mt.geometry;let Mt=mt.type;const gr=Ye===0?mt.minX:mt.minY,zr=Ye===0?mt.maxX:mt.maxY;if(gr>=pe&&zr=Fe)continue;let Hr=[];if(Mt==="Point"||Mt==="MultiPoint")zi(Gt,Hr,pe,Fe,Ye);else if(Mt==="LineString")Ir(Gt,Hr,pe,Fe,Ye,!1,ht.lineMetrics);else if(Mt==="MultiLineString")Si(Gt,Hr,pe,Fe,Ye,!1);else if(Mt==="Polygon")Si(Gt,Hr,pe,Fe,Ye,!0);else if(Mt==="MultiPolygon")for(const hr of Gt){const rt=[];Si(hr,rt,pe,Fe,Ye,!0),rt.length&&Hr.push(rt)}if(Hr.length){if(ht.lineMetrics&&Mt==="LineString"){for(const hr of Hr)it.push(Kt(mt.id,Mt,hr,mt.tags));continue}Mt!=="LineString"&&Mt!=="MultiLineString"||(Hr.length===1?(Mt="LineString",Hr=Hr[0]):Mt="MultiLineString"),Mt!=="Point"&&Mt!=="MultiPoint"||(Mt=Hr.length===3?"Point":"MultiPoint"),it.push(Kt(mt.id,Mt,Hr,mt.tags))}}return it.length?it:null}function zi(dt,he,pe,Fe,Ye){for(let et=0;et=pe&&nt<=Fe&&oi(he,dt[et],dt[et+1],dt[et+2])}}function Ir(dt,he,pe,Fe,Ye,et,nt){let ht=$n(dt);const it=Ye===0?ia:Xr;let mt,Gt,Mt=dt.start;for(let rt=0;rtpe&&(Gt=it(ht,qt,vr,Cn,Qn,pe),nt&&(ht.start=Mt+mt*Gt)):Ns>Fe?Jn=pe&&(Gt=it(ht,qt,vr,Cn,Qn,pe),ks=!0),Jn>Fe&&Ns<=Fe&&(Gt=it(ht,qt,vr,Cn,Qn,Fe),ks=!0),!et&&ks&&(nt&&(ht.end=Mt+mt*Gt),he.push(ht),ht=$n(dt)),nt&&(Mt+=mt)}let gr=dt.length-3;const zr=dt[gr],Hr=dt[gr+1],hr=Ye===0?zr:Hr;hr>=pe&&hr<=Fe&&oi(ht,zr,Hr,dt[gr+2]),gr=ht.length-3,et&&gr>=3&&(ht[gr]!==ht[0]||ht[gr+1]!==ht[1])&&oi(ht,ht[0],ht[1],ht[2]),ht.length&&he.push(ht)}function $n(dt){const he=[];return he.size=dt.size,he.start=dt.start,he.end=dt.end,he}function Si(dt,he,pe,Fe,Ye,et){for(const nt of dt)Ir(nt,he,pe,Fe,Ye,et,!1)}function oi(dt,he,pe,Fe){dt.push(he,pe,Fe)}function ia(dt,he,pe,Fe,Ye,et){const nt=(et-he)/(Fe-he);return oi(dt,et,pe+(Ye-pe)*nt,1),nt}function Xr(dt,he,pe,Fe,Ye,et){const nt=(et-pe)/(Ye-pe);return oi(dt,he+(Fe-he)*nt,et,1),nt}function un(dt,he){const pe=[];for(let Fe=0;Fe0&&he.size<(Ye?nt:Fe))return void(pe.numPoints+=he.length/3);const ht=[];for(let it=0;itnt)&&(pe.numSimplified++,ht.push(he[it],he[it+1])),pe.numPoints++;Ye&&function(it,mt){let Gt=0;for(let Mt=0,gr=it.length,zr=gr-2;Mt0===mt)for(let Mt=0,gr=it.length;Mt24)throw new Error("maxZoom should be in the 0-24 range");if(pe.promoteId&&pe.generateId)throw new Error("promoteId and generateId cannot be used together.");let Ye=function(et,nt){const ht=[];if(et.type==="FeatureCollection")for(let it=0;it1&&console.time("creation"),zr=this.tiles[gr]=nn(he,pe,Fe,Ye,mt),this.tileCoords.push({z:pe,x:Fe,y:Ye}),Gt)){Gt>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",pe,Fe,Ye,zr.numFeatures,zr.numPoints,zr.numSimplified),console.timeEnd("creation"));const ks=`z${pe}`;this.stats[ks]=(this.stats[ks]||0)+1,this.total++}if(zr.source=he,et==null){if(pe===mt.indexMaxZoom||zr.numPoints<=mt.indexMaxPoints)continue}else{if(pe===mt.maxZoom||pe===et)continue;if(et!=null){const ks=et-pe;if(Fe!==nt>>ks||Ye!==ht>>ks)continue}}if(zr.source=null,he.length===0)continue;Gt>1&&console.time("clipping");const Hr=.5*mt.buffer/mt.extent,hr=.5-Hr,rt=.5+Hr,qt=1+Hr;let vr=null,wn=null,Cn=null,Qn=null,Ns=gs(he,Mt,Fe-Hr,Fe+rt,0,zr.minX,zr.maxX,mt),Jn=gs(he,Mt,Fe+hr,Fe+qt,0,zr.minX,zr.maxX,mt);he=null,Ns&&(vr=gs(Ns,Mt,Ye-Hr,Ye+rt,1,zr.minY,zr.maxY,mt),wn=gs(Ns,Mt,Ye+hr,Ye+qt,1,zr.minY,zr.maxY,mt),Ns=null),Jn&&(Cn=gs(Jn,Mt,Ye-Hr,Ye+rt,1,zr.minY,zr.maxY,mt),Qn=gs(Jn,Mt,Ye+hr,Ye+qt,1,zr.minY,zr.maxY,mt),Jn=null),Gt>1&&console.timeEnd("clipping"),it.push(vr||[],pe+1,2*Fe,2*Ye),it.push(wn||[],pe+1,2*Fe,2*Ye+1),it.push(Cn||[],pe+1,2*Fe+1,2*Ye),it.push(Qn||[],pe+1,2*Fe+1,2*Ye+1)}}getTile(he,pe,Fe){he=+he,pe=+pe,Fe=+Fe;const Ye=this.options,{extent:et,debug:nt}=Ye;if(he<0||he>24)return null;const ht=1<1&&console.log("drilling down to z%d-%d-%d",he,pe,Fe);let mt,Gt=he,Mt=pe,gr=Fe;for(;!mt&&Gt>0;)Gt--,Mt>>=1,gr>>=1,mt=this.tiles[Ft(Gt,Mt,gr)];return mt&&mt.source?(nt>1&&(console.log("found parent tile z%d-%d-%d",Gt,Mt,gr),console.time("drilling down")),this.splitTile(mt.source,Gt,Mt,gr,he,pe,Fe),nt>1&&console.timeEnd("drilling down"),this.tiles[it]?Qr(this.tiles[it],et):null):null}}function Ft(dt,he,pe){return 32*((1<mt.tags&&"3d_elevation_id"in mt.tags&&"source"in mt.tags&&mt.tags.source==="elevation",et=Fe.features.filter(mt=>Ye(mt));let nt={_geojsonTileLayer:Fe.features};et.length>0&&(nt={_geojsonTileLayer:Fe.features.filter(mt=>!Ye(mt)),hd_road_elevation:et});const ht=new Se(nt),it=function(mt){const Gt=new f.a$;for(const Mt of Object.keys(mt))Gt.writeMessage(3,yt,{name:Mt,features:mt[Mt]});return Gt.finish()}(nt).buffer;he(null,{vectorTile:ht,rawData:it})}class ws extends Q{constructor(he){super(he),this.loadVectorData=jo,this._dynamicIndex=new me}loadData(he,pe){const Fe=he&&he.request,Ye=Fe&&Fe.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(he,(et,nt)=>{if(et||!nt)return pe(et);if(typeof nt!="object")return pe(new Error(`Input data given to '${he.source}' is not a valid GeoJSON object.`));{try{if(he.filter){const it=f.X(he.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(it.result==="error")throw new Error(it.value.map(mt=>`${mt.key}: ${mt.message}`).join(", "));nt.features=nt.features.filter(mt=>it.value.evaluate({zoom:0},mt))}he.dynamic?(nt.type==="Feature"&&(nt={type:"FeatureCollection",features:[nt]}),he.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(nt.features,this.loaded),he.cluster&&(nt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=he.cluster?new $r(function({superclusterOptions:it,clusterProperties:mt}){if(!mt||!it)return it;const Gt={},Mt={},gr={accumulated:null,zoom:0},zr={properties:null},Hr=Object.keys(mt);for(const hr of Hr){const[rt,qt]=mt[hr],vr=f.X(qt),wn=f.X(typeof rt=="string"?[rt,["accumulated"],["get",hr]]:rt);Gt[hr]=vr.value,Mt[hr]=wn.value}return it.map=hr=>{zr.properties=hr;const rt={};for(const qt of Hr)rt[qt]=Gt[qt].evaluate(gr,zr);return rt},it.reduce=(hr,rt)=>{zr.properties=rt;for(const qt of Hr)gr.accumulated=hr[qt],hr[qt]=Mt[qt].evaluate(gr,zr)},it}(he)).load(nt.features):he.dynamic?this._dynamicIndex:function(it,mt){return new Us(it,mt)}(nt,he.geojsonVtOptions)}catch(it){return pe(it)}const ht={};if(Ye){const it=m(Fe);it&&(ht.resourceTiming={},ht.resourceTiming[he.source]=JSON.parse(JSON.stringify(it)))}pe(null,ht)}})}reloadTile(he,pe){const Fe=this.loaded;return Fe&&Fe[he.uid]?he.partial?pe(null,void 0):super.reloadTile(he,pe):this.loadTile(he,pe)}loadGeoJSON(he,pe){if(he.request)f.m(he.request,pe);else{if(typeof he.data!="string")return pe(new Error(`Input data given to '${he.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return pe(null,JSON.parse(he.data))}catch{return pe(new Error(`Input data given to '${he.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(he,pe){try{pe(null,this._geoJSONIndex.getClusterExpansionZoom(he.clusterId))}catch(Fe){pe(Fe)}}getClusterChildren(he,pe){try{pe(null,this._geoJSONIndex.getChildren(he.clusterId))}catch(Fe){pe(Fe)}}getClusterLeaves(he,pe){try{pe(null,this._geoJSONIndex.getLeaves(he.clusterId,he.limit,he.offset))}catch(Fe){pe(Fe)}}}class yi{constructor(he,pe,Fe){this.tileID=new f.aR(he.tileID.overscaledZ,he.tileID.wrap,he.tileID.canonical.z,he.tileID.canonical.x,he.tileID.canonical.y),this.tileZoom=he.tileZoom,this.uid=he.uid,this.zoom=he.zoom,this.canonical=he.tileID.canonical,this.pixelRatio=he.pixelRatio,this.tileSize=he.tileSize,this.source=he.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=he.projection,this.brightness=pe,this.worldview=Fe}parse(he,pe,Fe,Ye){this.status="parsing";const et=new f.aR(Fe.tileID.overscaledZ,Fe.tileID.wrap,Fe.tileID.canonical.z,Fe.tileID.canonical.x,Fe.tileID.canonical.y),nt=[],ht=pe.familiesBySource[Fe.source],it=new f.ff(et,Fe.promoteId);it.bucketLayerIDs=[],it.is3DTile=!0,f.fB(he).then(mt=>{const Gt=mt.json.extensionsUsed&&mt.json.extensionsUsed.includes("MAPBOX_mesh_features")||mt.json.asset.extras&&mt.json.asset.extras.MAPBOX_mesh_features,Mt=mt.json.extensionsUsed&&mt.json.extensionsUsed.includes("EXT_meshopt_compression"),gr=new f.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const zr in ht)for(const Hr of ht[zr]){const hr=Hr[0];it.bucketLayerIDs.push(Hr.map(vr=>f.F(vr.id,vr.scope))),hr.recalculate(gr,[]);const rt=f.fC(mt,1/f.cS(Fe.tileID.canonical)),qt=new f.fD(Hr,rt,et,Gt,Mt,this.brightness,it,this.worldview);Gt||(qt.needsUpload=!0),nt.push(qt),qt.evaluate(hr)}this.status="done",Ye(null,{buckets:nt,featureIndex:it,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(mt=>Ye(new Error(mt.message)))}}class Xn{constructor({actor:he,layerIndex:pe,availableImages:Fe,availableModels:Ye,brightness:et,worldview:nt}){this.actor=he,this.layerIndex=pe,this.availableImages=Fe,this.availableModels=Ye,this.brightness=et,this.loading={},this.loaded={},this.worldview=nt}loadTile(he,pe){const Fe=he.uid,Ye=this.loading[Fe]=new yi(he,this.brightness,this.worldview);f.b1(he.request,(et,nt)=>{const ht=!this.loading[Fe];return delete this.loading[Fe],ht||et?(Ye.status="done",ht||(this.loaded[Fe]=Ye),pe(et)):nt&&nt.byteLength!==0?void Ye.parse(nt,this.layerIndex,he,(it,mt)=>{Ye.status="done",this.loaded=this.loaded||{},this.loaded[Fe]=Ye,it||!mt?pe(it):pe(null,mt)}):(Ye.status="done",this.loaded[Fe]=Ye,pe())})}reloadTile(he,pe){const Fe=this.loaded,Ye=he.uid;if(Fe&&Fe[Ye]){const et=Fe[Ye];et.projection=he.projection,et.brightness=he.brightness;const nt=(ht,it)=>{et.reloadCallback&&(delete et.reloadCallback,this.loadTile(he,pe)),pe(ht,it)};et.status==="parsing"?et.reloadCallback=nt:et.status==="done"&&this.loadTile(he,pe)}}abortTile(he,pe){const Fe=he.uid;this.loading[Fe]&&delete this.loading[Fe],pe()}removeTile(he,pe){const Fe=this.loaded,Ye=he.uid;Fe&&Fe[Ye]&&delete Fe[Ye],pe()}}const Da=new Map,_c=new Map;class hl{constructor(he){this.self=he,this.actor=new f.A(he,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:Q,geojson:ws,"raster-dem":ee,"raster-array":de,"batched-model":Xn},this.workerSources={},this.self.registerWorkerSource=(pe,Fe)=>{if(this.workerSourceTypes[pe])throw new Error(`Worker source with name "${pe}" already registered.`);this.workerSourceTypes[pe]=Fe},this.self.registerRTLTextPlugin=pe=>{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=pe.applyArabicShaping,f.fF.processBidirectionalText=pe.processBidirectionalText,f.fF.processStyledBidirectionalText=pe.processStyledBidirectionalText;for(const Fe of this.rtlPluginParsingListeners)Fe(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(he,pe,Fe){delete this.layerIndexes[he],delete this.availableImages[he],delete this.availableModels[he],delete this.workerSources[he],Fe()}checkIfReady(he,pe,Fe){Fe()}setReferrer(he,pe){this.referrer=pe}spriteLoaded(he,pe){this.isSpriteLoaded[he]||(this.isSpriteLoaded[he]={});const{scope:Fe,isLoaded:Ye}=pe;if(this.isSpriteLoaded[he][Fe]=Ye,this.workerSources[he]&&this.workerSources[he][Fe])for(const et in this.workerSources[he][Fe]){const nt=this.workerSources[he][Fe][et];for(const ht in nt){const it=nt[ht];it instanceof Q&&(it.isSpriteLoaded=Ye,it.fire(new f.C("isSpriteLoaded")))}}}setImages(he,pe,Fe){this.availableImages[he]||(this.availableImages[he]={});const{scope:Ye,images:et}=pe;if(this.availableImages[he][Ye]=et,this.workerSources[he]&&this.workerSources[he][Ye]){for(const nt in this.workerSources[he][Ye]){const ht=this.workerSources[he][Ye][nt];for(const it in ht)ht[it].availableImages=et}Fe()}else Fe()}setModels(he,{scope:pe,models:Fe},Ye){if(this.availableModels[he]||(this.availableModels[he]={}),this.availableModels[he][pe]=Fe,this.workerSources[he]&&this.workerSources[he][pe]){for(const et in this.workerSources[he][pe]){const nt=this.workerSources[he][pe][et];for(const ht in nt)nt[ht].availableModels=Fe}Ye()}else Ye()}setProjection(he,pe){this.projections[he]=f.c0(pe)}setBrightness(he,pe,Fe){this.brightness=pe,Fe()}setContextParams(he,pe,Fe){this.maxUniformBufferBindings=pe.maxBindingPoints,this.maxUniformBlockSizeDwords=pe.maxUniformBlockSizeDwords,this.disableSymbolUBO=pe.disableSymbolUBO,Fe()}setWorldview(he,pe,Fe){this.worldview=pe,Fe()}setLayers(he,pe,Fe){this.getLayerIndex(he,pe.scope).replace(pe.layers,pe.options),Fe()}updateLayers(he,pe,Fe){this.getLayerIndex(he,pe.scope).update(pe.layers,pe.removedIds,pe.options),Fe()}loadTile(he,pe,Fe){pe.projection=this.projections[he]||this.defaultProjection,this.getWorkerSource(he,pe).loadTile(pe,Fe)}decodeRasterArray(he,pe,Fe){this.getWorkerSource(he,pe).decodeRasterArray(pe,Fe)}reloadTile(he,pe,Fe){pe.projection=this.projections[he]||this.defaultProjection,this.getWorkerSource(he,pe).reloadTile(pe,Fe)}abortTile(he,pe,Fe){this.getWorkerSource(he,pe).abortTile(pe,Fe)}removeTile(he,pe,Fe){this.getWorkerSource(he,pe).removeTile(pe,Fe)}removeSource(he,pe,Fe){if(!(this.workerSources[he]&&this.workerSources[he][pe.scope]&&this.workerSources[he][pe.scope][pe.type]&&this.workerSources[he][pe.scope][pe.type][pe.source]))return;const Ye=this.workerSources[he][pe.scope][pe.type][pe.source];delete this.workerSources[he][pe.scope][pe.type][pe.source],Ye.removeSource!==void 0?Ye.removeSource(pe,Fe):Fe()}loadTileProvider(he,pe,Fe){(async function(Ye,et){const nt=_c.get(Ye);if(nt)return nt;const ht=Da.get(Ye);if(ht!==void 0)return ht;const it=import(et).then(mt=>{const Gt=mt.default;if(typeof Gt!="function")throw new Error(`TileProvider "${Ye}" module must default-export a class`);if(typeof Gt.prototype.loadTile!="function")throw new Error(`TileProvider "${Ye}" class must have a loadTile method`);return _c.set(Ye,Gt),Gt}).finally(()=>{Da.delete(Ye)});return Da.set(Ye,it),it})(pe.name,pe.url).then(Ye=>{const et=new Ye(pe.options);return this.getWorkerSource(he,{type:pe.type,source:pe.source,scope:pe.scope},et),et.load&&pe.request?et.load({request:pe.request}):null}).then(Ye=>Fe(null,Ye)).catch(Ye=>Fe(Ye instanceof Error?Ye:new Error(typeof Ye=="string"?Ye:"Unknown error")))}loadWorkerSource(he,pe,Fe){try{this.self.importScripts(pe.url),Fe()}catch(Ye){Fe(Ye)}}syncRTLPluginState(he,pe,Fe){if(f.fF.isParsed())Fe(null,!0);else if(f.fF.isParsing())this.rtlPluginParsingListeners.push(Fe);else try{f.fF.setState(pe);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()?Fe(null,!0):this.rtlPluginParsingListeners.push(Fe))}catch(Ye){Fe(Ye)}}setConfig(he,pe){Object.assign(f.g,pe)}getAvailableImages(he,pe){this.availableImages[he]||(this.availableImages[he]={});let Fe=this.availableImages[he][pe];return Fe||(Fe=[]),Fe}getAvailableModels(he,pe){this.availableModels[he]||(this.availableModels[he]={});let Fe=this.availableModels[he][pe];return Fe||(Fe={}),Fe}getLayerIndex(he,pe){this.layerIndexes[he]||(this.layerIndexes[he]={});let Fe=this.layerIndexes[he][pe];return Fe||(Fe=this.layerIndexes[he][pe]=new j,Fe.scope=pe),Fe}getWorkerSource(he,pe,Fe){const{type:Ye,source:et,scope:nt}=pe,ht=this.workerSources;if(ht[he]||(ht[he]={}),ht[he][nt]||(ht[he][nt]={}),ht[he][nt][Ye]||(ht[he][nt][Ye]={}),this.isSpriteLoaded[he]||(this.isSpriteLoaded[he]={}),!ht[he][nt][Ye][et]){const it={send:(Gt,Mt,gr,zr,Hr,hr)=>this.actor.send(Gt,Mt,gr,he,Hr,hr),scheduler:this.actor.scheduler},mt=this.workerSourceTypes[Ye];if(!mt)throw new Error(`Unknown worker source type "${Ye}".`);ht[he][nt][Ye][et]=new mt({actor:it,layerIndex:this.getLayerIndex(he,nt),availableImages:this.getAvailableImages(he,nt),availableModels:this.getAvailableModels(he,nt),isSpriteLoaded:this.isSpriteLoaded[he][nt],tileProvider:Fe,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return ht[he][nt][Ye][et]}rasterizeImagesWorker(he,pe,Fe){const Ye=new Map;for(const[et,{image:nt,imageVariant:ht}]of pe.tasks.entries()){const it=this.imageRasterizer.rasterize(ht,nt,pe.scope,he);Ye.set(et,it)}Fe(void 0,Ye)}removeRasterizedImages(he,pe,Fe){this.imageRasterizer.removeImagesFromCacheByIds(pe.imageIds,pe.scope,he),Fe()}enforceCacheSizeLimit(he,pe){f.fH(pe)}getWorkerPerformanceMetrics(he,pe,Fe){Fe(void 0,void 0)}}return f.fE(self)&&(self.worker=new hl(self)),hl}),o(["./shared"],function(a){var f="3.22.0";const m={create:"create",load:"load",fullLoad:"fullLoad"},y={mark(_){performance.mark(_)},measure(_,d,g){performance.measure(_,d,g)}};function v(_){const d=_.name.split("?")[0];return a.a(d)&&d.includes("mapbox-gl.js")?"javascript":a.a(d)&&d.includes("mapbox-gl.css")?"css":a.b(d)?"fontRange":a.c(d)?"sprite":a.i(d)?"style":a.d(d)?"tilejson":"other"}var w,j={},A=function(){if(w)return j;function _(S){return!d(S)}function d(S){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var R,L,B=new Blob([""],{type:"text/javascript"}),U=URL.createObjectURL(B);try{L=new Worker(U),R=!0}catch{R=!1}return L&&L.terminate(),URL.revokeObjectURL(U),R}()?function(){var R=document.createElement("canvas");R.width=R.height=1;var L=R.getContext("2d");if(!L)return!1;var B=L.getImageData(0,0,1,1);return B&&B.width===R.width}()?(g[E=S&&S.failIfMajorPerformanceCaveat]===void 0&&(g[E]=function(R){var L,B=function(U){var W=document.createElement("canvas"),Z=Object.create(_.webGLContextAttributes);return Z.failIfMajorPerformanceCaveat=U,W.getContext("webgl2",Z)}(R);if(!B)return!1;try{L=B.createShader(B.VERTEX_SHADER)}catch{return!1}return!(!L||B.isContextLost())&&(B.shaderSource(L,"void main() {}"),B.compileShader(L),B.getShaderParameter(L,B.COMPILE_STATUS)===!0)}(E)),g[E]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var E}w=1,j.supported=_,j.notSupportedReason=d;var g={};return _.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},j}();function C(_,d,g){const S=document.createElement(_);return d!=null&&(S.className=d),g&&g.appendChild(S),S}function I(_,d,g){const S=document.createElementNS("http://www.w3.org/2000/svg",_);for(const E of Object.keys(d))S.setAttributeNS(null,E,String(d[E]));return g&&g.appendChild(S),S}const M=typeof document<"u"?document.documentElement&&document.documentElement.style:null,D=M&&M.userSelect!==void 0?"userSelect":"WebkitUserSelect";let F;function z(){M&&D&&(F=M[D],M[D]="none")}function q(){M&&D&&(M[D]=F)}function H(_){_.preventDefault(),_.stopPropagation(),window.removeEventListener("click",H,!0)}function K(){window.addEventListener("click",H,!0),window.setTimeout(()=>{window.removeEventListener("click",H,!0)},0)}function J(_,d){const g=_.getBoundingClientRect();return oe(_,g,d)}function Q(_,d){const g=_.getBoundingClientRect(),S=[];for(let E=0;Ethis._skuTokenExpiresAt}transformRequest(d,g){return this._transformRequestFn&&this._transformRequestFn(d,g)||{url:d}}normalizeStyleURL(d,g){if(!a.e(d))return d;const S=Se(d);return S.params.push(`sdk=js-${f}`),S.path=`/styles/v1${S.path}`,this._makeAPIURL(S,this._customAccessToken||g)}normalizeGlyphsURL(d,g){if(!a.e(d))return d;const S=Se(d);return S.path=`/fonts/v1${S.path}`,this._makeAPIURL(S,this._customAccessToken||g)}normalizeModelURL(d,g){if(!a.e(d))return d;const S=Se(d);return S.path=`/models/v1${S.path}`,this._makeAPIURL(S,this._customAccessToken||g)}normalizeSourceURL(d,g,S,E){if(!a.e(d))return d;const R=Se(d);return R.path=`/v4/${R.authority}.json`,R.params.push("secure"),S&&R.params.push(`language=${S}`),E&&R.params.push(`worldview=${E}`),this._makeAPIURL(R,this._customAccessToken||g)}normalizeIconsetURL(d,g){const S=Se(d);return a.e(d)?(S.path=`/styles/v1${S.path}/iconset.pbf`,this._makeAPIURL(S,this._customAccessToken||g)):ve(S)}normalizeSpriteURL(d,g,S,E){const R=Se(d);return a.e(d)?(R.path=`/styles/v1${R.path}/sprite${g}${S}`,this._makeAPIURL(R,this._customAccessToken||E)):(R.path+=`${g}${S}`,ve(R))}normalizeTileURL(d,g,S){if(this._isSkuTokenExpired()&&this._createSkuToken(),d&&!a.e(d))return d;const E=Se(d);E.path=E.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${g||S&&E.authority!=="raster"&&S===512?"@2x":""}${a.k.supported?".webp":"$1"}`),E.authority==="raster"?E.path=`/${a.g.RASTER_URL_PREFIX}${E.path}`:E.authority==="rasterarrays"?E.path=`/${a.g.RASTERARRAYS_URL_PREFIX}${E.path}`:E.authority==="3dtiles"?E.path=`/${a.g.TILES3D_URL_PREFIX}${E.path}`:(E.path=E.path.replace(/^.+\/v4\//,"/"),E.path=`/${a.g.TILE_URL_VERSION}${E.path}`);const R=this._customAccessToken||function(L){for(const B of L){const U=B.match(/^access_token=(.*)$/);if(U)return U[1]}return null}(E.params)||a.g.ACCESS_TOKEN;return a.g.REQUIRE_ACCESS_TOKEN&&R&&this._skuToken&&E.params.push(`sku=${this._skuToken}`),this._makeAPIURL(E,R)}canonicalizeTileURL(d,g){const S=Se(d);if(!S.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!S.path.match(/\.[\w]+$/))return d;let E="mapbox://";S.path.match(/^\/raster\/v1\//)?E+=`raster/${S.path.replace(`/${a.g.RASTER_URL_PREFIX}/`,"")}`:S.path.match(/^\/rasterarrays\/v1\//)?E+=`rasterarrays/${S.path.replace(`/${a.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:E+=`tiles/${S.path.replace(`/${a.g.TILE_URL_VERSION}/`,"")}`;let R=S.params;return g&&(R=R.filter(L=>!L.match(/^access_token=/))),R.length&&(E+=`?${R.join("&")}`),E}canonicalizeTileset(d,g){const S=!!g&&a.e(g),E=[];for(const R of d.tiles||[])a.f(R)?E.push(this.canonicalizeTileURL(R,S)):E.push(R);return E}_makeAPIURL(d,g){const S="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",E=Se(a.g.API_URL);if(d.protocol=E.protocol,d.authority=E.authority,d.protocol==="http"){const R=d.params.indexOf("secure");R>=0&&d.params.splice(R,1)}if(E.path!=="/"&&(d.path=`${E.path}${d.path}`),!a.g.REQUIRE_ACCESS_TOKEN)return ve(d);if(g=g||a.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!g)throw new Error(`An API access token is required to use Mapbox GL. ${S}`);if(g[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${S}`)}return d.params=d.params.filter(R=>R.indexOf("access_token")===-1),d.params.push(`access_token=${g||""}`),ve(d)}}const Le=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Se(_){const d=_.match(Le);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 ve(_){const d=_.params.length?`?${_.params.join("&")}`:"";return`${_.protocol}://${_.authority}${_.path}${d}`}const me="mapbox.eventData";function ke(_){if(!_)return null;const d=_.split(".");if(!d||d.length!==3)return null;try{return JSON.parse(a.l(d[1]))}catch{return null}}function Pe(_){return!(!a.g.EVENTS_URL||!_&&!a.g.ACCESS_TOKEN)}class Ee{constructor(d){this.type=d,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(d){const g=ke(a.g.ACCESS_TOKEN);let S="";return S=g&&g.u?a.j(g.u):a.g.ACCESS_TOKEN||"",d?`${me}.${d}:${S}`:`${me}:${S}`}fetchEventData(){const d=a.s("localStorage"),g=this.getStorageKey(),S=this.getStorageKey("uuid"),E=this.getStorageKey("uuidTimestamp");if(d)try{const R=localStorage.getItem(g);R&&(this.eventData=JSON.parse(R));const L=localStorage.getItem(S);L&&(this.anonId=L);const B=localStorage.getItem(E);B&&(this.anonIdTimestamp=Number(B));const U=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(g,JSON.stringify(this.eventData)),L&&localStorage.setItem(E,L.toString())}catch{a.w("Unable to write to LocalStorage")}}processRequests(d){}postEvent(d,g,S,E){if(!a.g.EVENTS_URL)return;const R=Se(a.g.EVENTS_URL);R.params.push(`access_token=${E||a.g.ACCESS_TOKEN||""}`);const L={event:this.type,created:new Date(d).toISOString()},B=g?Object.assign(L,g):L,U={url:ve(R),headers:{"Content-Type":"text/plain"},body:JSON.stringify([B])};this.pendingRequest=a.p(U,W=>{this.pendingRequest=null,S(W),this.saveEventData(),this.processRequests(E)})}queueRequest(d,g){this.queue.push(d),this.processRequests(g)}}class xe extends Ee{constructor(d){super("metrics"),d&&(this.data=d)}postMetricsEvent(d){if(!Pe(d))return;this.anonId||this.fetchEventData(),a.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:S}=this.queue.shift();this.postEvent(g,S,()=>{},d)}}const Ue=new class extends Ee{constructor(_){super("appUserTurnstile"),this._customAccessToken=_}postTurnstileEvent(_,d){Pe(d)&&Array.isArray(_)&&_.some(g=>a.e(g)||a.f(g))&&this.queueRequest(Date.now(),d)}processRequests(_){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const d=ke(a.g.ACCESS_TOKEN),g=d?d.u:a.g.ACCESS_TOKEN;let S=g!==this.eventData.tokenU;a.v(this.anonId)||(this.refreshUUID(),S=!0);const E=this.queue.shift();if(this.eventData.lastSuccess){const R=new Date(this.eventData.lastSuccess),L=new Date(E),B=(E-this.eventData.lastSuccess)/864e5;S=S||B>=1||B<-1||R.getDate()!==L.getDate()}else S=!0;S?this.postEvent(E,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:de,"enabled.telemetry":!1,userId:this.anonId},R=>{R||(this.eventData.lastSuccess=E,this.eventData.tokenU=g)},_):this.processRequests()}},Ze=Ue.postTurnstileEvent.bind(Ue),lt=new class extends Ee{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(_,d,g,S){this.skuToken=d,this.errorCb=S,a.g.EVENTS_URL&&(g||a.g.ACCESS_TOKEN?this.queueRequest({id:_,timestamp:Date.now()},g):this.errorCb(new Error(ye)))}processRequests(_){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(),a.v(this.anonId)||this.refreshUUID(),this.postEvent(g,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:de,skuToken:this.skuToken,userId:this.anonId},S=>{S?this.errorCb(S):d&&(this.success[d]=!0)},_))}remove(){this.errorCb=null}},wt=lt.postMapLoadEvent.bind(lt),yt=new class extends Ee{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(_){let d=this.mapInstanceIdMap.get(_);return d||(d=a.u(),this.mapInstanceIdMap.set(_,d)),d}getEventId(_){const d=this.eventIdPerMapInstanceMap.get(_)||0;return this.eventIdPerMapInstanceMap.set(_,d+1),d}postStyleLoadEvent(_,d){const{map:g,style:S,importedStyles:E}=d;if(!Pe(_))return;const R=this.getMapInstanceId(g),L={mapInstanceId:R,eventId:this.getEventId(R),style:S};E.length&&(L.importedStyles=E),this.queueRequest({timestamp:Date.now(),payload:L},_)}processRequests(_){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:d,payload:g}=this.queue.shift();this.postEvent(d,g,()=>{},_)}},gt=yt.postStyleLoadEvent.bind(yt),ft=new xe({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),kt=ft.postMetricsEvent.bind(ft),Vt=new xe({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),xt=Vt.postMetricsEvent.bind(Vt),or=new class extends Ee{constructor(){super("gljs.performance")}postPerformanceEvent(_,d){Pe(_)&&this.queueRequest({timestamp:Date.now(),performanceData:d},_)}processRequests(_){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:d,performanceData:g}=this.queue.shift(),S=function(E){const R=performance.getEntriesByType("resource"),L=performance.getEntriesByType("mark"),B=function(ie){const ce={};if(ie){for(const le in ie)if(le!=="other")for(const be of ie[le]){const _e=`${le}ResolveRangeMin`,Re=`${le}ResolveRangeMax`,Me=`${le}RequestCount`,je=`${le}RequestCachedCount`;ce[_e]=Math.min(ce[_e]||1/0,be.startTime),ce[Re]=Math.max(ce[Re]||-1/0,be.responseEnd);const Xe=$e=>{ce[$e]===void 0&&(ce[$e]=0),++ce[$e]};be.transferSize!==void 0&&be.transferSize===0&&Xe(je),Xe(Me)}}return ce}(function(ie,ce){const le={};if(ie)for(const be of ie){const _e=ce(be);le[_e]===void 0&&(le[_e]=[]),le[_e].push(be)}return le}(R,v)),U=window.devicePixelRatio,W=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Z=W?W.effectiveType:void 0,ne={counters:[],metadata:[],attributes:[]},re=(ie,ce,le)=>{le!=null&&ie.push({name:ce,value:le.toString()})};for(const ie in B)re(ne.counters,ie,B[ie]);if(E.interactionRange[0]!==1/0&&E.interactionRange[1]!==-1/0&&(re(ne.counters,"interactionRangeMin",E.interactionRange[0]),re(ne.counters,"interactionRangeMax",E.interactionRange[1])),L)for(const ie of Object.values(m)){const ce=L.find(le=>le.name===ie);ce&&re(ne.counters,ie,ce.startTime)}return re(ne.counters,"visibilityHidden",E.visibilityHidden),re(ne.attributes,"style",function(ie){if(ie)for(const ce of ie){const le=ce.name.split("?")[0];if(a.i(le)){const be=le.split("/").slice(-2);if(be.length===2)return`mapbox://styles/${be[0]}/${be[1]}`}}}(R)),re(ne.attributes,"terrainEnabled",E.terrainEnabled?"true":"false"),re(ne.attributes,"fogEnabled",E.fogEnabled?"true":"false"),re(ne.attributes,"projection",E.projection),re(ne.attributes,"zoom",E.zoom),re(ne.metadata,"devicePixelRatio",U),re(ne.metadata,"connectionEffectiveType",Z),re(ne.metadata,"navigatorUserAgent",navigator.userAgent),re(ne.metadata,"screenWidth",window.screen.width),re(ne.metadata,"screenHeight",window.screen.height),re(ne.metadata,"windowWidth",window.innerWidth),re(ne.metadata,"windowHeight",window.innerHeight),re(ne.metadata,"mapWidth",E.width/U),re(ne.metadata,"mapHeight",E.height/U),re(ne.metadata,"webglRenderer",E.renderer),re(ne.metadata,"webglVendor",E.vendor),re(ne.metadata,"sdkVersion",f),re(ne.metadata,"sdkIdentifier","mapbox-gl-js"),ne}(g);for(const E of S.metadata);for(const E of S.counters);for(const E of S.attributes);this.postEvent(d,S,()=>{},_)}},Tr=or.postPerformanceEvent.bind(or),rn=new class extends Ee{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(_,d,g,S){if(!a.g.API_URL||!a.g.SESSION_PATH)return;const E=Se(a.g.API_URL+a.g.SESSION_PATH);E.params.push(`sku=${d||""}`),E.params.push(`access_token=${S||a.g.ACCESS_TOKEN||""}`);const R={url:ve(E),headers:{"Content-Type":"text/plain"}};this.pendingRequest=a.h(R,L=>{this.pendingRequest=null,g(L),this.saveEventData(),this.processRequests(S)})}getSessionAPI(_,d,g,S){this.skuToken=d,this.errorCb=S,a.g.EVENTS_URL&&a.g.SESSION_PATH&&a.g.API_URL&&(g||a.g.ACCESS_TOKEN?this.queueRequest({id:_,timestamp:Date.now()},g):this.errorCb(new Error(ye)))}processRequests(_){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,S=>{S?this.errorCb(S):d&&(this.success[d]=!0)},_)}remove(){this.errorCb=null}},Lr=rn.getSessionAPI.bind(rn),$r=new Set;function qr(_,d){d?$r.add(_):$r.delete(_)}class Nn{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(a.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 tt(_){const{userImage:d}=_;return!!(d&&d.render&&d.render())&&(_.data.replace(new Uint8Array(d.data.buffer)),!0)}const Tt={workerUrl:"",workerClass:null,workerParams:void 0};function Zt(_){return Tt.workerClass!=null?new Tt.workerClass:new self.Worker(Tt.workerUrl,Object.assign({name:_},Tt.workerParams))}const ar="mapboxgl_preloaded_worker_pool";class Wt{constructor(d){this.active={},this.name=d}acquire(d,g=Wt.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{g.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[ar]}numActive(){return Object.keys(this.active).length}}Wt.workerCount=2;class Kt{constructor(d,g,S="Worker",E=Wt.workerCount){this.workerPool=d,this.actors=[],this.currentActor=0,this.id=a.r();const R=this.workerPool.acquire(this.id,E);for(let L=0;L{this.ready=!0})}broadcast(d,g,S){a.t(this.actors,(E,R)=>{E.send(d,g,R)},S=S||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 At,pr;function yn(){return At||(At=new Wt),At}Kt.Actor=a.A;class Gn extends a.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 a.x,this.dirty=!0,this.spriteFormat=d,d!=="raster"&&a.y()&&(this.imageRasterizerDispatcher=new Kt((pr||(pr=new Wt("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 a.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 S of g.values())S.hasPendingRequests()&&d.push(S);return d}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new a.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:S,callback:E}of this.requestors)this._notify(S,g,E);this.requestors=[]}}hasImage(d,g){return!!this.getImage(d,g)}getImage(d,g){return this.images.get(g).get(d.toString())}addImage(d,g,S){if(this._validate(d,S)){this.images.get(g).set(d.toString(),S);const E=this.imageVersions.get(g),R=E.get(d.toString())||0;E.set(d.toString(),R+1)}}_validate(d,g){let S=!0;return this._validateStretch(g.stretchX,g.data&&g.data.width)||(this.fire(new a.B(new Error(`Image "${d.name}" has invalid "stretchX" value`))),S=!1),this._validateStretch(g.stretchY,g.data&&g.data.height)||(this.fire(new a.B(new Error(`Image "${d.name}" has invalid "stretchY" value`))),S=!1),this._validateContent(g.content,g)||(this.fire(new a.B(new Error(`Image "${d.name}" has invalid "content" value`))),S=!1),S}_validateStretch(d,g){if(!d)return!0;let S=0;for(const E of d){if(E[0]a.I.from(g))}getImageVersions(d){const g=this.imageVersions.get(d);if(g)return g}getImages(d,g,S){const E=[],R=[],L=this.imageProviders.get(g);for(const Z of d){if(!Z.iconsetId){E.push(Z);continue}const ne=L.get(Z.iconsetId);ne&&(this.getImage(Z,g)?R.push(Z):ne.addPendingRequest(Z))}if(E.length===0)return void this._notify(R,g,S);let B=!0;const U=!!this.loaded.get(g),W=this.images.get(g);if(!U)for(const Z of E)W.has(Z.toString())||(B=!1);U||B?this._notify(E,g,S):this.requestors.push({ids:E,scope:g,callback:S})}rasterizeImages(d,g){const S=new Map,{tasks:E,scope:R}=d;for(const[L,B]of E.entries()){const U=this.getImage(B.id,R);U&&S.set(L,{image:U,imageVariant:B})}this._rasterizeImages(R,S,g)}_rasterizeImages(d,g,S){if(a.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:g,scope:d},S);else{const E=new Map;for(const[R,{image:L,imageVariant:B}]of g.entries())E.set(R,this.imageRasterizer.rasterize(B,L,d,0));S(void 0,E)}}getUpdatedImages(d){return this.updatedImages.get(d)||new Set}_notify(d,g,S){const E=this.images.get(g),R=new Map;for(const L of d){if(!E.get(L.toString())){if(L.iconsetId)continue;this.fire(new a.C("styleimagemissing",{id:L.name}))}const B=E.get(L.toString());if(!B){a.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 U={data:B.usvg?null:B.data.clone(),pixelRatio:B.pixelRatio,sdf:B.sdf,usvg:B.usvg,stretchX:B.stretchX,stretchY:B.stretchY,content:B.content,hasRenderCallback:!!(B.userImage&&B.userImage.render)};B.usvg&&Object.assign(U,{width:B.icon.usvg_tree.width,height:B.icon.usvg_tree.height}),R.set(a.I.toString(L),U)}S(null,{images:R,versions:this.getImageVersions(g)})}getPixelSize(d){const{width:g,height:S}=this.atlasImage.get(d);return{width:g,height:S}}getPattern(d,g,S){const E=d.toString(),R=this.patterns.get(g),L=R.get(E),B=this.getImage(d,g);if(!B)return null;if(L){if(L.position.version===B.version)return L.position;L.position.version=B.version}else{if(B.usvg&&!B.data){const U=this.getPatternInFlightId(E,g);if(this.patternsInFlight.has(U))return null;this.patternsInFlight.add(U);const W=new a.D(d).scaleSelf(a.o.devicePixelRatio),Z=new Map([[W.toString(),{image:B,imageVariant:W}]]);return this._rasterizeImages(g,Z,(ne,re)=>this.storePatternImage(W,g,B,S,re)),null}this.storePattern(d,g,B)}return this._updatePatternAtlas(g,S),R.get(E).position}getPatternInFlightId(d,g){return a.F(d,g)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(d,g,S,E,R){const L=d.toString(),B=R?R.get(L):void 0;B&&(S.data=B,this.storePattern(d.id,g,S),this._updatePatternAtlas(g,E),this.patternsInFlight.delete(this.getPatternInFlightId(d.id.toString(),g)))}storePattern(d,g,S){const E={w:S.data.width+2*a.G,h:S.data.height+2*a.G,x:0,y:0},R=new a.H(E,S,a.G);this.patterns.get(g).set(d.toString(),{bin:E,position:R})}destroyAtlasTextures(){for(const d of this.atlasTexture.values())d&&d.destroy();this.atlasTexture.clear()}bind(d,g){const S=d.gl;let E=this.atlasTexture.get(g);E?this.dirty&&(E.update(this.atlasImage.get(g)),this.dirty=!1):(E=new a.T(d,this.atlasImage.get(g),S.RGBA8),this.atlasTexture.set(g,E)),E.bind(S.LINEAR,S.CLAMP_TO_EDGE)}_updatePatternAtlas(d,g){const S=this.patterns.get(d),E=Array.from(S.values()).map(({bin:W})=>W),{w:R,h:L}=a.J(E),B=this.atlasImage.get(d);B.resize({width:R||1,height:L||1});const U=this.images.get(d);for(const[W,{bin:Z,position:ne}]of S.entries()){let re=ne.padding;const ie=Z.x+re,ce=Z.y+re,le=U.get(W).data,be=le.width,_e=le.height;re=re>1?re-1:re,a.q.copy(le,B,{x:0,y:0},{x:ie,y:ce},{width:be,height:_e},g),a.q.copy(le,B,{x:0,y:_e-re},{x:ie,y:ce-re},{width:be,height:re},g),a.q.copy(le,B,{x:0,y:0},{x:ie,y:ce+_e},{width:be,height:re},g),a.q.copy(le,B,{x:be-re,y:0},{x:ie-re,y:ce},{width:re,height:_e},g),a.q.copy(le,B,{x:0,y:0},{x:ie+be,y:ce},{width:re,height:_e},g),a.q.copy(le,B,{x:be-re,y:_e-re},{x:ie-re,y:ce-re},{width:re,height:re},g),a.q.copy(le,B,{x:0,y:_e-re},{x:ie+be,y:ce-re},{width:re,height:re},g),a.q.copy(le,B,{x:0,y:0},{x:ie+be,y:ce+_e},{width:re,height:re},g),a.q.copy(le,B,{x:be-re,y:0},{x:ie-re,y:ce+_e},{width:re,height:re},g)}this.dirty=!0}beginFrame(){for(const d of this.images.keys())this.callbackDispatchedThisFrame.set(d,new Set)}dispatchRenderCallbacks(d,g){const S=this.images.get(g);for(const E of d){if(this.callbackDispatchedThisFrame.get(g).has(E.toString()))continue;this.callbackDispatchedThisFrame.get(g).add(E.toString());const R=S.get(E.toString());tt(R)&&this.updateImage(E,g,R)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Bn(_){const d=_.value,g=_.valueSpec,S=_.style,E=_.styleSpec,R=_.key,L=_.arrayElementValidator||ws;if(!Array.isArray(d))return[new a.V(R,d,`array expected, ${a.M(d)} found`)];if(g.length&&d.length!==g.length)return[new a.V(R,d,`array length ${g.length} expected, length ${d.length} found`)];if(g["min-length"]&&d.lengthE)return[new a.V(d,g,`${g} is greater than the maximum value ${E}`)]}return[]}function sa(_){const d=_.key,g=_.value;if(!a.K(g))return[new a.V(d,g,`object expected, ${a.M(g)} found`)];const S=_.valueSpec,E=a.L(g.type);let R,L,B,U={};const W=E!=="categorical"&&g.property===void 0,Z=!W,ne=function(le){const be=le.stops;return Array.isArray(be)&&Array.isArray(be[0])&&a.K(be[0][0])}(g),re=yi({key:_.key,value:_.value,valueSpec:_.styleSpec.function,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{stops:function(le){if(E==="identity")return[new a.V(le.key,le.value,'identity function may not have a "stops" property')];let be=[];const _e=le.value;return be=be.concat(Bn({key:le.key,value:_e,valueSpec:le.valueSpec,style:le.style,styleSpec:le.styleSpec,arrayElementValidator:ie})),Array.isArray(_e)&&_e.length===0&&be.push(new a.V(le.key,_e,"array must have at least one stop")),be},default:function(le){return ws({key:le.key,value:le.value,valueSpec:S,style:le.style,styleSpec:le.styleSpec})}}});return E==="identity"&&W&&re.push(new a.V(_.key,_.value,'missing required property "property"')),E==="identity"||g.stops||re.push(new a.V(_.key,_.value,'missing required property "stops"')),E==="exponential"&&S.expression&&!a.O(S)&&re.push(new a.V(_.key,_.value,"exponential functions not supported")),_.styleSpec.$version>=8&&(Z&&!a.Q(S)?re.push(new a.V(_.key,_.value,"property functions not supported")):W&&!a.S(S)&&re.push(new a.V(_.key,_.value,"zoom functions not supported"))),E!=="categorical"&&!ne||g.property!==void 0||re.push(new a.V(_.key,_.value,'"property" property is required')),re;function ie(le){let be=[];const _e=le.value,Re=le.key;if(!Array.isArray(_e))return[new a.V(Re,_e,`array expected, ${a.M(_e)} found`)];if(_e.length!==2)return[new a.V(Re,_e,`array length 2 expected, length ${_e.length} found`)];if(ne){if(!a.K(_e[0]))return[new a.V(Re,_e,`object expected, ${a.M(_e[0])} found`)];const Me=_e[0];if(Me.zoom===void 0)return[new a.V(Re,_e,"object stop key must have zoom")];if(Me.value===void 0)return[new a.V(Re,_e,"object stop key must have value")];const je=a.L(Me.zoom);if(typeof je!="number")return[new a.V(Re,Me.zoom,"stop zoom values must be numbers")];if(B&&B>je)return[new a.V(Re,Me.zoom,"stop zoom values must appear in ascending order")];je!==B&&(B=je,L=void 0,U={}),be=be.concat(yi({key:`${Re}[0]`,value:_e[0],valueSpec:{zoom:{}},style:le.style,styleSpec:le.styleSpec,objectElementValidators:{zoom:Rs,value:ce}}))}else be=be.concat(ce({key:`${Re}[0]`,value:_e[0],style:le.style,styleSpec:le.styleSpec},_e));return a.U(a.W(_e[1]))?be.concat([new a.V(`${Re}[1]`,_e[1],"expressions are not allowed in function stops.")]):be.concat(ws({key:`${Re}[1]`,value:_e[1],valueSpec:S,style:le.style,styleSpec:le.styleSpec}))}function ce(le,be){const _e=a.M(le.value),Re=a.L(le.value),Me=le.value!==null?le.value:be;if(R){if(_e!==R)return[new a.V(le.key,Me,`${_e} stop domain type must match previous stop domain type ${R}`)]}else R=_e;if(_e!=="number"&&_e!=="string"&&_e!=="boolean"&&typeof Re!="number"&&typeof Re!="string"&&typeof Re!="boolean")return[new a.V(le.key,Me,"stop domain value must be a number, string, or boolean")];if(_e!=="number"&&E!=="categorical"){let je=`number expected, ${_e} found`;return a.Q(S)&&E===void 0&&(je+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new a.V(le.key,Me,je)]}return E!=="categorical"||_e!=="number"||typeof Re=="number"&&isFinite(Re)&&Math.floor(Re)===Re?E!=="categorical"&&_e==="number"&&typeof Re=="number"&&typeof L=="number"&&L!==void 0&&Renew a.V(`${_.key}${S.key}`,_.value,S.message));const g=d.value.expression||d.value._styleExpression.expression;if(_.expressionContext==="property"&&_.propertyKey==="text-font"&&!g.outputDefined())return[new a.V(_.key,_.value,`Invalid data expression for "${_.propertyKey}". Output values must be contained as literals within the expression.`)];if(_.expressionContext==="property"&&_.propertyType==="layout"&&!a.$(g))return[new a.V(_.key,_.value,'"feature-state" data expressions are not supported with layout properties.')];if(_.expressionContext==="filter")return zi(g,_);if(_.expressionContext==="appearance")return Ir(g,_);if(_.expressionContext&&_.expressionContext.indexOf("cluster")===0){if(!a.Z(g,["zoom","feature-state"]))return[new a.V(_.key,_.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(_.expressionContext==="cluster-initial"&&!a._(g))return[new a.V(_.key,_.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function zi(_,d){const g=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(d.valueSpec&&d.valueSpec.expression)for(const E of d.valueSpec.expression.parameters)g.delete(E);if(g.size===0)return[];const S=[];return _ instanceof a.a0&&g.has(_.name)?[new a.V(d.key,d.value,`["${_.name}"] expression is not supported in a filter for a ${d.object.type} layer with id: ${d.object.id}`)]:(_.eachChild(E=>{S.push(...zi(E,d))}),S)}function Ir(_,d){const g=new Set;if(d.valueSpec&&d.valueSpec.expression)for(const E of d.valueSpec.expression.parameters)g.add(E);if(g.size===0)return[];const S=[];return _ instanceof a.a0&&!g.has(_.name)?[new a.V(d.key,d.value,`["${_.name}"] is not an allowed parameter`)]:(_.eachChild(E=>{S.push(...Ir(E,d))}),S)}function $n(_){const d=_.key,g=_.value,S=_.valueSpec,E=[];return Array.isArray(S.values)?S.values.indexOf(a.L(g))===-1&&E.push(new a.V(d,g,`expected one of [${S.values.join(", ")}], ${JSON.stringify(g)} found`)):Object.keys(S.values).indexOf(a.L(g))===-1&&E.push(new a.V(d,g,`expected one of [${Object.keys(S.values).join(", ")}], ${JSON.stringify(g)} found`)),E}function Si(_){return a.a4(a.W(_.value))?gs(Object.assign({},_,{expressionContext:"filter",valueSpec:_.styleSpec[`filter_${_.layerType||"fill"}`]})):oi(_)}function oi(_){const d=_.value,g=_.key;if(!Array.isArray(d))return[new a.V(g,d,`array expected, ${a.M(d)} found`)];if(d.length<1)return[new a.V(g,d,"filter array must have at least 1 element")];const S=_.styleSpec;let E=$n({key:`${g}[0]`,value:d[0],valueSpec:S.filter_operator});const R=()=>{d.length>=2&&(a.a2(d[1])||E.push(new a.V(`${g}[1]`,d[1],`string expected, ${a.M(d[1])} found`)));for(let L=2;L":case">=":d.length>=2&&a.L(d[1])==="$type"&&E.push(new a.V(g,d,`"$type" cannot be use with operator "${d[0]}"`)),d.length!==3&&E.push(new a.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),R();break;case"==":case"!=":d.length!==3&&E.push(new a.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),R();break;case"in":case"!in":R();break;case"any":case"all":case"none":for(let L=1;L{W in g&&d.push(new a.V(S,g[W],`"${W}" is prohibited for ref layers`))}),E.layers.forEach(W=>{a.L(W.id)===B&&(U=W)}),U?U.ref?d.push(new a.V(S,g.ref,"ref cannot reference another ref layer")):L=a.L(U.type):typeof B=="string"&&d.push(new a.V(S,g.ref,`ref layer "${B}" not found`))}else if(L!=="background"&&L!=="sky"&&L!=="slot")if(g.source)if(a.a2(g.source)){const U=E.sources&&E.sources[g.source],W=U&&a.L(U.type);U?W==="vector"&&L==="raster"?d.push(new a.V(S,g.source,`layer "${g.id}" requires a raster source`)):W==="raster"&&L!=="raster"?d.push(new a.V(S,g.source,`layer "${g.id}" requires a vector source`)):W!=="vector"||g["source-layer"]?W==="raster-dem"&&L!=="hillshade"?d.push(new a.V(S,g.source,"raster-dem source can only be used with layer type 'hillshade'.")):W!=="raster-array"||["raster","raster-particle"].includes(L)?L==="line"&&g.paint&&(g.paint["line-gradient"]||g.paint["line-trim-offset"])&&W==="geojson"&&!U.lineMetrics?d.push(new a.V(S,g,`layer "${g.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):L==="raster-particle"&&W!=="raster-array"&&d.push(new a.V(S,g.source,`layer "${g.id}" requires a 'raster-array' source.`)):d.push(new a.V(S,g.source,"raster-array source can only be used with layer type 'raster'.")):d.push(new a.V(S,g,`layer "${g.id}" must specify a "source-layer"`)):d.push(new a.V(S,g.source,`source "${g.source}" not found`))}else d.push(new a.V(`${S}.source`,g.source,'"source" must be a string'));else d.push(new a.V(S,g,'missing required property "source"'));return d=d.concat(yi({key:S,value:g,valueSpec:R.layer,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{"*":()=>[],type:()=>ws({key:`${S}.type`,value:g.type,valueSpec:R.layer.type,style:_.style,styleSpec:_.styleSpec,object:g,objectKey:"type"}),filter:U=>Si(Object.assign({layerType:L},U)),layout:U=>yi({layer:g,key:U.key,value:U.value,valueSpec:{},style:U.style,styleSpec:U.styleSpec,objectElementValidators:{"*":W=>un(Object.assign({layerType:L},W))}}),paint:U=>yi({layer:g,key:U.key,value:U.value,valueSpec:{},style:U.style,styleSpec:U.styleSpec,objectElementValidators:{"*":W=>Xr(Object.assign({layerType:L,layer:g},W))}}),appearances(U){const W=Bn({key:U.key,value:U.value,valueSpec:U.valueSpec,style:U.style,styleSpec:U.styleSpec,arrayElementValidator:re=>function(ie){const{key:ce,layer:le,layerType:be}=ie,_e=a.L(ie.value),Re=a.L(_e.name),Me=a.L(_e.condition),je=yi({key:ce,value:_e,valueSpec:ie.styleSpec.appearance,style:ie.style,styleSpec:ie.styleSpec,objectElementValidators:{condition:Xe=>function($e){const Ke=[];return Ke.push(...gs({key:$e.key,value:$e.object.condition,valueSpec:a.a8.appearance.condition,expressionContext:"appearance"})),Ke}(Object.assign({layer:le,layerType:be},Xe)),properties:Xe=>function($e){const Ke=[],{styleSpec:De,layer:Be,layerType:Ge}=$e,ot=De[`paint_${Ge}`],Je=De[`layout_${Ge}`],St=$e.object[$e.objectKey];for(const pt in St){const Ot=pt in ot?"paint":pt in Je?"layout":void 0;if(!Ot){Ke.push(new a.V($e.key,pt,`unknown property "${pt}" for layer type "${Ge}"`));continue}const Ut=Object.assign({},$e,{key:`${$e.key}.${pt}`,object:St,objectKey:pt,layer:Be,layerType:Ge,value:St[pt],valueSpec:Ot==="paint"?ot[pt]:Je[pt]});Ke.push(...ia(Ut,Ot))}return Ke}(Object.assign({layer:le,layerType:be},Xe))}});return Re!=="hidden"&&Me===void 0&&je.push(new a.V(ie.key,"name",'Appearance with name different than "hidden" must have a condition')),je}(Object.assign({layerType:L,layer:g},re))}),Z=Array.isArray(U.value)?U.value:[],ne=new Set;return Z.forEach((re,ie)=>{const ce=a.L(re.name);if(ce)if(ne.has(ce)){const le=a.L(g.id);W.push(new a.V(U.key,ce,`Duplicated appearance name "${ce}" for layer "${le}"`))}else ne.add(ce)}),W}}})),d}function Qr({key:_,value:d}){return a.a2(d)?[]:[new a.V(_,d,`string expected, ${a.M(d)} found`)]}const cs={promoteId:function _({key:d,value:g}){if(a.a2(g))return Qr({key:d,value:g});if(Array.isArray(g)){const E=[],R=a.W(g),L=a.X(R);return L.result==="error"?(L.value.forEach(B=>{E.push(new a.V(`${d}${B.key}`,null,`${B.message}`))}),E):(a.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"])||E.push(new a.V(`${d}`,null,"promoteId expression should be only feature dependent")),E)}if(!a.K(g))return[new a.V(d,g,`string, expression or object expected, "${a.M(g)}" found`)];const S=[];for(const E in g)S.push(..._({key:`${d}.${E}`,value:g[E]}));return S}};function nn(_){const d=_.value,g=_.key,S=_.styleSpec,E=_.style;if(!a.K(d))return[new a.V(g,d,`object expected, ${a.M(d)} found`)];if(!("type"in d))return[new a.V(g,d,'"type" is required')];const R=a.L(d.type);let L=[];switch(["vector","raster","raster-dem","raster-array"].includes(R)&&("url"in d||"tiles"in d||L.push(new a.a5(g,d,'Either "url" or "tiles" is required.'))),R){case"vector":case"raster":case"raster-dem":case"raster-array":return L=L.concat(yi({key:g,value:d,valueSpec:S[`source_${R.replace("-","_")}`],style:_.style,styleSpec:S,objectElementValidators:cs})),L;case"geojson":if(L=yi({key:g,value:d,valueSpec:S.source_geojson,style:E,styleSpec:S,objectElementValidators:cs}),"cluster"in d&&"clusterProperties"in d){if(!a.K(d.clusterProperties))return[new a.V(`${g}.clusterProperties`,d,`object expected, ${a.M(d)} found`)];for(const B in d.clusterProperties){const U=d.clusterProperties[B];if(!Array.isArray(U))return[new a.V(`${g}.clusterProperties.${B}`,U,"array expected")];const[W,Z]=U,ne=typeof W=="string"?[W,["accumulated"],["get",B]]:W;L.push(...gs({key:`${g}.${B}.map`,value:Z,expressionContext:"cluster-map"})),L.push(...gs({key:`${g}.${B}.reduce`,value:ne,expressionContext:"cluster-reduce"}))}}return L;case"video":return yi({key:g,value:d,valueSpec:S.source_video,style:E,styleSpec:S});case"image":return yi({key:g,value:d,valueSpec:S.source_image,style:E,styleSpec:S});case"canvas":return[new a.V(g,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return $n({key:`${g}.type`,value:d.type,valueSpec:{values:Ln(S)}})}}function Ln(_){return _.source.reduce((d,g)=>{const S=_[g];return S.type.type==="enum"&&(d=d.concat(Object.keys(S.type.values||{}))),d},[])}function ri(_){const d=_.value,g=_.styleSpec,S=g.light,E=_.style;if(d===void 0)return[];if(!a.K(d))return[new a.V("light",d,`object expected, ${a.M(d)} found`)];let R=[];for(const L in d){const B=L.match(/^(.*)-transition$/),U=L.match(/^(.*)-use-theme$/);R=R.concat(U&&S[U[1]]?ws({key:L,value:d[L],valueSpec:{type:"string"},style:E,styleSpec:g}):B&&S[B[1]]&&S[B[1]].transition?ws({key:L,value:d[L],valueSpec:g.transition,style:E,styleSpec:g}):S[L]?ws({key:L,value:d[L],valueSpec:S[L],style:E,styleSpec:g}):[new a.V(L,d[L],`unknown property "${L}"`)])}return R}function Yo(_){const d=_.value;if(!d)return[];const g=_.key;if(!a.K(d))return[new a.V(g,d,`object expected, ${a.M(d)} found`)];let S=[];const E=_.styleSpec,R=E["light-3d"],L=_.style,B=_.style.lights;for(const Z of["type","id"])if(!(Z in d))return S=S.concat([new a.V(g,d,`missing property "${Z}"`)]),S;if(!a.a2(d.type))return S=S.concat([new a.V(`${g}.type`,d.type,"string expected")]),S;if(B)for(let Z=0;Z<_.arrayIndex;Z++){const ne=a.L(d.type),re=B[Z];a.L(re.type)===ne&&S.push(new a.V(g,d.id,`duplicate light type "${d.type}", previously defined at line ${re.id.__line__}`))}const U=`properties_light_${d.type}`;if(!(U in E))return S=S.concat([new a.V(`${g}.type`,d,`Invalid light type ${d.type}`)]),S;const W=E[U];for(const Z in d)if(Z==="properties"){const ne=d[Z];if(!a.K(ne))return S=S.concat([new a.V("properties",ne,`object expected, ${a.M(ne)} found`)]),S;for(const re in ne){const ie=re.match(/^(.*)-transition$/),ce=re.match(/^(.*)-use-theme$/);S=S.concat(ce&&W[ce[1]]?ws({key:Z,value:ne[re],valueSpec:{type:"string"},style:L,styleSpec:E}):ie&&W[ie[1]]&&W[ie[1]].transition?ws({key:Z,value:d[Z],valueSpec:E.transition,style:L,styleSpec:E}):W[re]?ws({key:re,value:ne[re],valueSpec:W[re],style:L,styleSpec:E}):[new a.a5(_.key,ne[re],`unknown property "${re}"`)])}}else S=S.concat(R[Z]?ws({key:Z,value:d[Z],valueSpec:R[Z],style:L,styleSpec:E}):[new a.a5(Z,d[Z],`unknown property "${Z}"`)]);return S}function Us(_){const d=_.value,g=_.key,S=_.style,E=_.styleSpec,R=E.terrain;if(d==null)return[];if(!a.K(d))return[new a.V("terrain",d,`object expected, ${a.M(d)} found`)];let L=[];for(const B in d){const U=B.match(/^(.*)-transition$/),W=B.match(/^(.*)-use-theme$/);L=L.concat(W&&R[W[1]]?ws({key:B,value:d[B],valueSpec:{type:"string"},style:S,styleSpec:E}):U&&R[U[1]]&&R[U[1]].transition?ws({key:B,value:d[B],valueSpec:E.transition,style:S,styleSpec:E}):R[B]?ws({key:B,value:d[B],valueSpec:R[B],style:S,styleSpec:E}):[new a.a5(B,d[B],`unknown property "${B}"`)])}if(d.source)if(a.a2(d.source)){const B=S.sources&&S.sources[d.source],U=B&&a.L(B.type);B?U!=="raster-dem"&&L.push(new a.V(`${g}.source`,d.source,`terrain cannot be used with a source of type ${U}, it only be used with a "raster-dem" source type`)):L.push(new a.V(`${g}.source`,d.source,`source "${d.source}" not found`))}else L.push(new a.V(`${g}.source`,d.source,"source must be a string"));else L.push(new a.V(g,d,'terrain is missing required property "source"'));return L}function Ft(_){const d=_.value,g=_.style,S=_.styleSpec,E=S.fog;if(d===void 0)return[];if(!a.K(d))return[new a.V("fog",d,`object expected, ${a.M(d)} found`)];let R=[];for(const L in d){const B=L.match(/^(.*)-transition$/),U=L.match(/^(.*)-use-theme$/);R=R.concat(U&&E[U[1]]?ws({key:L,value:d[L],valueSpec:{type:"string"},style:g,styleSpec:S}):B&&E[B[1]]&&E[B[1]].transition?ws({key:L,value:d[L],valueSpec:S.transition,style:g,styleSpec:S}):E[L]?ws({key:L,value:d[L],valueSpec:E[L],style:g,styleSpec:S}):[new a.a5(L,d[L],`unknown property "${L}"`)])}return R}const jo={"*":()=>[],array:Bn,boolean:function(_){const d=_.value,g=_.key;return a.a1(d)?[]:[new a.V(g,d,`boolean expected, ${a.M(d)} found`)]},number:Rs,color:function({key:_,value:d}){return a.a2(d)?a.a3.parseCSSColor(d)===null?[new a.V(_,d,`color expected, "${d}" found`)]:[]:[new a.V(_,d,`color expected, ${a.M(d)} found`)]},enum:$n,filter:Si,function:sa,layer:xn,object:yi,source:nn,model:a.a9,light:ri,"light-3d":Yo,terrain:Us,fog:Ft,string:Qr,formatted:function(_){return Qr(_).length===0?[]:gs(_)},resolvedImage:function(_){return Qr(_).length===0?[]:gs(_)},projection:function(_){const d=_.value,g=_.styleSpec,S=g.projection,E=_.style;if(a.K(d)){let R=[];for(const L in d)R=R.concat(ws({key:L,value:d[L],valueSpec:S[L],style:E,styleSpec:g}));return R}return a.a2(d)?[]:[new a.V("projection",d,`object or string expected, ${a.M(d)} found`)]},import:function(_){const d=_.key,{value:g,styleSpec:S}=_;if(!a.K(g))return[new a.V(d,g,"import must be an object")];const{data:E,...R}=g;Object.defineProperty(R,"__line__",{value:g.__line__,enumerable:!1});let L=yi(Object.assign({},_,{value:R,valueSpec:S.import}));return a.L(R.id)===""&&L.push(new a.V(`${_.key}.id`,R,"import id can't be an empty string")),E&&(L=L.concat(Da(E,S,{key:`${_.key}.data`}))),L},iconset:function(_){const d=_.value,g=_.key,S=_.styleSpec,E=_.style;if(!a.K(d))return[new a.V(g,d,"object expected")];if(!d.type)return[new a.V(g,d,'"type" is required')];const R=a.L(d.type);let L=[];if(L=L.concat(yi({key:g,value:d,valueSpec:S[`iconset_${R}`],style:E,styleSpec:S})),function(B,U){return!(B!=="source"||!U.source)}(R,d)){const B=E.sources&&E.sources[d.source],U=B&&a.L(B.type);B?U!=="raster-array"&&L.push(new a.V(g,d.source,`iconset cannot be used with a source of type ${String(U)}, it only be used with a "raster-array" source type`)):L.push(new a.V(g,d.source,`source "${d.source}" not found`))}return L}};function ws(_,d=!1){const g=_.value,S=_.valueSpec,E=_.styleSpec;if(S.expression){if(a.a6(a.L(g)))return sa(_);if(a.U(a.W(g)))return gs(_)}if(S.type&&jo[S.type]){const R=jo[S.type](_);return d===!0&&R.length>0&&Array.isArray(_.value)?gs(_):R}return yi(Object.assign({},_,{valueSpec:S.type?E[S.type]:S}))}function yi(_){const d=_.key,g=_.value,S=_.valueSpec||{},E=_.objectElementValidators||{},R=_.style,L=_.styleSpec;if(!a.K(g))return[new a.V(d,g,`object expected, ${a.M(g)} found`)];let B=[];for(const U in g){const W=U.split(".")[0];let Z;E[W]?Z=E[W]:S[W]?Z=ws:E["*"]?Z=E["*"]:S["*"]&&(Z=ws),Z?B=B.concat(Z({key:(d&&`${d}.`)+U,value:g[U],valueSpec:S[W]||S["*"],style:R,styleSpec:L,object:g,objectKey:U},g)):B.push(new a.a5(d,g[U],`unknown property "${U}"`))}for(const U in S){if(E[U])continue;const W=S[U];W.required&&W.default===void 0&&g[U]===void 0&&B.push(new a.V(d,g,`missing required property "${U}"`))}return B}function Xn({key:_,value:d}){const g=Qr({key:_,value:d});if(g.length)return g;const S=d;return S.indexOf("{fontstack}")===-1&&g.push(new a.V(_,d,'"glyphs" url must include a "{fontstack}" token')),S.indexOf("{range}")===-1&&g.push(new a.V(_,d,'"glyphs" url must include a "{range}" token')),g}function Da(_,d=a.a8,g={}){return yi({key:g.key||"",value:_,valueSpec:Object.assign(d.$root,{"*":{type:"*"}}),styleSpec:d,style:_,objectElementValidators:{glyphs:Xn}})}function _c(_,d=a.a8){return Mt(Da(_,d))}const hl=_=>Mt(nn(_)),dt=_=>Mt(ri(_)),he=_=>Mt(Yo(_)),pe=_=>Mt(Us(_)),Fe=_=>Mt(Ft(_)),Ye=_=>Mt(function(d){const g=d.value,S=d.style,E=d.styleSpec,R=E.snow;if(g===void 0)return[];if(!a.K(g))return[new a.V("snow",g,`object expected, ${a.M(g)} found`)];let L=[];for(const B in g){const U=B.match(/^(.*)-transition$/);L=L.concat(U&&R[U[1]]&&R[U[1]].transition?ws({key:B,value:g[B],valueSpec:E.transition,style:S,styleSpec:E}):R[B]?ws({key:B,value:g[B],valueSpec:R[B],style:S,styleSpec:E}):[new a.a5(B,g[B],`unknown property "${B}"`)])}return L}(_)),et=_=>Mt(function(d){const g=d.value,S=d.style,E=d.styleSpec,R=E.rain;if(g===void 0)return[];if(!a.K(g))return[new a.V("rain",g,`object expected, ${a.M(g)} found`)];let L=[];for(const B in g){const U=B.match(/^(.*)-transition$/);L=L.concat(U&&R[U[1]]&&R[U[1]].transition?ws({key:B,value:g[B],valueSpec:E.transition,style:S,styleSpec:E}):R[B]?ws({key:B,value:g[B],valueSpec:R[B],style:S,styleSpec:E}):[new a.a5(B,g[B],`unknown property "${B}"`)])}return L}(_)),nt=_=>Mt(xn(_)),ht=_=>Mt(Si(_)),it=_=>Mt(Xr(_)),mt=_=>Mt(un(_)),Gt=_=>Mt(a.a9(_));function Mt(_){return _.slice().sort((d,g)=>d.line&&g.line?d.line-g.line:0)}function gr(_,d){let g=!1;if(d&&d.length)for(const S of d)S instanceof a.a5?a.w(S.message):(_.fire(new a.B(new Error(S.message))),g=!0);return g}const zr=a.a8.light;let Hr;class hr extends a.E{constructor(d,g="flat"){super(),this._transitionable=new a.aa(Hr||(Hr=new a.ab({anchor:new a.ac(zr.anchor),position:new a.ad(zr.position),color:new a.ac(zr.color),intensity:new a.ac(zr.intensity)}))),this.setLight(d,g),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(d,g,S={}){this._validate(dt,d,S)||(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,S){return(!S||S.validate!==!1)&&gr(this,d.call(_c,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}}const rt=a.a8.terrain;let qt=class extends a.E{constructor(_,d,g,S,E){super(),this.scope=g,this._transitionable=new a.aa(new a.ab({source:new a.ac(rt.source),exaggeration:new a.ac(rt.exaggeration)}),g,S),this._transitionable.setTransitionOrValue(_,S),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=d,this.worldview=E}get(){return this._transitionable.serialize()}set(_,d){this._transitionable.setTransitionOrValue(_,d)}updateTransitions(_){this._transitioning=this._transitionable.transitioned(_,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(_){this.properties=this._transitioning.possiblyEvaluate(_)}getExaggeration(_){return this._transitioning.possiblyEvaluate(new a.ae(_,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const _=this._transitionable._values.exaggeration;if(!_)return null;const d=_.value.expression;if(!d)return null;let g=-1,S=-1,E=1;for(const R of d.zoomStops)E=d.evaluate(new a.ae(R,{worldview:this.worldview})),E>.01?(g=R,S=-1):S=R;return E<.01&&g>0&&S>g?[g,S]:null}isZoomDependent(){const _=this._transitionable._values.exaggeration;return _!=null&&_.value!=null&&_.value.expression!=null&&_.value.expression instanceof a.af}};const vr=.05;function wn(_,d,g,S){const E=a.aj(45,65,g),[R,L]=Cn(_,S);let B=1-Math.min(1,Math.exp((d-R)/(L-R)*-6));return B*=B*B,B=Math.min(1,1.00747*B),B*E*_.alpha}function Cn(_,d){const g=.5/Math.tan(.5*d);return[_.range[0]+g,_.range[1]+g]}function Qn(_,d,g,S,E){const R=a.ah([],[d,g,S],E.mercatorFogMatrix);return wn(_,a.ai(R),E.pitch,E._fov)}function Ns(_,d,g,S,E,R,L){const B=[[g,S,0],[E,S,0],[E,R,0],[g,R,0]];let U=Number.MAX_VALUE,W=-Number.MAX_VALUE;for(const Z of B){const ne=a.ah([],Z,d),re=a.ai(ne);U=Math.min(U,re),W=Math.max(W,re)}return[wn(_,U,L.pitch,L._fov),wn(_,W,L.pitch,L._fov)]}const Jn=a.a8.fog;class ks extends a.E{constructor(d,g,S,E){super();const R=new a.ab({range:new a.ac(Jn.range),color:new a.ac(Jn.color),"color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new a.ac(Jn["high-color"]),"high-color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new a.ac(Jn["space-color"]),"space-color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new a.ac(Jn["horizon-blend"]),"star-intensity":new a.ac(Jn["star-intensity"]),"vertical-range":new a.ac(Jn["vertical-range"])});this._transitionable=new a.aa(R,S,new Map(E)),this.set(d,E),this._transitioning=this._transitionable.untransitioned(),this._transform=g,this.properties=new a.ak(R),this.scope=S}get state(){const d=this._transform,g=d.projection.name==="globe",S=a.al(d.zoom),E=this.properties.get("range"),R=[.5,3];return{range:g?[a.am(R[0],E[0],S),a.am(R[1],E[1],S)]:E,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(d,g,S={}){if(this._validate(Fe,d,S))return;const E=Object.assign({},d);for(const R of Object.keys(Jn))E[R]===void 0&&(E[R]=Jn[R].default);this._options=E,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:a.aj(45,65,d))*g.a}getOpacityAtLatLng(d,g){return this._transform.projection.supportsFog?function(S,E,R){const L=a.ag.fromLngLat(E),B=R.elevation?R.elevation.getAtPointOrZero(L):0;return Qn(S,L.x,L.y,B,R)}(this.state,d,g):0}getOpacityForTile(d){if(!this._transform.projection.supportsFog)return[1,1];const g=this._transform.calculateFogTileMatrix(d.toUnwrapped());return Ns(this.state,g,0,0,a.an,a.an,this._transform)}getOpacityForBounds(d,g,S,E,R){return this._transform.projection.supportsFog?Ns(this.state,d,g,S,E,R,this._transform):[1,1]}getFovAdjustedRange(d){return this._transform.projection.supportsFog?Cn(this.state,d):[0,1]}isVisibleOnFrustum(d){if(!this._transform.projection.supportsFog)return!1;const g=[4,5,6,7];for(const S of g){const E=d.points[S];let R;if(E[2]>=0)R=E;else{const L=d.points[S-4];R=a.ao(L,E,L[2]/(L[2]-E[2]))}if(Qn(this.state,R[0],R[1],0,this._transform)>=vr)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,S){return(!S||S.validate!==!1)&&gr(this,d.call(_c,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}}let Ui,Un,ni,hi=class extends a.E{constructor(_,d,g,S){super();const E=Ui||(Ui=new a.ab({density:new a.ac(a.a8.snow.density),intensity:new a.ac(a.a8.snow.intensity),color:new a.ac(a.a8.snow.color),opacity:new a.ac(a.a8.snow.opacity),vignette:new a.ac(a.a8.snow.vignette),"vignette-color":new a.ac(a.a8.snow["vignette-color"]),"center-thinning":new a.ac(a.a8.snow["center-thinning"]),direction:new a.ac(a.a8.snow.direction),"flake-size":new a.ac(a.a8.snow["flake-size"])}));this._transitionable=new a.aa(E,g,new Map(S)),this.set(_,S),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ak(E),this.scope=g}get state(){const _=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),S=a.ap(g[0]),E=-Math.max(a.ap(g[1]),.01),R=[Math.cos(S)*Math.cos(E),Math.sin(S)*Math.cos(E),Math.sin(E)],L=this.properties.get("vignette"),B=this.properties.get("vignette-color");return B.a=L,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new a.aq(d.r,d.g,d.b,d.a*_),direction:R,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:B}}get(){return this._transitionable.serialize()}set(_,d,g={}){if(this._validate(Ye,_,g))return;const S=Object.assign({},_),E=a.a8.snow;for(const R of Object.keys(E))S[R]===void 0&&(S[R]=E[R].default);this._options=S,this._transitionable.setTransitionOrValue(this._options,d)}updateConfig(_){this._transitionable.setTransitionOrValue(this._options,new Map(_))}updateTransitions(_){this._transitioning=this._transitionable.transitioned(_,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(_){this.properties=this._transitioning.possiblyEvaluate(_)}_validate(_,d,g){return(!g||g.validate!==!1)&&gr(this,_.call(_c,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}},Vn=class extends a.E{constructor(_,d,g,S){super();const E=Un||(Un=new a.ab({density:new a.ac(a.a8.rain.density),intensity:new a.ac(a.a8.rain.intensity),color:new a.ac(a.a8.rain.color),opacity:new a.ac(a.a8.rain.opacity),vignette:new a.ac(a.a8.rain.vignette),"vignette-color":new a.ac(a.a8.rain["vignette-color"]),"center-thinning":new a.ac(a.a8.rain["center-thinning"]),direction:new a.ac(a.a8.rain.direction),"droplet-size":new a.ac(a.a8.rain["droplet-size"]),"distortion-strength":new a.ac(a.a8.rain["distortion-strength"])}));this._transitionable=new a.aa(E,g,new Map(S)),this.set(_,S),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ak(E),this.scope=g}get state(){const _=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),S=a.ap(g[0]),E=-Math.max(a.ap(g[1]),.01),R=[Math.cos(S)*Math.cos(E),Math.sin(S)*Math.cos(E),Math.sin(E)],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 a.aq(d.r,d.g,d.b,d.a*_),direction:R,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(_,d,g={}){if(this._validate(et,_,g))return;const S=Object.assign({},_),E=a.a8.rain;for(const R of Object.keys(E))S[R]===void 0&&(S[R]=E[R].default);this._options=S,this._transitionable.setTransitionOrValue(this._options,d)}updateConfig(_){this._transitionable.setTransitionOrValue(this._options,new Map(_))}updateTransitions(_){this._transitioning=this._transitionable.transitioned(_,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(_){this.properties=this._transitioning.possiblyEvaluate(_)}_validate(_,d,g){return(!g||g.validate!==!1)&&gr(this,_.call(_c,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}};class Oa extends a.E{constructor(d,g,S,E){super(),this.scope=S,this._options=d,this.properties=new a.ak(g),this._transitionable=new a.aa(g,S,new Map(E)),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 Lo=()=>ni||(ni=new a.ab({color:new a.ac(a.a8.properties_light_ambient.color),"color-use-theme":new a.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new a.ac(a.a8.properties_light_ambient.intensity)}));let Eo;const bc=()=>Eo||(Eo=new a.ab({direction:new a.ar(a.a8.properties_light_directional.direction),color:new a.ac(a.a8.properties_light_directional.color),"color-use-theme":new a.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new a.ac(a.a8.properties_light_directional.intensity),"cast-shadows":new a.ac(a.a8.properties_light_directional["cast-shadows"]),"shadow-quality":new a.ac(a.a8.properties_light_directional["shadow-quality"]),"shadow-intensity":new a.ac(a.a8.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new a.ac(a.a8.properties_light_directional["shadow-draw-before-layer"])}));class wc{constructor(d,g,S){this.screenBounds=d,this.cameraPoint=S.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=g,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,S)}static createFromScreenPoints(d,g){let S,E;if(d instanceof a.P||typeof d[0]=="number"){const R=a.P.convert(d);S=[R],E=g.isPointAboveHorizon(R)}else{const R=a.P.convert(d[0]),L=a.P.convert(d[1]),B=R.add(L)._div(2);S=[R,L],E=a.as(R,L).every(U=>g.isPointAboveHorizon(U))&&g.isPointAboveHorizon(B)}return new wc(S,E,g)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(d){return a.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],d)}bufferedCameraGeometry(d){const g=this.screenBounds[0],S=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],E=a.as(g,S,0,!1);return this.cameraPoint.y>S.y&&(this.cameraPoint.x>g.x&&this.cameraPoint.x=S.x?E[2]=this.cameraPoint:this.cameraPoint.x<=g.x&&(E[3]=this.cameraPoint)),a.at(E,d)}bufferedCameraGeometryGlobe(d){const g=this.screenBounds[0],S=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],E=a.as(g,S,d),R=this.cameraPoint.clone(),L=+(R.x>g.x)+ +(R.x>S.x);switch(3*(+(R.y>g.y)+ +(R.y>S.y))+L){case 0:E[0]=R,E[4]=R.clone();break;case 1:E.splice(1,0,R);break;case 2:E[1]=R;break;case 3:E.splice(4,0,R);break;case 5:E.splice(2,0,R);break;case 6:E[3]=R;break;case 7:E.splice(3,0,R);break;case 8:E[2]=R}return E}containsTile(d,g,S,E=0){const R=Math.max(d.queryPadding,d.evaluateQueryRenderedFeaturePadding())/g._pixelsPerMercatorPixel+1,L=S?this._bufferedCameraMercator(R,g):this._bufferedScreenMercator(R,g);let B=d.tileID.wrap+(L.unwrapped?E:0);const U=L.polygon.map(be=>a.au(d.tileTransform,be,B));if(!a.av(U,0,0,a.an,a.an))return;B=d.tileID.wrap+(this.screenGeometryMercator.unwrapped?E:0);const W=this.screenGeometryMercator.polygon.map(be=>a.aw(d.tileTransform,be,B)),Z=W.map(be=>new a.P(be[0],be[1])),ne=g.getFreeCameraOptions().position||new a.ag(0,0,0),re=a.aw(d.tileTransform,ne,B),ie=W.map(be=>{const _e=a.ax(be,be,re);return a.ay(_e,_e),new a.az(re,_e)}),ce=a.aA(d,1,g.zoom)*g._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Z,tilespaceRays:ie,bufferedTilespaceGeometry:U,bufferedTilespaceBounds:(le=a.aB(U),le.min.x=a.aC(le.min.x,0,a.an),le.min.y=a.aC(le.min.y,0,a.an),le.max.x=a.aC(le.max.x,0,a.an),le.max.y=a.aC(le.max.y,0,a.an),le),tile:d,tileID:d.tileID,pixelToTileUnitsFactor:ce};var le}_bufferedScreenMercator(d,g){const S=Sc(d);if(this._screenRaycastCache[S])return this._screenRaycastCache[S];{let E;return E=g.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(d),g):{polygon:this.bufferedScreenGeometry(d).map(R=>g.pointCoordinate3D(R)),unwrapped:!0},this._screenRaycastCache[S]=E,E}}_bufferedCameraMercator(d,g){const S=Sc(d);if(this._cameraRaycastCache[S])return this._cameraRaycastCache[S];{let E;return E=g.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(d),g):{polygon:this.bufferedCameraGeometry(d).map(R=>g.pointCoordinate3D(R)),unwrapped:!0},this._cameraRaycastCache[S]=E,E}}_projectAndResample(d,g){const S=function(R,L){const B=a.aD([],L.pixelMatrix,L.globeMatrix),U=[0,-a.aF,0,1],W=[0,a.aF,0,1],Z=[0,0,0,1];a.aE(U,U,B),a.aE(W,W,B),a.aE(Z,Z,B);const ne=new a.P(U[0]/U[3],U[1]/U[3]),re=new a.P(W[0]/W[3],W[1]/W[3]),ie=a.aG(R,ne)&&U[3]1?Kd(R.slice(0,be),L):[],Me=benew a.P(Ll(Ke.x),Ke.y)),Me=Me.map(Ke=>new a.P(Ll(Ke.x),Ke.y));const je=[...Re];je.length===0&&je.push(Me[Me.length-1]);const Xe=a.am(je[je.length-1].y,(Me.length===0?Re[0]:Me[0]).y,_e);let $e;return $e=ie?[new a.P(0,Xe),new a.P(0,0),new a.P(1,0),new a.P(1,Xe)]:[new a.P(1,Xe),new a.P(1,1),new a.P(0,1),new a.P(0,Xe)],je.push(...$e),Me.length===0?je.push(Re[0]):je.push(...Me),{polygon:je.map(Ke=>new a.ag(Ke.x,Ke.y)),unwrapped:!1}}(d,g);if(S)return S;const E=function(R,L){let B=!1,U=-1/0,W=0;for(let ne=0;neU&&(U=R[ne].x,W=ne);for(let ne=0;ne.5&&(ie.x{ne.x-=1}),{polygon:R,unwrapped:B}}(Kd(d,g).map(R=>new a.P(Ll(R.x),R.y)),g);return{polygon:E.polygon.map(R=>new a.ag(R.x,R.y)),unwrapped:E.unwrapped}}}function Kd(_,d){return a.aI(_,g=>{const S=d.pointCoordinate3D(g);g.x=S.x,g.y=S.y},1/256)}function Ll(_){return _<0?1+_%1:_%1}function Sc(_){return 100*_|0}function Yd(_,d,g){try{d=function(E){if(!E.variants)return E;if(!Array.isArray(E.variants))throw new Error("variants must be an array");for(const R of E.variants){if(R==null||typeof R!="object"||R.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(R.capabilities))throw new Error("capabilities must be an array");if(R.capabilities.length===1&&R.capabilities[0]==="meshopt")return Object.assign(E,R)}return E}(d)}catch(E){return new Error("Failed to process TileJSON variants",{cause:E})}const S=a.aJ(Object.assign({},d,_),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return _.url&&d.tiles&&_.tiles&&(S.tiles=d.tiles),S.tiles=g.canonicalizeTileset(S,_.url),S}function Hc(_,d,g,S,E){const R=function(B,U){if(B)return E(B);if(U){_.url&&U.tiles&&_.tiles&&delete _.tiles;const W=Yd(_,U,d);if(W instanceof Error)return E(W);E(null,W)}},L=function(B,U,W){if(!B)return null;if(!U&&!W)return B;W=W||B.worldview_default;const Z=Object.values(B.language||{});if(Z.length===0)return null;const ne=Object.values(B.worldview||{});if(ne.length===0)return null;const re=Z.every(ce=>ce===U),ie=ne.every(ce=>ce===W);return re&&ie?B:U in(B.language_options||{})||W in(B.worldview_options||{})?null:B.language_options&&B.worldview_options?B:null}(_.data,g,S);return L?a.o.frame(()=>R(null,L)):_.url?a.m(d.transformRequest(d.normalizeSourceURL(_.url,null,g,S),a.R.Source),R):a.o.frame(()=>{const{data:B,...U}=_;R(null,U)})}function Zd(_,d){const g=Math.pow(2,d.z),S=Math.floor(a.aH(_.getWest())*g),E=Math.floor(a.aL(_.getNorth())*g),R=Math.ceil(a.aH(_.getEast())*g),L=Math.ceil(a.aL(_.getSouth())*g);return d.x>=S&&d.x=E&&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}`),S&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${S}`),this.fire(new a.B(L))):B&&(this._setTileJSON(B),Ze(B.tiles,this.map._requestManager._customAccessToken),this.fire(new a.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))),d&&d(L)};this.provider=this._options.provider;const R=function(L){if("provider"in L&&!L.provider)return null;let B=L.provider;if(!B&&"url"in L&&L.url&&(B=a.aM(L.url)),!B)return null;const U=a.g.TILE_PROVIDER_URLS[B];if(!U)return null;let W;try{W=new URL(U,a.g.API_URL).href}catch{return a.w(`TileProvider "${B}" has an invalid URL: "${U}"`),null}return{name:B,url:W}}(this._options);if(this.provider&&!R)return this._loaded=!0,this.fire(new a.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(d&&d());this._tileJSONRequest=R?this._loadWithProvider(R,E):Hc(this._options,this.map._requestManager,g,S,E)}_loadWithProvider(d,g){this.provider=d.name;const S=new AbortController,E=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,a.R.Source):void 0,R=E?Object.assign({},this._options,{url:E.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:d.name,url:d.url,source:this.id,scope:this.scope,type:this.type,options:R,request:E},(L,B)=>{if(S.signal.aborted)return;if(L)return void g(L);const U=B?B.find(W=>W!=null):null;if(U){const W=Yd(this._options,U,this.map._requestManager);W instanceof Error?g(W):g(null,W)}else g(null,{tiles:this._options.tiles})}),{cancel:()=>{S.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=Iu.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=a.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 S=d.tileID.canonical.url(this.tiles,this.scheme),E=this.map._requestManager.normalizeTileURL(S),R=this.map._requestManager.transformRequest(E,a.R.Tile),L=this.map.style?this.map.style.getLut(this.scope):null,B=L?{image:L.image.clone()}:null,U={request:R,data:void 0,uid:d.uid,tileID:d.tileID,tileZoom:d.tileZoom,zoom:d.tileID.overscaledZ,maxZoom:this.maxzoom,lut:B,tileSize:this.tileSize*d.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:a.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&&a.e(S)&&(U.localizableLayerIds=this.localizableLayerIds),U.request.collectResourceTiming=this._collectResourceTiming,d.actor&&d.state!=="expired")d.state==="loading"?d.reloadCallback=g:d.request=d.actor.send("reloadTile",U,W.bind(this));else if(d.actor=this._tileWorkers[E]=this._tileWorkers[E]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)d.request=d.actor.send("loadTile",U,W.bind(this),void 0,!0);else{const Z=a.aO.call({deduped:this._deduped},U,(ne,re)=>{if(ne||!re)W.call(this,ne);else{const ie=a.aP(re.responseHeaders);U.data={rawData:re.rawData.slice(0),expires:ie.expires,cacheControl:ie.cacheControl},d.actor&&d.actor.send("loadTile",U,W.bind(this),void 0,!0)}},!0);d.request={cancel:Z}}function W(Z,ne){return delete d.request,d.aborted?g(null):Z?g(Z):(ne&&ne.resourceTiming&&(d.resourceTiming=ne.resourceTiming),this.map._refreshExpiredTiles&&ne&&d.setExpiryData(ne),d.loadVectorData(ne,this.map.painter),a.aQ(this.dispatcher),g(null,ne),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 M0 extends a.E{constructor(d,g,S,E){super(),this.id=d,this.dispatcher=S,this.setEventedParent(E),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,a.aJ(g,["url","scheme","tileSize"]))}load(d){this._loaded=!1,this.fire(new a.C("dataloading",{dataType:"source"}));const g=this.map.getWorldview();this._tileJSONRequest=Hc(this._options,this.map._requestManager,null,g,(S,E)=>{this._tileJSONRequest=null,this._loaded=!0,S?this.fire(new a.B(S)):E&&(Object.assign(this,E),E.raster_layers&&(this.rasterLayers=E.raster_layers,this.rasterLayerIds=this.rasterLayers.map(R=>R.id)),this.tileBounds=Iu.fromTileJSON(E),Ze(E.tiles),this.fire(new a.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))),d&&d(S)})}loaded(){return this._loaded}onAdd(d){this.map=d,this.load()}reload(){this.cancelTileJSONRequest();const d=a.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 S=a.o.devicePixelRatio>=2,E=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),S,this.tileSize);d.request=a.n(this.map._requestManager.transformRequest(E,a.R.Tile),(R,L,B)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(R)return d.state="errored",g(R);if(!L)return g(null);const U=a.aP(B);this.map._refreshExpiredTiles&&d.setExpiryData(U),d.setTexture(L,this.map.painter),d.state="loaded",a.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 a.T?(d.destroy(!1),d.texture&&d.texture instanceof a.T&&this.map.painter.saveTileTexture(d.texture)):d.destroy(),g&&g()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Fj([_,d],g,S,{scaled:E=!0}={}){const{tileSize:R,buffer:L}=S,{x:B,y:U,z:W}=g;if(!isFinite(B)||!isFinite(U)||!isFinite(W))throw new Error("Invalid MRT header");const Z=2**W,ne=Z*a.aH(_),re=Z*a.aL(d);return function([ie,ce],le,{scaled:be=!0}={}){if(!le)throw new Error("bandView is undefined");const{data:_e,tileSize:Re,buffer:Me,offset:je,scale:Xe,dimension:$e}=le;if(ie<-Me||ie>Re+Me||ce<-Me||ce>Re+Me)throw new Error(`Point (${ie}, ${ce}) out of bounds for tileSize=${Re}, buffer=${Me}`);const Ke=(ce+Me)*(Re+2*Me)+(ie+Me);if(new Uint32Array(_e.buffer)[Ke]===4294967295)return null;let De=[];De=be?[]:new le.data.constructor($e);for(let Be=0;Be<$e;Be++)De[Be]=Math.round(1e12*(_e[$e*Ke+Be]*Xe+je))/1e12;return De}([Math.min(Math.max(-L,Math.floor((ne-B)*R)),R-1+L),Math.min(Math.max(-L,Math.floor((re-U)*R)),R-1+L)],S,{scaled:E})}class yp extends M0{constructor(d,g,S,E){super(d,g,S,E),this.type="raster-array",this.maxzoom=22,this.partial=!0,this._loadTilePending={},this._loadTileLoaded={},this._options=Object.assign({type:"raster-array"},g)}triggerRepaint(d){const g=this.map.painter._terrain,S=this.map.style.getSourceCache(this.id);g&&g.enabled&&S&&g._clearRenderCacheForTile(S.id,d.tileID),this.map.triggerRepaint()}loadTile(d,g){const S=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),E=this.map._requestManager.transformRequest(S,a.R.Tile),R={request:E,uid:d.uid,tileID:d.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};d.source=this.id,d.scope=this.scope,d.requestParams=E,d.actor||(d.actor=this.dispatcher.getActor());const L=(B,U,W)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(B)return B.name==="AbortError"?void 0:(d.state="errored",g(B));if(this.map._refreshExpiredTiles&&U){const Z=a.aP(W);d.setExpiryData(Z)}if(this.partial&&d.state!=="expired")d.state="empty";else if(!this.partial){if(!U)return g(null);d.state="loaded",d._isHeaderLoaded=!0,d._mrt=U}g(null)};d.request=this.partial?d.fetchHeader(void 0,L.bind(this)):d.actor.send("loadTile",R,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 S=d.texturePerLayer;if(d.flushAllQueues(),S.size){d.destroy(!1);for(const E of S.values())this.map.painter.saveTileTexture(E)}else d.destroy()}prepareTile(d,g,S,E){d._isHeaderLoaded&&(d.state!=="empty"&&(d.state="reloading"),d.fetchBandForRender(g,S,E,(R,L)=>{R?(d.state="errored",this.fire(new a.B(R))):L&&(d._isHeaderLoaded=!0,d.setTexturePerLayer(S,L,this.map.painter),d.state="loaded"),this.triggerRepaint(d)}))}getInitialBand(d){if(!this.rasterLayers)return 0;const g=this.rasterLayers.find(({id:R})=>R===d),S=g&&g.fields,E=S&&S.bands&&S.bands;return E?E[0]:0}getTextureDescriptor(d,g,S){if(!d)return;const E=g.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!E)return;let R=null;g instanceof a.aS?R=g.paint.get("raster-array-band"):g instanceof a.aT&&(R=g.paint.get("raster-particle-array-band"));const L=R||this.getInitialBand(E);if(L==null)return;if(!d.textureDescriptorPerLayer.get(g.id))return void this.prepareTile(d,E,g.id,L);if(d.updateNeeded(g.id,L)&&!S)return;const B=d.textureDescriptorPerLayer.get(g.id);return Object.assign({},B,{texture:d.texturePerLayer.get(g.id)})}getImages(d,g){const S=new Map;for(const E of d)for(const R of g){const[L,B]=R.split("/"),U=E.getLayer(L);if(!U||!U.hasBand(B)||!U.hasDataForBand(B))continue;const{bytes:W,tileSize:Z,buffer:ne}=U.getBandView(B),re=Z+2*ne,ie={data:new a.q({width:re,height:re},W),pixelRatio:2,sdf:!1,usvg:!1,version:0};S.set(R,ie)}return S}queryRasterArrayValueByBandId(d,g,S){const E=g._mrt;return new Promise(R=>{const L={},B=new Set;for(const[U,W]of Object.entries(E.layers)){if(S.layerName&&U!==S.layerName)continue;const Z={};L[U]=Z;for(const{bands:ne}of W.dataIndex)for(const re of ne)S.bands&&!S.bands.includes(re)||(B.add(a.F(U,re)),g.fetchBand(U,null,re,ie=>{a.o.frame(()=>{Z[re]=ie?null:Fj([d.lng,d.lat],E,W.getBandView(re)),B.delete(a.F(U,re)),B.size===0&&R(L)})},!1))}B.size===0&&R(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 S=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),E=this.map._requestManager.transformRequest(S,a.R.Tile);d.actor.send("loadTile",{request:E,uid:d.uid,tileID:d.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(R,L,B)=>{if(R)return this._loadTilePending[d.uid].forEach(U=>U(R,null)),void delete this._loadTilePending[d.uid];if(!L)return this._loadTilePending[d.uid].forEach(U=>U(null,null)),void delete this._loadTilePending[d.uid];if(this.map._refreshExpiredTiles&&L){const U=a.aP(B);d.setExpiryData(U)}d._mrt=L,d._isHeaderLoaded=!0,d.state="loaded",this._loadTilePending[d.uid].forEach(U=>U(null,L)),this._loadTileLoaded[d.uid]=!0,delete this._loadTilePending[d.uid]},void 0,!0)}queryRasterArrayValueByAllBands(d,g,S){return new Promise((E,R)=>{this._loadTileForQuery(g,(L,B)=>{L?R(L):E(B?this.queryRasterArrayValueByBandId(d,g,S):null)})})}queryRasterArrayValue(d,g){const S=a.aU.convert(d),E=this.findLoadedParent(S);return E&&E._mrt?g.bands||!this.partial?this.queryRasterArrayValueByBandId(S,E,g):this.queryRasterArrayValueByAllBands(S,E,g):Promise.resolve(null)}findLoadedParent(d){const g=a.ag.fromLngLat(d,this.map.transform.tileSize),S=this.maxzoom+1,E=1<0&&(B[new a.aR(_.overscaledZ,E,d.z,S,d.y-1).key]={backfilled:!1},B[new a.aR(_.overscaledZ,_.wrap,d.z,d.x,d.y-1).key]={backfilled:!1},B[new a.aR(_.overscaledZ,L,d.z,R,d.y-1).key]={backfilled:!1}),d.y+1{if(this._loaded=!0,this._pendingLoad=null,S)this.fire(new a.B(S));else{const R={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&E&&E.resourceTiming&&E.resourceTiming[this.id]&&(R.resourceTiming=E.resourceTiming[this.id]),_&&(this._partialReload=!0),this.fire(new a.C("data",R)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(_),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const _=a.F(this.id,this.scope);this.map.style.clearSource(_),this._updateWorkerData()}loadTile(_,d){const g=_.actor?"reloadTile":"loadTile";_.actor=this.actor;const S=this.map.style?this.map.style.getLut(this.scope):null,E=S?{image:S.image.clone()}:null,R=this._partialReload,L={type:this.type,uid:_.uid,tileID:_.tileID,tileZoom:_.tileZoom,zoom:_.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:E,scope:this.scope,pixelRatio:a.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:_.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:R,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};_.request=this.actor.send(g,L,(B,U)=>R&&!U?(_.state="loaded",d(null)):(delete _.request,_.destroy(!1),_.aborted?d(null):B?d(B):(_.loadVectorData(U,this.map.painter,g==="reloadTile"),d(null))),void 0,g==="loadTile")}abortTile(_){_.request&&(_.request.cancel(),delete _.request),_.aborted=!0}unloadTile(_,d){this.actor.send("removeTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope}),_.destroy()}onRemove(_){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends a.aV{constructor(_,d,g,S){super(_,d,g,S),this.roundZoom=!0,this.type="video",this.options=d}load(){this._loaded=!1;const _=this.options;this.urls=[];for(const d of _.urls)this.urls.push(this.map._requestManager.transformRequest(d,a.R.Source).url);a.aW(this.urls,(d,g)=>{this._loaded=!0,d?this.fire(new a.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(_){if(this.video){const d=this.video.seekable;_d.end(0)?this.fire(new a.B(new a.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=_}}getVideo(){return this.video}onAdd(_){this.map||(this.map=_,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const _=this.map.painter.context,d=_.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 a.T(_,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(_)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:a.aV,model:a.aY,"batched-model":class extends a.E{constructor(_,d,g,S){super(),this.type="batched-model",this.id=_,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(S)}onAdd(_){this.map=_,this.load()}reload(){this.cancelTileJSONRequest();const _=a.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(_))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(_){this._loaded=!1,this.fire(new a.C("dataloading",{dataType:"source"}));const d=Array.isArray(this.map._language)?this.map._language.join():this.map._language,g=this.map.getWorldview();this._tileJSONRequest=Hc(this._options,this.map._requestManager,d,g,(S,E)=>{this._tileJSONRequest=null,this._loaded=!0,S?(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 a.B(S))):E&&(Object.assign(this,E),E.bounds&&(this.tileBounds=new Iu(E.bounds,this.minzoom,this.maxzoom)),Ze(E.tiles,this.map._requestManager._customAccessToken),this.fire(new a.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))),_&&_(S)})}hasTransition(){return!1}hasTile(_){return!this.tileBounds||this.tileBounds.contains(_.canonical)}loaded(){return this._loaded}loadTile(_,d){const g=this.map._requestManager.normalizeTileURL(_.tileID.canonical.url(this.tiles,this.scheme)),S={request:this.map._requestManager.transformRequest(g,a.R.Tile),data:void 0,uid:_.uid,tileID:_.tileID,tileZoom:_.tileZoom,zoom:_.tileID.overscaledZ,tileSize:this.tileSize*_.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:_.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:a.o.devicePixelRatio,promoteId:this.promoteId};if(_.actor&&_.state!=="expired")if(_.state==="loading")_.reloadCallback=d;else{if(_.buckets){const R=Object.values(_.buckets);for(const L of R)L.dirty=!0;return void(_.state="loaded")}_.request=_.actor.send("reloadTile",S,E.bind(this))}else _.actor=this.dispatcher.getActor(),_.request=_.actor.send("loadTile",S,E.bind(this),void 0,!0);function E(R,L){return _.aborted?d(null):R&&R.status!==404?d(R):(this.map._refreshExpiredTiles&&L&&_.setExpiryData(L),_.loadModelData(L,this.map.painter),_.state="loaded",void d(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends a.aV{constructor(_,d,g,S){super(_,d,g,S),d.coordinates?Array.isArray(d.coordinates)&&d.coordinates.length===4&&!d.coordinates.some(E=>!Array.isArray(E)||E.length!==2||E.some(R=>typeof R!="number"))||this.fire(new a.B(new a.V(`sources.${_}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new a.B(new a.V(`sources.${_}`,null,'missing required property "coordinates"'))),d.animate&&typeof d.animate!="boolean"&&this.fire(new a.B(new a.V(`sources.${_}`,null,'optional "animate" property must be a boolean value'))),d.canvas?typeof d.canvas=="string"||d.canvas instanceof HTMLCanvasElement||this.fire(new a.B(new a.V(`sources.${_}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new a.B(new a.V(`sources.${_}`,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 a.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(_){this.map=_,this.load(),this.canvas&&this.animate&&this.play()}onRemove(_){this.pause()}prepare(){let _=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,_=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,_=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const d=this.map.painter.context;this.texture?!_&&!this._playing||this.texture instanceof a.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new a.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 _ of[this.canvas.width,this.canvas.height])if(isNaN(_)||_<=0)return!0;return!1}},custom:class extends a.E{constructor(_,d,g,S){super(),this.id=_,this.type="custom",this._dataType="raster",this._dispatcher=g,this._implementation=d,this.setEventedParent(S),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new a.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new a.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new Iu(this._implementation.bounds,this.minzoom,this.maxzoom));const E=d;E.update=this._update.bind(this),E.clearTiles=this._clearTiles.bind(this),E.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,a.aJ(d,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return a.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new a.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(_){this.map=_,this._loaded=!1,this.fire(new a.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(_),this.load()}onRemove(_){this._implementation.onRemove&&this._implementation.onRemove(_)}hasTile(_){if(this._implementation.hasTile){const{x:d,y:g,z:S}=_.canonical;return this._implementation.hasTile({x:d,y:g,z:S})}return!this.tileBounds||this.tileBounds.contains(_.canonical)}loadTile(_,d){const{x:g,y:S,z:E}=_.tileID.canonical,R=new AbortController,L=Promise.resolve(this._implementation.loadTile({x:g,y:S,z:E},{signal:R.signal})).then((function(B){return delete _.request,_.aborted?(_.state="unloaded",d(null)):B===void 0?(_.state="errored",d(null)):B===null?(this.loadTileData(_,{width:this.tileSize,height:this.tileSize,data:null}),_.state="loaded",d(null)):function(U){return U instanceof ImageData||U instanceof HTMLCanvasElement||U instanceof ImageBitmap||U instanceof HTMLImageElement}(B)?(this.loadTileData(_,B),_.state="loaded",void d(null)):(_.state="errored",d(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(B=>{B.name!=="AbortError"&&(_.state="errored",d(B))});L.cancel=()=>R.abort(),_.request=L}loadTileData(_,d){_.setTexture(d,this.map.painter)}unloadTile(_,d){if(_.texture&&_.texture instanceof a.T?(_.destroy(!1),_.texture&&_.texture instanceof a.T&&this.map.painter.saveTileTexture(_.texture)):_.destroy(),this._implementation.unloadTile){const{x:g,y:S,z:E}=_.tileID.canonical;this._implementation.unloadTile({x:g,y:S,z:E})}d&&d()}abortTile(_,d){_.request&&_.request.cancel&&(_.request.cancel(),delete _.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(_=>({x:_.canonical.x,y:_.canonical.y,z:_.canonical.z}))}_clearTiles(){const _=a.F(this.id,this.scope);this.map.style.clearSource(_)}_update(){this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))}}},Eb=function(_,d,g,S){const E=new jb[d.type](_,d,g,S);if(E.id!==_)throw new Error(`Expected Source id to be ${_} instead of ${E.id}`);return a.aZ(["load","abort","unload","serialize","prepare"],E),E};function Bj(_,d,g=""){return`${g}:${d.id||""}:${d.layer.id}:${function(S){if("layerId"in S)return`layer:${S.layerId}`;{const{featuresetId:E,importId:R}=S;return`featureset:${E}${R?`:import:${R}`:""}`}}(_.target)}`}function Xd(_,d,g,S=""){if(_.uniqueFeatureID){const E=Bj(_,d,S);if(g.has(E))return!0;g.add(E)}return!1}function TI(_,d,g,S,E=!1,R=void 0){const L=d.sourceCache.transform,B=d.sourceCache.tilesIn(_,d.has3DLayers,E);B.sort(Ab);const U=[];for(const W of B){const Z=W.tile.queryRenderedFeatures(d,W,g,S,L,E,R);Object.keys(Z).length&&U.push({wrappedTileID:W.tile.tileID.wrapped().key,queryResults:Z})}for(const W in d.layers){const Z=d.layers[W];if(Z.styleLayer){const ne=Z.styleLayer.queryRenderedFeatures(_,d.sourceCache,S);Object.keys(ne).length&&U.push({wrappedTileID:0,queryResults:ne})}}return U.length===0?{}:function(W){const Z={},ne={};for(const re of W){const ie=re.queryResults,ce=re.wrappedTileID,le=ne[ce]=ne[ce]||{};for(const be in ie){const _e=ie[be],Re=le[be]=le[be]||{},Me=Z[be]=Z[be]||[];for(const je of _e)Re[je.featureIndex]||(Re[je.featureIndex]=!0,Me.push(je))}}return Z}(U)}function kb(_,d,g,S,E,R){const L={},B=S.queryRenderedSymbols(_),U=[];for(const W of Object.keys(B).map(Number))U.push(E[W]);U.sort(Ab);for(const W of U){const Z=W.featureIndex.lookupSymbolFeatures(B[W.bucketInstanceId],W.bucketIndex,W.sourceLayerIndex,d,g,R);for(const ne in Z){const re=L[ne]=L[ne]||[],ie=Z[ne];ie.sort((ce,le)=>{const be=W.featureSortOrder;if(be){const _e=be.indexOf(ce.featureIndex);return be.indexOf(le.featureIndex)-_e}return le.featureIndex-ce.featureIndex});for(const ce of ie)re.push(ce)}}return L}function $j(_,d){const g=_.getRenderableIds().map(R=>_.getTileByID(R)),S=[],E={};for(let R=0;R{if(R)g(R);else try{const U=S.getHeaderLength(L);if(U>d)return void(this.request=this.fetchHeader(U,g));S.parseHeader(L),this._isHeaderLoaded=!0;let W=0;for(const Z of Object.values(S.layers))W=Math.max(W,Z.dataIndex[Z.dataIndex.length-1].lastByte);L.byteLength>=W&&(this.entireBuffer=L),g(null,this.entireBuffer||L,B)}catch(U){g(U)}}),this.request}fetchBandForRender(d,g,S,E){this.fetchBand(d,g,S,R=>{if(R)return void E(R);this.updateTextureDescriptor(d,g,S);const L=this.textureDescriptorPerLayer.get(g);E(null,L?L.img:null)})}fetchBand(d,g,S,E,R=!0){const L=this._mrt;if(!this._isHeaderLoaded||!L)return void E(new Error("Tile header is not ready"));const B=this.actor;if(!B)return void E(new Error("Can't fetch tile band without an actor"));let U;const W=a.F(String(S),a.F(this.tileID.key,d));let Z=this._taskQueue.get(W);Z?Z.add(E):(Z=new Set,Z.add(E),this._taskQueue.set(W,Z));const ne=(le,be)=>{U.complete(le,be),le?E(le):(Z.forEach(_e=>_e(null,be)),this._taskQueue.delete(W))},re=(le,be)=>{if(le)return E(le);const _e=B.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:be,task:U},ne,void 0,!0);if(g!==null){const Re=this._workQueuePerLayer.get(g)||[];Re.push(()=>{_e&&_e.cancel(),U.cancel()}),this._workQueuePerLayer.has(g)||this._workQueuePerLayer.set(g,Re)}};let ie;try{ie=L.getLayer(d)}catch(le){if(this.state==="reloading")return;throw le}if(!ie)return void E(new Error(`Unknown sourceLayer "${d}"`));if(ie.hasDataForBand(S))return Z.forEach(le=>le(null,null)),void this._taskQueue.delete(W);const ce=ie.getDataRange([S]);if(U=L.createDecodingTask(ce),!U||U.tasks.length)if(g!==null&&this.flushQueues(g),this.entireBuffer)re(null,this.entireBuffer.slice(ce.firstByte,ce.lastByte+1));else{const le=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ce.firstByte}-${ce.lastByte}`}}),be=a.b1(le,re);if(g!==null){const _e=this._fetchQueuePerLayer.get(g)||[];_e.push(()=>{be.cancel(),U.cancel()}),this._fetchQueuePerLayer.has(g)||this._fetchQueuePerLayer.set(g,_e)}}}updateNeeded(d,g){return(!this.textureDescriptorPerLayer.get(d)||this.textureDescriptorPerLayer.get(d).band!==g||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(d,g,S){if(!this._mrt)return;const E=this._mrt.getLayer(d);if(!E||!E.hasBand(S)||!E.hasDataForBand(S))return;const{bytes:R,tileSize:L,buffer:B,offset:U,scale:W}=E.getBandView(S),Z=L+2*B,ne=new a.q({width:Z,height:Z},R),re=this.texturePerLayer.get(g);re&&re instanceof a.T&&re.update(ne,{premultiply:!1}),this.textureDescriptorPerLayer.set(g,{layer:d,band:S,img:ne,buffer:B,offset:U,tileSize:L,format:E.pixelFormat,mix:[W,256*W,65536*W,16777216*W]})}destroy(d=!1){if(super.destroy(d),delete this._mrt,!d)for(const g of this.texturePerLayer.values())g&&g instanceof a.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 Xg{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,S){const E=d.wrapped().key;this.data[E]===void 0&&(this.data[E]=[]);const R={value:g,timeout:void 0};if(S!==void 0&&(R.timeout=setTimeout(()=>{this.remove(d,R)},S)),this.data[E].push(R),this.order.push(E),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 S=d.wrapped().key,E=g===void 0?0:this.data[S].indexOf(g),R=this.data[S][E];return this.data[S].splice(E,1),R.timeout&&clearTimeout(R.timeout),this.data[S].length===0&&delete this.data[S],this.onRemove(R.value),this.order.splice(this.order.indexOf(S),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 S in this.data)for(const E of this.data[S])d(E.value)||g.push(E);for(const S of g)this.remove(S.value.tileID,S)}}class zj{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(d,g,S){const E=String(g);if(this.stateChanges[d]=this.stateChanges[d]||{},this.stateChanges[d][E]=this.stateChanges[d][E]||{},Object.assign(this.stateChanges[d][E],S),this.deletedStates[d]===null){this.deletedStates[d]={};for(const R in this.state[d])R!==E&&(this.deletedStates[d][R]=null)}else if(this.deletedStates[d]&&this.deletedStates[d][E]===null){this.deletedStates[d][E]={};for(const R in this.state[d][E])S[R]||(this.deletedStates[d][E][R]=null)}else for(const R in S)this.deletedStates[d]&&this.deletedStates[d][E]&&this.deletedStates[d][E][R]===null&&delete this.deletedStates[d][E][R]}removeFeatureState(d,g,S){if(this.deletedStates[d]===null)return;const E=String(g);if(this.deletedStates[d]=this.deletedStates[d]||{},S&&g!==void 0)this.deletedStates[d][E]!==null&&(this.deletedStates[d][E]=this.deletedStates[d][E]||{},this.deletedStates[d][E][S]=null);else if(g!==void 0)if(this.stateChanges[d]&&this.stateChanges[d][E])for(S in this.deletedStates[d][E]={},this.stateChanges[d][E])this.deletedStates[d][E][S]=null;else this.deletedStates[d][E]=null;else this.deletedStates[d]=null}getState(d,g){const S=this.state[d]||{},E=this.stateChanges[d]||{},R=this.deletedStates[d];if(R===null)return{};if(g!==void 0){const B=String(g),U=Object.assign({},S[B],E[B]);if(R){const W=R[g];if(W===null)return{};for(const Z in W)delete U[Z]}return U}const L=Object.assign({},S,E);if(R)for(const B in R)delete L[B];return L}initializeTileState(d,g){d.refreshFeatureState(g)}coalesceChanges(d,g){const S={};for(const E in this.stateChanges){this.state[E]=this.state[E]||{};const R={};for(const L in this.stateChanges[E])this.state[E][L]||(this.state[E][L]={}),Object.assign(this.state[E][L],this.stateChanges[E][L]),R[L]=this.state[E][L];S[E]=R}for(const E in this.deletedStates){this.state[E]=this.state[E]||{};const R={};if(this.deletedStates[E]===null)for(const L in this.state[E])R[L]={},this.state[E][L]={};else for(const L in this.deletedStates[E]){if(this.deletedStates[E][L]===null)this.state[E][L]={};else if(this.state[E][L])for(const B of Object.keys(this.deletedStates[E][L]))delete this.state[E][L][B];R[L]=this.state[E][L]}S[E]=S[E]||{},Object.assign(S[E],R)}if(this.stateChanges={},this.deletedStates={},Object.keys(S).length!==0)for(const E in d)d[E].refreshFeatureState(g,S)}}class Pu extends a.E{constructor(d,g,S){super(),this.id=d,this._renderSourceType=S,this._maxzoomOverride=null,g.on("data",E=>{E.dataType==="source"&&E.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&E.dataType==="source"&&E.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),g.on("error",()=>{this._sourceErrored=!0}),this._source=g,this._tiles={},this._cache=new Xg(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 zj,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 S=this._tiles[g];S.upload(d,this.map?this.map.painter:void 0),S.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(Uj).map(d=>d.key)}getRenderableIds(d,g){const S=[];for(const E in this._tiles)this._isIdRenderable(+E,d,g)&&S.push(this._tiles[E]);return d?S.sort((E,R)=>{const L=E.tileID,B=R.tileID,U=new a.P(L.canonical.x,L.canonical.y)._rotate(this.transform.angle),W=new a.P(B.canonical.x,B.canonical.y)._rotate(this.transform.angle);return L.overscaledZ-B.overscaledZ||W.y-U.y||W.x-U.x}).map(E=>E.tileID.key):S.map(E=>E.tileID).sort(Uj).map(E=>E.key)}hasRenderableParent(d){const g=this.findLoadedParent(d,0);return!!g&&this._isIdRenderable(g.tileID.key)}_isIdRenderable(d,g,S){return this._tiles[d]&&this._tiles[d].hasData()&&!this._coveredTiles[d]&&(g||!this._tiles[d].holdingForFade())&&(S||!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 S=this._tiles[d];S&&(S.state!=="loading"&&(S.state=g),this._loadTile(S,this._tileLoaded.bind(this,S,d,g)))}_tileLoaded(d,g,S,E,R){if(E){if(d.state="errored",a.b2(E)){if(this._source.fire(new a.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 B=this.map.painter.terrain;this.update(this.transform,B.getScaledDemTileSize(),!0),B.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new a.B(E,{tile:d}));return}d.timeAdded=a.o.now(),S==="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;R&&R.responseHeaders&&(L=R.responseHeaders),this._source.fire(new a.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 E=0;E1||(Math.abs(L)>1&&(Math.abs(L+U)===1?L+=U:Math.abs(L-U)===1&&(L-=U)),R.dem&&E.dem&&(E.dem.backfillBorder(R.dem,L,B),E.neighboringTiles&&E.neighboringTiles[W]&&(E.neighboringTiles[W].backfilled=!0)))}}getTile(d){return this.getTileByID(d.key)}getTileByID(d){return this._tiles[d]}_retainLoadedChildren(d,g,S,E){for(const R in this._tiles){let L=this._tiles[R];if(E[R]||!L.hasData()||L.tileID.overscaledZ<=g||L.tileID.overscaledZ>S)continue;let B=L.tileID;for(;L&&L.tileID.overscaledZ>g+1;){const W=L.tileID.scaledTo(L.tileID.overscaledZ-1);L=this._tiles[W.key],L&&L.hasData()&&(B=W)}let U=B;for(;U.overscaledZ>g;)if(U=U.scaledTo(U.overscaledZ-1),d[U.key]){E[B.key]=B;break}}}findLoadedParent(d,g){if(d.key in this._loadedParentTiles){const S=this._loadedParentTiles[d.key];return S&&S.tileID.overscaledZ>=g?S:null}for(let S=d.overscaledZ-1;S>=g;S--){const E=d.scaledTo(S),R=this._getLoadedTile(E);if(R)return R}}_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 S=Math.ceil(d.width/g)+1,E=Math.ceil(d.height/g)+1,R=Math.floor(S*E*5),L=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,R):R,B=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,L):L;this._cache.setMaxSize(B)}handleWrapJump(d){const g=Math.round((d-(this._prevLng===void 0?d:this._prevLng))/360);if(this._prevLng=d,g){const S={};for(const E in this._tiles){const R=this._tiles[E];R.tileID=R.tileID.unwrapTo(R.tileID.wrap+g),S[R.tileID.key]=R}this._tiles=S;for(const E in this._timers)clearTimeout(this._timers[E]),delete this._timers[E];for(const E in this._tiles)this._setTileReloadTimer(+E,this._tiles[E])}}update(d,g,S,E,R){if(this.transform=d,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!S)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 B,U=this._source.maxzoom;this._maxzoomOverride!==null&&(U=Math.min(U,this._maxzoomOverride));const W=this.map&&this.map.painter?this.map.painter._terrain:null;if(W&&W.sourceCache===this&&W.attenuationRange()){const ie=W.attenuationRange()[0],ce=Math.floor(ie)-Math.log2(W.getDemUpscale());U>ce&&(U=ce)}const Z=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)B=d.getVisibleUnwrappedCoordinates(this._source.tileID).map(ie=>new a.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,B=ie.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:U,roundZoom:this._source.roundZoom&&!S,reparseOverscaled:Z,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.minzoom<=1&&d.projection.name==="globe"&&(B.push(new a.aR(1,0,1,0,0)),B.push(new a.aR(1,0,1,1,0)),B.push(new a.aR(1,0,1,0,1)),B.push(new a.aR(1,0,1,1,1)))}else if(B=d.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:U,roundZoom:this._source.roundZoom&&!S,reparseOverscaled:Z,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.hasTile){const ie=this._source.hasTile.bind(this._source);B=B.filter(ce=>ie(ce))}}else B=[];if(B.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const ie=d.coveringZoomLevel({tileSize:g||this._source.tileSize,roundZoom:this._source.roundZoom&&!S}),ce=Math.min(ie,U);if(L){const le=d.extendTileCover(B,ce);for(const be of le)B.push(be)}else if(R){const le=this.transform.getFrustum(ce),be=d.extendTileCoverToNearPlane(B,le,ce);for(const _e of be)B.push(_e);if(ce>=18&&this._hasTunnelGeometry()){const _e=d.extendTileCoverForTunnels(B,le,ce,20);for(const Re of _e)B.push(Re)}}else if(this.castsShadows&&E){const le=d.extendTileCover(B,ce,E,16);for(const be of le)this._shadowCasterTiles[be.key]=!0,B.push(be)}}const ne=this._updateRetainedTiles(B);if(this._supportsFading&&B.length!==0){const ie={},ce={},le=a.o.now(),be=Object.keys(ne);for(const Re of be){const Me=ne[Re],je=this._tiles[Re];if(!je||je.fadeEndTime!==void 0&&je.fadeEndTime<=le)continue;const Xe=this.findLoadedParent(Me,Math.max(Me.overscaledZ-Pu.maxOverzooming,this._source.minzoom));Xe&&(this._addTile(Xe.tileID),ie[Xe.tileID.key]=Xe.tileID),ce[Re]=Me}const _e=B[B.length-1].overscaledZ;for(const Re in this._tiles){const Me=this._tiles[Re];if(ne[Re]||!Me.hasData())continue;let je=Me.tileID;for(;je.overscaledZ>_e;){je=je.scaledTo(je.overscaledZ-1);const Xe=this._tiles[je.key];if(Xe&&Xe.hasData()&&ce[je.key]){ne[Re]=Me.tileID;break}}}for(const Re in ie)ne[Re]||(this._coveredTiles[Re]=!0,ne[Re]=ie[Re])}for(const ie in ne)this._tiles[ie].clearFadeHold();const re=a.b3(this._tiles,ne);for(const ie of re){const ce=this._tiles[ie];ce.hasSymbolBuckets&&!ce.holdingForFade()?ce.setHoldDuration(this.map._fadeDuration):ce.hasSymbolBuckets&&!ce.symbolFadeFinished()||this._removeTile(+ie)}this._updateLoadedParentTileCache(),this._renderSourceType===a.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 S={},E=d.reduce((W,Z)=>Math.min(W,Z.overscaledZ),1/0),R=d[0].overscaledZ,L=Math.max(R-Pu.maxOverzooming,this._source.minzoom),B=Math.max(R+Pu.maxUnderzooming,this._source.minzoom),U={};for(const W of d){const Z=this._addTile(W);g[W.key]=W,Z.hasData()||E=this._source.maxzoom){const re=W.children(this._source.maxzoom)[0],ie=this.getTile(re);if(ie&&ie.hasData()){g[re.key]=re;continue}}else{const re=W.children(this._source.maxzoom);if(g[re[0].key]&&g[re[1].key]&&g[re[2].key]&&g[re[3].key])continue}let ne=Z.wasRequested();for(let re=W.overscaledZ-1;re>=L;--re){const ie=W.scaledTo(re);if(S[ie.key]||(S[ie.key]=!0,Z=this.getTile(ie),!Z&&ne&&(Z=this._addTile(ie)),Z&&(g[ie.key]=ie,ne=Z.wasRequested(),Z.hasData())))break}}return g}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const d in this._tiles){const g=[];let S,E=this._tiles[d].tileID;for(;E.overscaledZ>0;){if(E.key in this._loadedParentTiles){S=this._loadedParentTiles[E.key];break}g.push(E.key);const R=E.scaledTo(E.overscaledZ-1);if(S=this._getLoadedTile(R),S)break;E=R}for(const R of g)this._loadedParentTiles[R]=S}}_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 S=!!g;if(!S){const E=this.map?this.map.painter:null,R=this._source.tileSize*d.overscaleFactor();g=this._source.type==="raster-array"?new xp(d,R,this.transform.tileZoom,E,this._isRaster):new a.b0(d,R,this.transform.tileZoom,E,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,S||this._source.fire(new a.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 S=g.getExpiryTimeout();S&&(this._timers[d]=setTimeout(()=>{this._reloadTile(d,"expired"),delete this._timers[d]},S))}_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,S){const E=[],R=this.transform;if(!R)return E;const L=R.projection.name==="globe",B=a.aH(R.center.lng);for(const U in this._tiles){const W=this._tiles[U];if(S&&W.clearQueryDebugViz(),W.holdingForFade())continue;let Z;if(L){const ne=W.tileID.canonical;if(ne.z===0){const re=[Math.abs(a.aC(B,...Qg(ne,-1))-B),Math.abs(a.aC(B,...Qg(ne,1))-B)];Z=[0,2*re.indexOf(Math.min(...re))-1]}else{const re=[Math.abs(a.aC(B,...Qg(ne,-1))-B),Math.abs(a.aC(B,...Qg(ne,0))-B),Math.abs(a.aC(B,...Qg(ne,1))-B)];Z=[re.indexOf(Math.min(...re))-1]}}else Z=[0];for(const ne of Z){const re=d.containsTile(W,R,g,ne);re&&E.push(re)}}return E}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(d){return this._getRenderableCoordinates(d)}_getRenderableCoordinates(d,g){const S=this.getRenderableIds(d,g).map(R=>this._tiles[R].tileID),E=this.transform.projection.name==="globe";for(const R of S)R.projMatrix=this.transform.calculateProjMatrix(R.toUnwrapped()),R.expandedProjMatrix=E?this.transform.calculateProjMatrix(R.toUnwrapped(),!1,!0):R.projMatrix;return S}sortCoordinatesByDistance(d){const g=d.slice(),S=this.transform._camera.position,E=this.transform._camera.forward(),R={};for(const L of g){const B=1/(1<R[L.key]-R[B.key]),g}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const d=a.o.now();for(const g in this._tiles){const S=this._tiles[g];if(S.fadeEndTime!==void 0&&S.fadeEndTime>=d)return!0}}return!1}setFeatureState(d,g,S){this._state.updateState(d=d||"_geojsonTileLayer",g,S)}removeFeatureState(d,g,S){this._state.removeFeatureState(d=d||"_geojsonTileLayer",g,S)}getFeatureState(d,g){return this._state.getState(d=d||"_geojsonTileLayer",g)}setDependencies(d,g,S){const E=this._tiles[d];E&&E.setDependencies(g,S)}reloadTilesForDependencies(d,g){for(const S in this._tiles)this._tiles[S].hasDependency(d,g)&&this._reloadTile(+S,"reloading");this._cache.filter(S=>!S.hasDependency(d,g))}_preloadTiles(d,g){if(!this._sourceLoaded){const U=()=>{this._sourceLoaded&&(this._source.off("data",U),this._preloadTiles(d,g))};return void this._source.on("data",U)}const S=new Map,E=Array.isArray(d)?d:[d],R=this.map.painter.terrain,L=this.usedForTerrain&&R?R.getScaledDemTileSize():this._source.tileSize;for(const U of E){const W=U.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 Z of W)S.set(Z.key,Z);this.usedForTerrain&&U.updateElevation(!1)}const B=Array.from(S.values());a.t(B,(U,W)=>{const Z=new a.b0(U,this._source.tileSize*U.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Z,ne=>{this._source.type==="raster-dem"&&Z.dem&&this._backfillDEM(Z),W(ne,Z)})},g)}}function Uj(_,d){const g=Math.abs(2*_.wrap)-+(_.wrap<0),S=Math.abs(2*d.wrap)-+(d.wrap<0);return _.overscaledZ-d.overscaledZ||S-g||d.canonical.y-_.canonical.y||d.canonical.x-_.canonical.x}function Qg(_,d){const g=1<<_.z;return[_.x/g+d,(_.x+1)/g+d]}Pu.maxOverzooming=10,Pu.maxUnderzooming=3;class D0{constructor(d){this.style=d,this.layersGotHidden=!1,this.layers=[]}processLayersChanged(){this.layers=[];const d=!1,g=!1;for(const S in this.style._mergedLayers){const E=this.style._mergedLayers[S];if(E.type==="fill-extrusion"||E.type==="building")this.layers.push({layer:E,visible:d,visibilityChanged:g});else if(E.type==="model"){const R=this.style.getLayerSource(E);R&&R.type==="batched-model"&&this.layers.push({layer:E,visible:d,visibilityChanged:g})}}}onNewFrame(d){this.layersGotHidden=!1;for(const g of this.layers){const S=g.layer;let E=!1;S.type==="fill-extrusion"?E=!S.isHidden(d)&&S.paint.get("fill-extrusion-opacity")>0:S.type==="building"?E=!S.isHidden(d)&&S.paint.get("building-opacity")>0:S.type==="model"&&(E=!S.isHidden(d)&&S.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!E&&g.visible,g.visible=E}}updateZOffset(d,g){this.currentBuildingBuckets=[];for(const E of this.layers){const R=E.layer,L=this.style.getLayerSourceCache(R);let B=1;R.type==="fill-extrusion"?B=E.visible?R.paint.get("fill-extrusion-vertical-scale"):0:R.type==="building"&&(B=E.visible?R.paint.get("building-vertical-scale"):0);let U=L?L.getTile(g):null;if(!U&&L)for(const W in L._tiles){const Z=L._tiles[W];if(g.canonical.isChildOf(Z.tileID.canonical)){U=Z;break}}this.currentBuildingBuckets.push({bucket:U?U.getBucket(R):null,tileID:U?U.tileID:g,verticalScale:B})}d.hasAnyZOffset=!1;let S=!1;for(let E=0;E{S in d&&(g[S]=d[S])}),g}function qj(_){_=_.slice();const d=Object.create(null);for(const g of _)d[g.id]=g;for(let g=0;g<_.length;g++){const S=_[g];if(S&&"ref"in S){const E=d[S.ref];E&&(_[g]=Vj(S,E))}}return _}const us={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setSlot:"setSlot",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight",setTerrain:"setTerrain",setFog:"setFog",setSnow:"setSnow",setRain:"setRain",setCamera:"setCamera",setLights:"setLights",setProjection:"setProjection",addImport:"addImport",removeImport:"removeImport",updateImport:"updateImport",addIconset:"addIconset",removeIconset:"removeIconset"};function Jg(_,d,g){g.push({command:us.addSource,args:[_,d[_]]})}function ey(_,d,g){d.push({command:us.removeSource,args:[_]}),g[_]=!0}function nB(_,d,g,S){ey(_,g,S),Jg(_,d,g)}function Nb(_,d,g){let S;for(S in _[g])if(_[g].hasOwnProperty(S)&&S!=="data"&&!a.b6(_[g][S],d[g][S]))return!1;for(S in d[g])if(d[g].hasOwnProperty(S)&&S!=="data"&&!a.b6(_[g][S],d[g][S]))return!1;return!0}function Wf(_,d,g,S,E,R){let L;for(L in d=d||{},_=_||{})_.hasOwnProperty(L)&&(a.b6(_[L],d[L])||g.push({command:R,args:[S,L,d[L],E]}));for(L in d)d.hasOwnProperty(L)&&!_.hasOwnProperty(L)&&(a.b6(_[L],d[L])||g.push({command:R,args:[S,L,d[L],E]}))}function ty(_){return _.id}function O0(_,d){return _[d.id]=d,_}function Cb(_,d,g){const S=d.createTileMatrix(_,_.worldSize,g.toUnwrapped());return a.aD(new Float32Array(16),_.projMatrix,S)}function jI(_,d,g){if(d.projection.name===g.projection.name)return _.projMatrix;const S=g.clone();return S.setProjection(d.projection),Cb(S,d.getProjection(),_)}function vp(_,d,g){return d.name===g.projection.name?_.projMatrix:Cb(g,d,_)}class EI{constructor(d,g){this.reset(d,g)}reset(d,g){this.points=d||[],this._distances=[0];for(let S=1;S0?(E-L)/B:0;return this.points[R].mult(1-U).add(this.points[g].mult(U))}}class Gj{constructor(d,g,S){const E=this.boxCells=[],R=this.circleCells=[];this.xCellCount=Math.ceil(d/S),this.yCellCount=Math.ceil(g/S);for(let L=0;Lthis.width||E<0||g>this.height)return!R&&[];const B=[];if(d<=0&&g<=0&&this.width<=S&&this.height<=E){if(R)return!0;for(let U=0;U0:B}_queryCircle(d,g,S,E,R){const L=d-S,B=d+S,U=g-S,W=g+S;if(B<0||L>this.width||W<0||U>this.height)return!E&&[];const Z=[];return this._forEachCell(L,U,B,W,this._queryCellCircle,Z,{hitTest:E,circle:{x:d,y:g,radius:S},seenUids:{box:{},circle:{}}},R),E?Z.length>0:Z}query(d,g,S,E,R){return this._query(d,g,S,E,!1,R)}hitTest(d,g,S,E,R){return this._query(d,g,S,E,!0,R)}hitTestCircle(d,g,S,E){return this._queryCircle(d,g,S,!0,E)}_queryCell(d,g,S,E,R,L,B,U){const W=B.seenUids,Z=this.boxCells[R];if(Z!==null){const re=this.bboxes;for(const ie of Z)if(!W.box[ie]){W.box[ie]=!0;const ce=4*ie;if(d<=re[ce+2]&&g<=re[ce+3]&&S>=re[ce+0]&&E>=re[ce+1]&&(!U||U(this.boxKeys[ie]))){if(B.hitTest)return L.push(!0),!0;L.push({key:this.boxKeys[ie],x1:re[ce],y1:re[ce+1],x2:re[ce+2],y2:re[ce+3]})}}}const ne=this.circleCells[R];if(ne!==null){const re=this.circles;for(const ie of ne)if(!W.circle[ie]){W.circle[ie]=!0;const ce=3*ie;if(this._circleAndRectCollide(re[ce],re[ce+1],re[ce+2],d,g,S,E)&&(!U||U(this.circleKeys[ie]))){if(B.hitTest)return L.push(!0),!0;{const le=re[ce],be=re[ce+1],_e=re[ce+2];L.push({key:this.circleKeys[ie],x1:le-_e,y1:be-_e,x2:le+_e,y2:be+_e})}}}}}_queryCellCircle(d,g,S,E,R,L,B,U){const W=B.circle,Z=B.seenUids,ne=this.boxCells[R];if(ne!==null){const ie=this.bboxes;for(const ce of ne)if(!Z.box[ce]){Z.box[ce]=!0;const le=4*ce;if(this._circleAndRectCollide(W.x,W.y,W.radius,ie[le+0],ie[le+1],ie[le+2],ie[le+3])&&(!U||U(this.boxKeys[ce])))return L.push(!0),!0}}const re=this.circleCells[R];if(re!==null){const ie=this.circles;for(const ce of re)if(!Z.circle[ce]){Z.circle[ce]=!0;const le=3*ce;if(this._circlesCollide(ie[le],ie[le+1],ie[le+2],W.x,W.y,W.radius)&&(!U||U(this.circleKeys[ce])))return L.push(!0),!0}}}_forEachCell(d,g,S,E,R,L,B,U){const W=this._convertToXCellCoord(d),Z=this._convertToYCellCoord(g),ne=this._convertToXCellCoord(S),re=this._convertToYCellCoord(E);for(let ie=W;ie<=ne;ie++)for(let ce=Z;ce<=re;ce++)if(R.call(this,d,g,S,E,this.xCellCount*ce+ie,L,B,U))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,S,E,R,L){const B=E-d,U=R-g,W=S+L;return W*W>B*B+U*U}_circleAndRectCollide(d,g,S,E,R,L,B){const U=(L-E)/2,W=Math.abs(d-(E+U));if(W>U+S)return!1;const Z=(B-R)/2,ne=Math.abs(g-(R+Z));if(ne>Z+S)return!1;if(W<=U||ne<=Z)return!0;const re=W-U,ie=ne-Z;return re*re+ie*ie<=S*S}}const sB=Math.tan(85*Math.PI/180);function Kf(_,d,g,S,E,R,L){const B=a.bb();if(g)if(R.name==="globe"){const U=a.bc(E,d);a.aD(B,B,U)}else{const U=a.bd([],L);B[0]=U[0],B[1]=U[1],B[4]=U[2],B[5]=U[3],S||a.ba(B,B,E.angle)}else a.aD(B,E.labelPlaneMatrix,_);return B}function ud(_,d,g,S,E,R,L){const B=Kf(_,d,g,S,E,R,L);return R.name==="globe"&&g||(B[2]=B[6]=B[10]=B[14]=0),B}function ry(_,d,g,S,E,R,L){if(g){if(R.name==="globe"){const B=Kf(_,d,g,S,E,R,L);return a.b7(B,B),a.aD(B,_,B),B}{const B=a.b8(_),U=a.b9([]);return U[0]=L[0],U[1]=L[1],U[4]=L[2],U[5]=L[3],a.aD(B,B,U),S||a.ba(B,B,-E.angle),B}}return E.glCoordMatrix}function Ru(_,d,g,S){const E=[_,d,g,1];g?a.aE(E,E,S):sn(E,E,S);const R=E[3];return E[0]/=R,E[1]/=R,E[2]/=R,E}function Ib(_,d){return Math.min(.5+_/d*.5,1.5)}function F0(_,d){const g=_[0]/_[3],S=_[1]/_[3];return g>=-d[0]&&g<=d[0]&&S>=-d[1]&&S<=d[1]}function Tc(_,d,g,S,E,R,L,B,U,W,Z=1){const ne=g.transform,re=S?_.textSizeData:_.iconSizeData,ie=a.bj(re,g.transform.zoom,Z),ce=ne.projection.name==="globe",le=[256/g.width*2+1,256/g.height*2+1],be=S?_.text.dynamicLayoutVertexArray:_.icon.dynamicLayoutVertexArray;be.clear();let _e=null;ce&&(_e=S?_.text.globeExtVertexArray:_.icon.globeExtVertexArray);const Re=_.lineVertexArray,Me=S?_.text.placedSymbolArray:_.icon.placedSymbolArray,je=g.transform.width/g.transform.height;let Xe,$e=!1;for(let Ke=0;KeMath.abs(g)?{useVertical:!0}:_===a.bk.vertical?S>0?{needsFlipping:!0}:null:d!==0&&function(E,R){return E===0||Math.abs(R/E)>sB}(g,S)?d===1?{needsFlipping:!0}:null:g<0?{needsFlipping:!0}:null}function Wj(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re,Me){const je=d/24,Xe=_.lineOffsetX*je,$e=_.lineOffsetY*je,{lineStartIndex:Ke,glyphStartIndex:De,numGlyphs:Be,segment:Ge,writingMode:ot,flipState:Je}=_,St=Ke+_.lineLength,pt=Ot=>{if(Z){const[_t,jt,Nt]=Ot.up,lr=W.length;a.bm(Z,lr+0,_t,jt,Nt),a.bm(Z,lr+1,_t,jt,Nt),a.bm(Z,lr+2,_t,jt,Nt),a.bm(Z,lr+3,_t,jt,Nt)}const[Ut,ut,st]=Ot.point;a.bn(W,Ut,ut,st,Ot.angle)};if(Be>1){const Ot=Hj(je,B,Xe,$e,g,ne,re,_,U,R,ie,le,!1,be,_e,Re,Me);if(!Ot)return{notEnoughRoom:!0};if(S&&!g){let[Ut,ut,st]=Ot.first.point,[_t,jt,Nt]=Ot.last.point;[Ut,ut]=Ru(Ut,ut,st,L),[_t,jt]=Ru(_t,jt,Nt,L);const lr=Pb(ot,Je,(_t-Ut)*ce,jt-ut);if(_.flipState=lr&&lr.needsFlipping?1:2,lr)return lr}pt(Ot.first);for(let Ut=De+1;Ut0?_t:Kj(re,st,Ut,1,E,void 0,be,_e.canonical),Nt=Pb(ot,Je,(jt[0]-Ut[0])*ce,jt[1]-Ut[1]);if(_.flipState=Nt&&Nt.needsFlipping?1:2,Nt)return Nt}const Ot=Rb(je*B.getoffsetX(De),Xe,$e,g,ne,re,Ge,Ke,St,U,R,ie,le,!1,!1,be,_e,Re,Me);if(!Ot)return{notEnoughRoom:!0};pt(Ot)}return{}}function as(_,d,g,S,E){const{x:R,y:L,z:B}=S.projectTilePoint(_.x,_.y,d);if(!E)return Ru(R,L,B,g);const[U,W,Z]=E.getElevation(_,E.elevation,E.elevationFeature);return Ru(R+U,L+W,B+Z,g)}function Kj(_,d,g,S,E,R,L,B){const U=as(_.sub(d)._unit()._add(_),B,E,L,R);return a.ax(U,g,U),a.ay(U,U),a.bg(U,g,U,S)}function Rb(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re){const Me=S?_-d:_+d;let je=Me>0?1:-1,Xe=0;S&&(je*=-1,Xe=Math.PI),je<0&&(Xe+=Math.PI);let $e=B+L+(je>0?0:1)|0,Ke=E,De=E,Be=0,Ge=0;const ot=Math.abs(Me),Je=[],St=[];let pt=R,Ot=pt,Ut=a.be([]);const ut=()=>Kj(Ot,pt,De,ot-Be+1,Z,re,le,be.canonical);for(;Be+Ge<=ot;){if($e+=je,$e=U)return null;if(De=Ke,Ot=pt,Je.push(De),ie&&St.push(Ot),pt=new a.P(W.getx($e),W.gety($e)),Ke=ne[$e],!Ke){const Fr=as(pt,be.canonical,Z,le,re);Ke=Fr[3]>0?ne[$e]=Fr:ut()}Be+=Ge;const zt=a.ax([],Ke,De),Pr=a.bf(De,Ke);if(g&&Pr>0&&Ge>0&&a.bi(Ut,zt)/(Ge*Pr)0,Me),Ke=W*$e.perspectiveRatio,De=(S.x1*g+B.x-S.padding)*Ke+$e.point.x,Be=(S.y1*g+B.y-S.padding)*Ke+$e.point.y,Ge=(S.x2*g+B.x+S.padding)*Ke+$e.point.x,ot=(S.y2*g+B.y+S.padding)*Ke+$e.point.y,Je=$e.perspectiveRatio<=.55||$e.occluded;return!this.isInsideGrid(De,Be,Ge,ot)||!U&&this.grid.hitTest(De,Be,Ge,ot,ne)||Je?{box:[],offscreen:!1,occluded:$e.occluded}:{box:[De,Be,Ge,ot],offscreen:this.isOffscreen(De,Be,Ge,ot),occluded:!1}}placeCollisionCircles(d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be){const _e=[],Re=this.transform.elevation,Me=d.getProjection(),je=d.elevationType==="road",Xe=!!Re||je,$e=a.bu.getAtTileOffsetFunc(be,this.transform.center.lat,this.transform.worldSize,Me),Ke=new a.P(S.tileAnchorX,S.tileAnchorY),De=new a.P(S.tileAnchorX,S.tileAnchorY);let{x:Be,y:Ge,z:ot}=Me.projectTilePoint(De.x,De.y,be.canonical),Je=null;if(Xe){const Pr=je?d.getElevationFeatureForText(E):null;Je={getElevation:$e,elevation:Re,elevationFeature:Pr};const[Fr,br,Nr]=$e(Ke,Re,Pr);Be+=Fr,Ge+=br,ot+=Nr}const St=Me.name==="globe",pt=this.projectAndGetPerspectiveRatio(U,Be,Ge,ot,be,St||!!Re||this.transform.pitch>0,Me),{perspectiveRatio:Ot}=pt,Ut=(re?B/Ot:B*Ot)/a.by,ut=Ru(Be,Ge,ot,W),st=S.lineOffsetX*Ut,_t=S.lineOffsetY*Ut,jt=a.ap(d.layers[0].layout.get("text-max-angle")),Nt=Math.cos(jt),lr=pt.signedDistanceFromCamera>0?Hj(Ut,L,st,_t,je&&S.flipState===1,ut,De,S,R,W,{},Xe&&!re?Je:null,re&&Xe,Me,be,re,Nt):null;let Jt=!1,er=!1,zt=!0;if(lr&&!pt.occluded){const Pr=.5*ce*Ot+le,Fr=new a.P(-100,-100),br=new a.P(this.screenRightBoundary,this.screenBottomBoundary),Nr=new EI,{first:Jr,last:dn}=lr,on=Jr.path.length;let Tn=[];for(let ln=on-1;ln>=1;ln--)Tn.push(Jr.path[ln]);for(let ln=1;ln(Xe&&!St&&(Cs=$e(liln[3]<=0)&&(Tn=[]));let jn=[];if(Tn.length>0){let ln=1/0,ts=-1/0,Cs=1/0,li=-1/0;for(const Fs of Tn)ln=Math.min(ln,Fs[0]),Cs=Math.min(Cs,Fs[1]),ts=Math.max(ts,Fs[0]),li=Math.max(li,Fs[1]);ts>=Fr.x&&ln<=br.x&&li>=Fr.y&&Cs<=br.y&&(jn=[Tn.map(Fs=>new a.P(Fs[0],Fs[1]))],(lnbr.x||Csbr.y)&&(jn=a.bv(jn,Fr.x,Fr.y,br.x,br.y)))}for(const ln of jn){Nr.reset(ln,.25*Pr);let ts=0;ts=Nr.length<=.5*Pr?1:Math.ceil(Nr.paddedLength/Kr)+1;for(let Cs=0;Cs0?(a.aE(U,U,d),this.fogState&&R&&B.name!=="globe"&&(W=function(re,ie,ce,le,be,_e){const Re=_e.calculateFogTileMatrix(be),Me=[ie,ce,le];return a.ah(Me,Me,Re),wn(re,a.ai(Me),_e.pitch,_e._fov)}(this.fogState,g,S,E,R.toUnwrapped(),this.transform)>.9)):sn(U,U,d);const Z=U[3];return{point:new a.P((U[0]/Z+1)/2*this.transform.width+dd,(-U[1]/Z+1)/2*this.transform.height+dd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(B)/Z*.5,1.5),signedDistanceFromCamera:Z,occluded:L&&U[2]>Z||W}}isOffscreen(d,g,S,E){return S=this.screenRightBoundary||Ethis.screenBottomBoundary}isInsideGrid(d,g,S,E){return S>=0&&d=0&&gS.collisionGroupID===g}}return this.collisionGroups[d]}}function Ml(_,d,g,S,E){const{horizontalAlign:R,verticalAlign:L}=a.bF(_),B=-(R-.5)*d,U=-(L-.5)*g,W=a.bG(_,S);return new a.P(B+W[0]*E,U+W[1]*E)}function Yf(_,d,g,S,E){const R=new a.P(_,d);return g&&R._rotate(S?E:-E),R}class Ts{constructor(d,g,S,E,R,L){this.transform=d.clone(),this.projection=d.projection.name,this.collisionIndex=new Lb(this.transform,R),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 Ss(S),this.collisionCircleArrays={},this.prevPlacement=E,E&&(E.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(d,g,S,E,R=1){const L=S.getBucket(g),B=S.latestFeatureIndex;if(!L||!B||g.fqid!==L.layerIds[0])return;const U=L.layers[0].layout,W=L.layers[0].paint,Z=S.collisionBoxArray,ne=Math.pow(2,this.transform.zoom-S.tileID.overscaledZ),re=S.tileSize/a.an,ie=S.tileID.toUnwrapped();this.transform.setProjection(L.projection);const ce=(le=S.tileID,be=L.getProjection(),_e=this.transform,be.name===this.projection?_e.calculateProjMatrix(le.toUnwrapped()):Cb(_e,be,le));var le,be,_e;const Re=U.get("text-pitch-alignment")==="map",Me=U.get("text-rotation-alignment")==="map";g.compileFilter(g.options);const je=g.dynamicFilter(),Xe=g.dynamicFilterNeedsFeature(),$e=g.dynamicFilterNeedsGeometry(),Ke=this.transform.calculatePixelsToTileUnitsMatrix(S),De=ud(ce,S.tileID.canonical,Re,Me,this.transform,L.getProjection(),Ke);let Be=null;const Ge=L.getProjection().createInversionMatrix(this.transform,S.tileID.canonical);if(Re){const _t=ry(ce,S.tileID.canonical,Re,Me,this.transform,L.getProjection(),Ke);Be=a.aD([],this.transform.labelPlaneMatrix,_t)}let ot=null;je&&S.latestFeatureIndex&&(ot={unwrappedTileID:ie,dynamicFilter:je,dynamicFilterNeedsFeature:Xe,needGeometry:$e}),this.retainedQueryData[L.bucketInstanceId]=new vs(L.bucketInstanceId,B,L.sourceLayerIndex,L.index,S.tileID);const[Je,St]=L.layers[0].layout.get("text-size-scale-range"),pt=a.aC(R,Je,St),[Ot,Ut]=U.get("icon-size-scale-range"),ut=a.aC(R,Ot,Ut),st={bucket:L,layout:U,paint:W,posMatrix:ce,invMatrix:Ge,mercatorCenter:[a.aH(this.transform.center.lng),a.aL(this.transform.center.lat)],textLabelPlaneMatrix:De,labelToScreenMatrix:Be,clippingData:ot,scale:ne,textPixelRatio:re,holdingForFade:S.holdingForFade(),collisionBoxArray:Z,partiallyEvaluatedTextSize:a.bj(L.textSizeData,this.transform.zoom,pt),partiallyEvaluatedIconSize:a.bj(L.iconSizeData,this.transform.zoom,ut),collisionGroup:this.collisionGroups.get(L.sourceID),latestFeatureIndex:S.latestFeatureIndex};if(E)for(const _t of L.sortKeyRanges){const{sortKey:jt,symbolInstanceStart:Nt,symbolInstanceEnd:lr}=_t;d.push({sortKey:jt,symbolInstanceStart:Nt,symbolInstanceEnd:lr,parameters:st})}else d.push({symbolInstanceStart:0,symbolInstanceEnd:L.symbolInstances.length,parameters:st})}attemptAnchorPlacement(d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re,Me,je,Xe){const{textOffset0:$e,textOffset1:Ke,crossTileID:De}=le,Be=[$e,Ke],Ge=Ml(d,L,B,Be,U),ot=this.collisionIndex.placeCollisionBox(_e,U,g,S,E,R,Yf(Ge.x,Ge.y,W,Z,this.transform.angle),ce,ne,re,ie.predicate);if(Me){const Je=_e.getSymbolInstanceIconSize(Xe,this.transform.zoom,le.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(_e,Je,Me,S,E,R,Yf(Ge.x,Ge.y,W,Z,this.transform.angle),ce,ne,re,ie.predicate).box.length===0)return}if(ot.box.length>0){let Je;return this.prevPlacement&&this.prevPlacement.variableOffsets[De]&&this.prevPlacement.placements[De]&&this.prevPlacement.placements[De].text&&(Je=this.prevPlacement.variableOffsets[De].anchor),this.variableOffsets[De]={textOffset:Be,width:L,height:B,anchor:d,textScale:U,prevAnchor:Je},this.markUsedJustification(_e,d,le,Re),_e.allowVerticalPlacement&&(this.markUsedOrientation(_e,Re,le),this.placedOrientations[De]=Re),{shift:Ge,placedGlyphBoxes:ot}}}placeLayerBucketPart(d,g,S,E,R=1){const{bucket:L,layout:B,paint:U,posMatrix:W,textLabelPlaneMatrix:Z,labelToScreenMatrix:ne,clippingData:re,textPixelRatio:ie,mercatorCenter:ce,invMatrix:le,holdingForFade:be,collisionBoxArray:_e,partiallyEvaluatedTextSize:Re,partiallyEvaluatedIconSize:Me,collisionGroup:je,latestFeatureIndex:Xe}=d.parameters,$e=B.get("text-optional"),Ke=B.get("icon-optional"),De=B.get("text-allow-overlap"),Be=B.get("icon-allow-overlap"),Ge=B.get("text-rotation-alignment")==="map",ot=B.get("icon-rotation-alignment")==="map",Je=B.get("text-pitch-alignment")==="map",St=U.get("symbol-z-offset"),pt=B.get("symbol-elevation-reference")==="sea",Ot=B.get("symbol-placement"),[Ut,ut]=B.get("text-size-scale-range"),[st,_t]=B.get("icon-size-scale-range"),jt=a.aC(R,Ut,ut),Nt=a.aC(R,st,_t),lr=B.get("text-variable-anchor"),Jt=Ge&&Ot!=="point",er=ot&&Ot!=="point",zt=lr&&L.hasTextData(),Pr=L.hasIconTextFit()&&zt&&L.hasIconData();this.transform.setProjection(L.projection);const Fr=zt||Jt,br=er||Pr;let Nr=De&&(Be||!L.hasIconData()||Ke),Jr=Be&&(De||!L.hasTextData()||$e);const dn=!St.isConstant();!L.collisionArrays&&_e&&L.deserializeCollisionBoxes(_e),S&&E&&L.updateCollisionDebugBuffers(this.transform.zoom,_e,jt,Nt);const on=(Kr,jn,ln)=>{const{crossTileID:ts,numVerticalGlyphVertices:Cs}=Kr;let li=null;if(re&&re.dynamicFilterNeedsFeature||dn){const Vs=this.retainedQueryData[L.bucketInstanceId],Ys=Xe.loadFeature({featureIndex:Kr.featureIndex,bucketIndex:Vs.bucketIndex,sourceLayerIndex:Vs.sourceLayerIndex,layoutVertexArrayOffset:0}),js=Ys.properties?Ys.properties.worldview:null;if(L.localizable&&L.worldview&&typeof js=="string")if(js==="all")Ys.properties.$localized=!0;else{if(!js.split(",").includes(L.worldview))return;Ys.properties.$localized=!0,Ys.properties.worldview=L.worldview}li=re&&re.needGeometry?a.bD(Ys,!0):Ys}if(re&&!(0,re.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:L.worldview},li,this.retainedQueryData[L.bucketInstanceId].tileID.canonical,new a.P(Kr.tileAnchorX,Kr.tileAnchorY),this.transform.calculateDistanceTileData(re.unwrappedTileID)))return this.placements[ts]=new zh(!1,!1,!1,!0),void g.add(ts);const Fs=St.evaluate(li,{});if((Kr.zOffset||0)+(Fs||0)>0&&this.frontCutoffStart>0){const Vs=2*this.frontCutoffStart-1,Ys=[Kr.tileAnchorX,Kr.tileAnchorY,0,1],js=a.aE(a.bE(),Ys,W);if(js[1]/js[3]{Vs.tileID=this.retainedQueryData[L.bucketInstanceId].tileID;const Ys=this.transform.elevation;Vs.elevation=pt?Fs:Fs+a.bu.getAtTileOffset(Vs.tileID,new a.P(Vs.tileAnchorX,Vs.tileAnchorY),Ys,Sa),Vs.elevation+=Kr.zOffset},kc=ln.textBox;if(kc){io(kc);const Vs=js=>{let qi=a.bk.horizontal;if(L.allowVerticalPlacement&&!js&&this.prevPlacement){const Qo=this.prevPlacement.placedOrientations[ts];Qo&&(this.placedOrientations[ts]=Qo,qi=Qo,this.markUsedOrientation(L,qi,Kr))}return qi},Ys=(js,qi)=>{if(L.allowVerticalPlacement&&Cs>0&&ln.verticalTextBox){for(const Qo of L.writingModes)if(Qo===a.bk.vertical?(hn=qi(),si=hn):hn=js(),hn&&hn.box&&hn.box.length)break}else hn=js()};if(lr){let js=lr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[ts]){const Ti=this.prevPlacement.variableOffsets[ts];js.indexOf(Ti.anchor)>0&&(js=js.filter(Ac=>Ac!==Ti.anchor),js.unshift(Ti.anchor))}const qi=(Ti,Ac,sm)=>{const Fp=L.getSymbolInstanceTextSize(Re,Kr,this.transform.zoom,jn),Bp=(Ti.x2-Ti.x1)*Fp+2*Ti.padding,Ty=(Ti.y2-Ti.y1)*Fp+2*Ti.padding,Zh=Kr.hasIconTextFit&&!Be?Ac:null;Zh&&io(Zh);let sh={box:[],offscreen:!1,occluded:!1};const jy=De?2*js.length:js.length;for(let Ql=0;Ql=js.length,Kr,jn,L,sm,Zh,Re,Me);if(im&&(sh=im.placedGlyphBoxes,sh&&sh.box&&sh.box.length)){ds=!0,hs=im.shift;break}}return sh};Ys(()=>qi(kc,ln.iconBox,a.bk.horizontal),()=>{const Ti=ln.verticalTextBox;return Ti&&io(Ti),L.allowVerticalPlacement&&!(hn&&hn.box&&hn.box.length)&&Cs>0&&Ti?qi(Ti,ln.verticalIconBox,a.bk.vertical):{box:null,offscreen:null,occluded:null}}),hn&&(ds=hn.box,bn=hn.offscreen,Bs=hn.occluded);const Qo=Vs(!(!hn||!hn.box));if(!ds&&this.prevPlacement){const Ti=this.prevPlacement.variableOffsets[ts];Ti&&(this.variableOffsets[ts]=Ti,this.markUsedJustification(L,Ti.anchor,Kr,Qo))}}else{const js=(qi,Qo)=>{const Ti=L.getSymbolInstanceTextSize(Re,Kr,this.transform.zoom,jn),Ac=this.collisionIndex.placeCollisionBox(L,Ti,qi,ce,le,Fr,new a.P(0,0),De,ie,W,je.predicate);return Ac&&Ac.box&&Ac.box.length&&(this.markUsedOrientation(L,Qo,Kr),this.placedOrientations[ts]=Qo),Ac};Ys(()=>js(kc,a.bk.horizontal),()=>{const qi=ln.verticalTextBox;return L.allowVerticalPlacement&&Cs>0&&qi?(io(qi),js(qi,a.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Vs(!!(hn&&hn.box&&hn.box.length))}}if(Is=hn,ds=Is&&Is.box&&Is.box.length>0,bn=Is&&Is.offscreen,Bs=Is&&Is.occluded,Kr.useRuntimeCollisionCircles){const Vs=Kr.centerJustifiedTextSymbolIndex>=0?Kr.centerJustifiedTextSymbolIndex:Kr.verticalPlacedTextSymbolIndex,Ys=L.text.placedSymbolArray.get(Vs),js=a.bl(L.textSizeData,Re,Ys),qi=B.get("text-padding");Yi=this.collisionIndex.placeCollisionCircles(L,De,Ys,Vs,L.lineVertexArray,L.glyphOffsetArray,js,W,Z,ne,S,Je,je.predicate,Kr.collisionCircleDiameter*js/a.by,qi,this.retainedQueryData[L.bucketInstanceId].tileID),ds=De||Yi.circles.length>0&&!Yi.collisionDetected,bn=bn&&Yi.offscreen,Bs=Yi.occluded}if(ln.iconFeatureIndex&&(Do=ln.iconFeatureIndex),ln.iconBox){const Vs=Ys=>{io(Ys);const js=Kr.hasIconTextFit&&hs?Yf(hs.x,hs.y,Ge,Je,this.transform.angle):new a.P(0,0),qi=L.getSymbolInstanceIconSize(Me,this.transform.zoom,Kr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(L,qi,Ys,ce,le,br,js,Be,ie,W,je.predicate)};si&&si.box&&si.box.length&&ln.verticalIconBox?(Mn=Vs(ln.verticalIconBox),_n=Mn.box.length>0):(Mn=Vs(ln.iconBox),_n=Mn.box.length>0),bn=bn&&Mn.offscreen,mi=Mn.occluded}const ys=$e||Kr.numHorizontalGlyphVertices===0&&Cs===0,Qc=Ke||Kr.numIconVertices===0;if(ys||Qc?Qc?ys||(_n=_n&&ds):ds=_n&&ds:_n=ds=_n&&ds,ds&&Is&&Is.box&&this.collisionIndex.insertCollisionBox(Is.box,B.get("text-ignore-placement"),L.bucketInstanceId,si&&si.box&&ha?ha:Ms,je.ID),_n&&Mn&&this.collisionIndex.insertCollisionBox(Mn.box,B.get("icon-ignore-placement"),L.bucketInstanceId,Do,je.ID),Yi&&(ds&&this.collisionIndex.insertCollisionCircles(Yi.circles,B.get("text-ignore-placement"),L.bucketInstanceId,Ms,je.ID),S)){const Vs=L.bucketInstanceId;let Ys=this.collisionCircleArrays[Vs];Ys===void 0&&(Ys=this.collisionCircleArrays[Vs]=new Ur);for(let js=0;js=0;--jn){const ln=Kr[jn];on(L.symbolInstances.get(ln),ln,L.collisionArrays[ln])}L.hasAnyZOffset&&a.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 Kr=L.getSortedIndexesByZOffset();for(let jn=0;jn=0&&(d.text.placedSymbolArray.get(R).crossTileID=ne>=0&&R!==ne?0:W),L>=0&&(d.text.placedSymbolArray.get(L).crossTileID=ne>=0&&L!==ne?0:W),B>=0&&(d.text.placedSymbolArray.get(B).crossTileID=ne>=0&&B!==ne?0:W),U>=0&&(d.text.placedSymbolArray.get(U).crossTileID=ne>=0&&U!==ne?0:W)}markUsedOrientation(d,g,S){const E=g===a.bk.horizontal||g===a.bk.horizontalOnly?g:0,R=g===a.bk.vertical?g:0,{leftJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:B,rightJustifiedTextSymbolIndex:U,verticalPlacedTextSymbolIndex:W}=S,Z=d.text.placedSymbolArray;L>=0&&(Z.get(L).placedOrientation=E),B>=0&&(Z.get(B).placedOrientation=E),U>=0&&(Z.get(U).placedOrientation=E),W>=0&&(Z.get(W).placedOrientation=R)}commit(d){this.commitTime=d,this.zoomAtLastRecencyCheck=this.transform.zoom;const g=this.prevPlacement;let S=!1;this.prevZoomAdjustment=g?g.zoomAdjustment(this.transform.zoom):0;const E=g?g.symbolFadeChange(d):1,R=g?g.opacities:{},L=g?g.variableOffsets:{},B=g?g.placedOrientations:{};for(const U in this.placements){const W=this.placements[U],Z=R[U];Z?(this.opacities[U]=new _p(Z,E,W.text,W.icon,null,W.clipped),S=S||W.text!==Z.text.placed||W.icon!==Z.icon.placed):(this.opacities[U]=new _p(null,E,W.text,W.icon,W.skipFade,W.clipped),S=S||W.text||W.icon)}for(const U in R){const W=R[U];if(!this.opacities[U]){const Z=new _p(W,E,!1,!1);Z.isHidden()||(this.opacities[U]=Z,S=S||W.text.placed||W.icon.placed)}}for(const U in L)this.variableOffsets[U]||!this.opacities[U]||this.opacities[U].isHidden()||(this.variableOffsets[U]=L[U]);for(const U in B)this.placedOrientations[U]||!this.opacities[U]||this.opacities[U].isHidden()||(this.placedOrientations[U]=B[U]);S?this.lastPlacementChangeTime=d:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=g?g.lastPlacementChangeTime:d)}updateLayerOpacities(d,g,S,E){E&&(this.lastReplacementSourceUpdateTime=E.updateTime);const R=new Set;for(const L of g){const B=L.getBucket(d);B&&L.latestFeatureIndex&&d.fqid===B.layerIds[0]&&(this.updateBucketOpacities(B,R,L,L.collisionBoxArray,S,E,L.tileID,d.scope),B.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(B,L.tileID),B.elevationType==="road"&&B.updateRoadElevation(L.tileID.canonical),B.updateZOffset())}}updateBucketOpacities(d,g,S,E,R,L,B,U){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 W=d.layers[0].layout,Z=d.layers[0].paint,ne=!!d.layers[0].dynamicFilter(),re=new _p(null,0,!1,!1,!0),ie=W.get("text-allow-overlap"),ce=W.get("icon-allow-overlap"),le=W.get("text-variable-anchor"),be=W.get("text-rotation-alignment")==="map",_e=W.get("text-pitch-alignment")==="map",Re=Z.get("symbol-z-offset"),Me=W.get("symbol-elevation-reference")==="sea",je=!Re.isConstant(),Xe=new _p(null,0,ie&&(ce||!d.hasIconData()||W.get("icon-optional")),ce&&(ie||!d.hasTextData()||W.get("text-optional")),!0);!d.collisionArrays&&E&&(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData())&&d.deserializeCollisionBoxes(E);const $e=(De,Be,Ge)=>{for(let ot=0;ot0||ot>0,lr=St>0,Jt=this.placedOrientations[Je],er=Jt===a.bk.vertical,zt=Jt===a.bk.horizontal||Jt===a.bk.horizontalOnly;!Nt&&!lr||jt.isHidden()||Ke++;let Pr=!1;if((Nt||lr)&&L)for(const Fr of d.activeReplacements){if(a.bz(Fr,R,a.bA.Symbol,U)||Fr.min.x>pt||pt>Fr.max.x||Fr.min.y>Ot||Ot>Fr.max.y)continue;const br=a.bB(pt,Ot,B.canonical,Fr.footprintTileId.canonical);if(Pr=a.bC(br,Fr.footprint),Pr)break}if(Pr&&this.collisionIndex.markSymbolAsClipped(d.bucketInstanceId,Be.featureIndex),Nt){const Fr=Pr?Uh:sy(jt.text);$e(d.text,Ge,er?Uh:Fr),$e(d.text,ot,zt?Uh:Fr);const br=jt.text.isHidden(),{leftJustifiedTextSymbolIndex:Nr,centerJustifiedTextSymbolIndex:Jr,rightJustifiedTextSymbolIndex:dn,verticalPlacedTextSymbolIndex:on}=Be,Tn=d.text.placedSymbolArray,Kr=br||er?1:0;Nr>=0&&(Tn.get(Nr).hidden=Kr),Jr>=0&&(Tn.get(Jr).hidden=Kr),dn>=0&&(Tn.get(dn).hidden=Kr),on>=0&&(Tn.get(on).hidden=br||zt?1:0);const jn=this.variableOffsets[Je];jn&&this.markUsedJustification(d,jn.anchor,Be,Jt);const ln=this.placedOrientations[Je];ln&&(this.markUsedJustification(d,"left",Be,ln),this.markUsedOrientation(d,ln,Be))}if(lr){const Fr=Pr?Uh:sy(jt.icon),{placedIconSymbolIndex:br,verticalPlacedIconSymbolIndex:Nr}=Be,Jr=d.icon.placedSymbolArray,dn=jt.icon.isHidden()?1:0;br>=0&&($e(d.icon,St,er?Uh:Fr),Jr.get(br).hidden=dn),Nr>=0&&($e(d.icon,Be.numVerticalIconVertices,zt?Uh:Fr),Jr.get(Nr).hidden=dn)}if(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData()){const Fr=d.collisionArrays[De];if(Fr){let br=new a.P(0,0),Nr=!0;if(Fr.textBox||Fr.verticalTextBox){if(le){const dn=this.variableOffsets[Je];dn?(br=Ml(dn.anchor,dn.width,dn.height,dn.textOffset,dn.textScale),be&&br._rotate(_e?this.transform.angle:-this.transform.angle)):Nr=!1}ne&&(Nr=!jt.clipped),Fr.textBox&&bp(d.textCollisionBox.collisionVertexArray,jt.text.placed,!Nr||er,st,Me,br.x,br.y),Fr.verticalTextBox&&bp(d.textCollisionBox.collisionVertexArray,jt.text.placed,!Nr||zt,st,Me,br.x,br.y)}const Jr=Nr&&!!(!zt&&Fr.verticalIconBox);Fr.iconBox&&bp(d.iconCollisionBox.collisionVertexArray,jt.icon.placed,Jr,st,Me,Be.hasIconTextFit?br.x:0,Be.hasIconTextFit?br.y:0),Fr.verticalIconBox&&bp(d.iconCollisionBox.collisionVertexArray,jt.icon.placed,!Jr,st,Me,Be.hasIconTextFit?br.x:0,Be.hasIconTextFit?br.y:0)}}}if(d.fullyClipped=Ke===0,d.sortFeatures(this.transform.angle),this.retainedQueryData[d.bucketInstanceId]&&(this.retainedQueryData[d.bucketInstanceId].featureSortOrder=d.featureSortOrder),d.hasTextData()&&d.text.opacityVertexBuffer&&d.text.opacityVertexBuffer.updateData(d.text.opacityVertexArray),d.hasIconData()&&d.icon.opacityVertexBuffer&&d.icon.opacityVertexBuffer.updateData(d.icon.opacityVertexArray),d.hasIconCollisionBoxData()&&d.iconCollisionBox.collisionVertexBuffer&&d.iconCollisionBox.collisionVertexBuffer.updateData(d.iconCollisionBox.collisionVertexArray),d.hasTextCollisionBoxData()&&d.textCollisionBox.collisionVertexBuffer&&d.textCollisionBox.collisionVertexBuffer.updateData(d.textCollisionBox.collisionVertexArray),d.bucketInstanceId in this.collisionCircleArrays){const De=this.collisionCircleArrays[d.bucketInstanceId];d.placementInvProjMatrix=De.invProjMatrix,d.placementViewportMatrix=De.viewportMatrix,d.collisionCircleArray=De.circles,delete this.collisionCircleArrays[d.bucketInstanceId]}}symbolFadeChange(d){return this.fadeDuration===0?1:(d-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(d){return Math.max(0,(this.transform.zoom-d)/1.5)}hasTransitions(d){return d-this.lastPlacementChangeTimed}isStale(){return this.stale}setStale(){this.stale=!0}}function bp(_,d,g,S,E,R,L){_.emplaceBack(d?1:0,g?1:0,R||0,L||0,S,E?1:0),_.emplaceBack(d?1:0,g?1:0,R||0,L||0,S,E?1:0),_.emplaceBack(d?1:0,g?1:0,R||0,L||0,S,E?1:0),_.emplaceBack(d?1:0,g?1:0,R||0,L||0,S,E?1:0)}const B0=Math.pow(2,25),$0=Math.pow(2,24),fl=Math.pow(2,17),ba=Math.pow(2,16),iB=Math.pow(2,9),z0=Math.pow(2,8),Yj=Math.pow(2,1);function sy(_){if(_.opacity===0&&!_.placed)return 0;if(_.opacity===1&&_.placed)return 4294967295;const d=_.placed?1:0,g=Math.floor(127*_.opacity);return g*B0+d*$0+g*fl+d*ba+g*iB+d*z0+g*Yj+d}const Uh=0;class Zj{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,S,E,R,L){const B=this._bucketParts;for(;this._currentTileIndexU.sortKey-W.sortKey));this._currentPartIndex{const U=a.o.now()-L;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&U>2};for(;this._currentPlacementIndex>=0;){const U=g[d[this._currentPlacementIndex]],W=this.placement.collisionIndex.transform.zoom;if(U.type==="symbol"&&U.visibility!=="none"&&(!U.minzoom||U.minzoom<=W)&&(!U.maxzoom||U.maxzoom>W)){const Z=U,ne=Z.layout.get("symbol-z-elevate"),re=Z.layout.get("symbol-sort-key").constantOr(1)!==void 0,ie=Z.layout.get("symbol-z-order"),ce=ie==="viewport-y"||ie==="auto"&&!(ie!=="viewport-y"&&re),le=Z.layout.get("text-allow-overlap")||Z.layout.get("icon-allow-overlap")||Z.layout.get("text-ignore-placement")||Z.layout.get("icon-ignore-placement"),be=ce&&le,_e=this._inProgressLayer=this._inProgressLayer||new Zj(Z),Re=a.F(U.source,U.scope);if(_e.continuePlacement(ne||be?E[Re]:S[Re],this.placement,this._showCollisionBoxes,U,B,R))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(d){return this.placement.commit(d),this.placement}}const Zo=512/a.an/2;class Mu{constructor(d,g,S){this.tileID=d,this.bucketInstanceId=S,this.index=new a.bI(g.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const E=d.canonical.x*a.an,R=d.canonical.y*a.an;for(let L=0;Lbe-_e);for(const be of le){const _e=this.crossTileIDs[be];if(this.keys[be]===Z&&!S.has(_e)){S.add(_e),W.crossTileID=_e;break}}}}}class Xl{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class kI{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(d){const g=Math.round((d-this.lng)/360);if(g!==0)for(const S in this.indexes){const E=this.indexes[S],R={};for(const L in E){const B=E[L];B.tileID=B.tileID.unwrapTo(B.tileID.wrap+g),R[B.tileID.key]=B}this.indexes[S]=R}this.lng=d}addBucket(d,g,S){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 R=0;Rd.overscaledZ)for(const B in L){const U=L[B];U.tileID.isChildOf(d)&&U.findMatches(g.symbolInstances,d,E)}else{const B=L[d.scaledTo(Number(R)).key];B&&B.findMatches(g.symbolInstances,d,E)}}for(let R=0;R{g[S]=!0});for(const S in this.layerIndexes)g[S]||delete this.layerIndexes[S]}}const Vi=771;class tn{constructor(d,g,S,E){this.blendFunction=d,this.blendColor=g.toNonPremultipliedRenderColor(null),this.mask=S,this.blendEquation=E}}tn.Replace=[1,0,1,0],tn.disabled=new tn(tn.Replace,a.aq.transparent,[!1,!1,!1,!1]),tn.unblended=new tn(tn.Replace,a.aq.transparent,[!0,!0,!0,!0]),tn.alphaBlended=new tn([1,Vi,1,Vi],a.aq.transparent,[!0,!0,!0,!0]),tn.alphaBlendedNonPremultiplied=new tn([770,Vi,770,Vi],a.aq.transparent,[!0,!0,!0,!0]),tn.multiply=new tn([774,0,774,0],a.aq.transparent,[!0,!0,!0,!0]),tn.multiplyAccumulateAlpha=new tn([774,0,1,Vi],a.aq.transparent,[!0,!0,!0,!0]),tn.additive=new tn([1,1,1,1],a.aq.transparent,[!0,!0,!0,!0]);class Mr{constructor(d,g,S){this.func=d,this.mask=g,this.range=S}}Mr.ReadOnly=!1,Mr.ReadWrite=!0,Mr.disabled=new Mr(519,Mr.ReadOnly,[0,1]);const da=7680;class an{constructor(d,g,S,E,R,L){this.test=d,this.ref=g,this.mask=S,this.fail=E,this.depthFail=R,this.pass=L}}an.disabled=new an({func:519,mask:0},0,0,da,da,da);const Wc=1029,wp=2305;class Zr{constructor(d,g,S){this.enable=d,this.mode=g,this.frontFace=S}}function V0(_,d){const g=a.bO(_,3);a.bR(_,d),a.bW(_,3,g)}function Mb(_,d){const g=a.bL([]);return a.bM(g,g,-d),a.bN(g,g,-_),g}function Db(_,d){const g=[_[0],_[1],0],S=[d[0],d[1],0];if(a.ai(g)>=1e-15){const L=a.ay([],g);a.bJ(S,L,a.bi(S,L)),d[0]=S[0],d[1]=S[1]}const E=a.bh([],d,_);if(a.bK(E)<1e-15)return null;const R=Math.atan2(-E[1],E[0]);return Mb(Math.atan2(Math.sqrt(_[0]*_[0]+_[1]*_[1]),-_[2]),R)}Zr.disabled=new Zr(!1,Wc,wp),Zr.backCCW=new Zr(!0,Wc,wp),Zr.backCW=new Zr(!0,Wc,2304),Zr.frontCW=new Zr(!0,1028,2304),Zr.frontCCW=new Zr(!0,1028,wp);class q0{constructor(d,g){this.position=d,this.orientation=g}get position(){return this._position}set position(d){if(d){const g=d instanceof a.ag?d:new a.ag(d[0],d[1],d[2]);this._renderWorldCopies&&(g.x=a.bs(g.x,0,1)),this._position=g}else this._position=null}lookAtPoint(d,g,S){if(this.orientation=null,!this.position)return;const E=this.position,R=S||(this._elevation?this._elevation.getAtPointOrZero(a.ag.fromLngLat(d)):0),L=a.ag.fromLngLat(d,R),B=[L.x-E.x,L.y-E.y,L.z-E.z];g||(g=[0,0,1]),g[2]=Math.abs(g[2]),this.orientation=Db(B,g)}setPitchBearing(d,g){this.orientation=Mb(a.ap(d),a.ap(-g))}}class G0{constructor(d,g){this._transform=a.b9([]),this.orientation=g,this.position=d}get mercatorPosition(){const d=this.position;return new a.ag(d[0],d[1],d[2])}get position(){const d=a.bO(this._transform,3);return[d[0],d[1],d[2]]}set position(d){var g;d&&a.bW(this._transform,3,[(g=d)[0],g[1],g[2],1])}get orientation(){return this._orientation}set orientation(d){this._orientation=d||a.bL([]),d&&V0(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=Mb(d,g),V0(this._transform,this._orientation)}forward(){const d=a.bO(this._transform,2);return[-d[0],-d[1],-d[2]]}up(){const d=a.bO(this._transform,1);return[-d[0],-d[1],-d[2]]}right(){const d=a.bO(this._transform,0);return[d[0],d[1],d[2]]}getCameraToWorld(d,g){const S=new Float64Array(16);return a.b7(S,this.getWorldToCamera(d,g)),S}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(d,g,S){const E=this.position;a.bJ(E,E,-d);const R=new Float64Array(16);return a.bP(R,[S,S,S]),a.bx(R,R,E),R[10]*=g,R}getWorldToCamera(d,g){const S=new Float64Array(16),E=new Float64Array(4),R=this.position;return a.bQ(E,this._orientation),a.bJ(R,R,-d),a.bR(S,E),a.bx(S,S,R),S[1]*=-1,S[5]*=-1,S[9]*=-1,S[13]*=-1,S[8]*=g,S[9]*=g,S[10]*=g,S[11]*=g,S}getCameraToClipPerspective(d,g,S,E){const R=new Float64Array(16);return a.bS(R,d,g,S,E),R}getCameraToClipOrthographic(d,g,S,E,R,L){const B=new Float64Array(16);return a.bT(B,d,g,S,E,R,L),B}getDistanceToElevation(d,g=!1){const S=d===0?0:a.bU(d,g?a.bV(this.position[1]):this.position[1]),E=this.forward();return(S-this.position[2])/E[2]}clone(){return new G0([...this.position],[...this.orientation])}}const aB=(_,d)=>({u_matrix:_,u_ground_shadow_factor:d});class hd{constructor(d=0,g=0,S=0,E=0){if(isNaN(d)||d<0||isNaN(g)||g<0||isNaN(S)||S<0||isNaN(E)||E<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=S,this.right=E}interpolate(d,g,S){return g.top!=null&&d.top!=null&&(this.top=a.am(d.top,g.top,S)),g.bottom!=null&&d.bottom!=null&&(this.bottom=a.am(d.bottom,g.bottom,S)),g.left!=null&&d.left!=null&&(this.left=a.am(d.left,g.left,S)),g.right!=null&&d.right!=null&&(this.right=a.am(d.right,g.right,S)),this}getCenter(d,g){const S=a.aC((this.left+d-this.right)/2,0,d),E=a.aC((this.top+g-this.bottom)/2,0,g);return new a.P(S,E)}equals(d){return this.top===d.top&&this.bottom===d.bottom&&this.left===d.left&&this.right===d.right}clone(){return new hd(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Sp=15;class H0{constructor(d,g,S,E,R,L,B){this.tileSize=512,this._renderWorldCopies=R===void 0||R,this._minZoom=d||0,this._maxZoom=g||22,this._minPitch=S??0,this._maxPitch=E??60,this.setProjection(L),this.setMaxBounds(B),this.width=0,this.height=0,this._center=new a.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 hd,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new G0,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 H0(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 S=this._elevation;g||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&S.exaggeration()&&this._centerAltitudeValidForExaggeration!==S.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*S.exaggeration(),this._centerAltitudeValidForExaggeration=S.exaggeration()):(this._centerAltitude=d||0,this._centerAltitudeValidForExaggeration=S.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]],S=this.horizonLineFromTop();let E=0,R=0;for(let L=0;L{const be=a.ck(re,ne,ie,ce,le);U.has(be)||(R.push(new a.aR(ne,re,ie,ce,le)),U.add(be))};for(let ne=0;nere.canonical.z)continue;const ie=re.canonical,ce=re.overscaledZ,le=re.wrap,be=1<0,Me=ie.y+10,Xe=re.wrap-(Re?0:1),$e=re.wrap+(_e?0:1),Ke=Re?ie.x-1:be-1,De=_e?ie.x+1:0;if(L)S[0]<0?(W(ce,$e,ie.z,De,ie.y),S[1]<0&&Me&&(W(ce,le,ie.z,ie.x,ie.y+1),W(ce,$e,ie.z,De,ie.y+1)),S[1]>0&&je&&(W(ce,le,ie.z,ie.x,ie.y-1),W(ce,$e,ie.z,De,ie.y-1))):S[0]>0?(W(ce,Xe,ie.z,Ke,ie.y),S[1]<0&&Me&&(W(ce,le,ie.z,ie.x,ie.y+1),W(ce,Xe,ie.z,Ke,ie.y+1)),S[1]>0&&je&&(W(ce,le,ie.z,ie.x,ie.y-1),W(ce,Xe,ie.z,Ke,ie.y-1))):S[1]<0&&Me?W(ce,le,ie.z,ie.x,ie.y+1):je&&W(ce,le,ie.z,ie.x,ie.y-1);else{const Be=re.visibleQuadrants;1&Be&&(W(ce,Xe,ie.z,Ke,ie.y),je&&(W(ce,le,ie.z,ie.x,ie.y-1),W(ce,Xe,ie.z,Ke,ie.y-1))),2&Be&&(W(ce,$e,ie.z,De,ie.y),je&&(W(ce,le,ie.z,ie.x,ie.y-1),W(ce,$e,ie.z,De,ie.y-1))),4&Be&&(W(ce,Xe,ie.z,Ke,ie.y),Me&&(W(ce,le,ie.z,ie.x,ie.y+1),W(ce,Xe,ie.z,Ke,ie.y+1))),8&Be&&(W(ce,$e,ie.z,De,ie.y),Me&&(W(ce,le,ie.z,ie.x,ie.y+1),W(ce,$e,ie.z,De,ie.y+1)))}}const Z=[];for(const ne of R)R.some(re=>ne.isChildOf(re))||Z.push(ne);if(R=Z.filter(ne=>!d.some(re=>!!(ne.overscaledZ{const _e=be.canonical.x+.5-ie[0],Re=be.canonical.y+.5-ie[1];return _e*_e+Re*Re{const Ke=a.ck(Me,Re,je,Xe,$e);R.has(Ke)||(E.push(new a.aR(Re,Me,je,Xe,$e)),R.add(Ke))},B=d.reduce((Re,Me)=>Math.max(Re,Me.overscaledZ),S),U=1<{const je=Math.floor(Re[0]),Xe=Math.floor(Re[1]),$e=(Re[0]-je)*a.an,Ke=(Re[1]-Xe)*a.an,De=Math.floor(Me[0]),Be=Math.floor(Me[1]),Ge=(Me[0]-De)*a.an,ot=(Me[1]-Be)*a.an;for(let Je=-1;Je<=1;Je++){const St=je+Je;if(!(St<0||St>=U)){Z.x=$e-Je*a.an,ne.x=Ge-(St-De)*a.an;for(let pt=-1;pt<=1;pt++){const Ot=Xe+pt;Z.y=Ke-pt*a.an,ne.y=ot-(Ot-Be)*a.an,a.cI(Z,ne,W)&&L(B,0,S,St,Ot)}}}},ie=g.points,ce=ie[a.c9],le=ie[a.ca],be=this._projectToGround(ce,ie[a.cb]),_e=this._projectToGround(le,ie[a.cc]);return re(ce,be),re(le,_e),E}_projectToGround(d,g){return a.cd(a.ce(),d,g,d[2]/(d[2]-g[2]))}_projectToZ(d,g,S){const E=d[2]-g[2];return Math.abs(E)<1e-6?a.cf(d):a.cd(a.ce(),d,g,(d[2]-S)/E)}extendTileCoverForTunnels(d,g,S,E){if(S<18)return[];const R=g.points,L=R[a.cg],B=R[a.ch],U=R[a.ci],W=R[a.cj];if(U[2]>=0&&W[2]>=0||L[2]<=0||B[2]<=0)return[];const Z=U[2]<0?this._projectToZ(L,U,0):U,ne=W[2]<0?this._projectToZ(B,W,0):W,re=-E,ie=U[2]3&&(le.length=3),le}_findExtensionTilesInQuad(d,g,S,E){const R=[],L=new Set;for(const De of d)L.add(De.key);const B=d.reduce((De,Be)=>Math.max(De,Be.overscaledZ),g),U=1<{const Ge=De.canonical.x+.5-$e,ot=De.canonical.y+.5-Ke,Je=Be.canonical.x+.5-$e,St=Be.canonical.y+.5-Ke;return Ge*Ge+ot*ot-(Je*Je+St*St)||De.canonical.x-Be.canonical.x||De.canonical.y-Be.canonical.y}),R}coveringTiles(d){let g=this.coveringZoomLevel(d);const S=g,E=this.elevation&&this.elevation.exaggeration(),R=E&&!d.isTerrainDEM,L=this.projection.name==="mercator";if(d.minzoom!==void 0&&gd.maxzoom&&(g=d.maxzoom);const B=this.locationCoordinate(this.center),U=this.center.lat,W=1<{const jt=new a.ag(st.x+25e-6,st.y,st.z),Nt=new a.ag(st.x,st.y+25e-6,st.z),lr=st.toLngLat(),Jt=jt.toLngLat(),er=Nt.toLngLat(),zt=this.locationCoordinate(lr),Pr=this.locationCoordinate(Jt),Fr=this.locationCoordinate(er),br=Math.hypot(Pr.x-zt.x,Pr.y-zt.y),Nr=Math.hypot(Fr.x-zt.x,Fr.y-zt.y);return Math.sqrt(br*Nr)*Ke/25e-6},Be=st=>{const _t=Xe,jt=$e;return{aabb:a.cp(this,W,0,0,0,st,jt,_t,this.projection),zoom:0,x:0,y:0,minZ:jt,maxZ:_t,wrap:st,fullyVisible:!1}},Ge=[];let ot=[];const Je=g,St=d.reparseOverscaled?S:g,pt=(be-this._centerAltitude)*le,Ot=st=>{if(!this._elevation||!st.tileID||!L)return;const _t=this._elevation.getMinMaxForTile(st.tileID),jt=st.aabb;_t?(jt.min[2]=_t.min,jt.max[2]=_t.max,jt.center[2]=(jt.min[2]+jt.max[2])/2):(st.shouldSplit=ut(st),st.shouldSplit||(jt.min[2]=jt.max[2]=jt.center[2]=this._centerAltitude))},Ut=(st,_t)=>{if(.707*_t{if(st.zoom=.9)return!0}else if(R&&(Nt=st.aabb.distanceZ(_e)*le),this.projection.isReprojectedInTileSpace&&S<=5){const Nr=Math.pow(2,st.zoom),Jr=De(new a.ag((st.x+.5)/Nr,(st.y+.5)/Nr));lr=Jr>.85?1:Jr}if(!L&&!ne){const Nr=Math.sqrt(_t*_t+jt*jt+Nt*Nt);let Jr=(1<0;){const st=Ge.pop(),_t=st.x,jt=st.y;let Nt=st.fullyVisible;const lr=()=>this.projection.name==="globe"&&(st.y===0||st.y===(1<Jt)continue;let er=0;if(!Nt){let br=Re?st.aabb.intersectsPrecise(ie):st.aabb.intersectsPreciseFlat(ie);if(br===0&&lr()){const Nr=new a.cn(st.zoom,_t,jt);br=a.co(this,W,Nr,!0).intersectsPrecise(ie)}if(br===0)continue;if(d.calculateQuadrantVisibility)if(ie.containsPoint(st.aabb.center))er=15;else for(let Nr=0;Nr<4;Nr++)st.aabb.quadrant(Nr).intersects(ie)!==0&&(er|=1<>1),Pr={aabb:L?st.aabb.quadrant(Jt):a.cp(this,W,st.zoom+1,er,zt,st.wrap,st.minZ,st.maxZ,this.projection),zoom:st.zoom+1,x:er,y:zt,wrap:st.wrap,fullyVisible:Nt,tileID:void 0,shouldSplit:void 0,minZ:st.minZ,maxZ:st.maxZ};R&&!ne&&(Pr.tileID=new a.aR(st.zoom+1===Je?St:st.zoom+1,st.wrap,st.zoom+1,er,zt),Ot(Pr)),Ge.push(Pr)}}if(this.fogCullDistSq){const st=this.fogCullDistSq,_t=this.horizonLineFromTop();ot=ot.filter(jt=>{const Nt=[0,0,0,1],lr=[a.an,a.an,0,1],Jt=this.calculateFogTileMatrix(jt.tileID.toUnwrapped());a.aE(Nt,Nt,Jt),a.aE(lr,lr,Jt);const er=a.cq([],Nt,lr),zt=a.cr([],Nt,lr),Pr=a.cK(er,zt);if(Pr===0)return!0;let Fr=!1;const br=this._elevation;if(br&&Pr>st&&_t!==0){const Nr=this.calculateProjMatrix(jt.tileID.toUnwrapped());let Jr;d.isTerrainDEM||(Jr=br.getMinMaxForTile(jt.tileID)),Jr||(Jr={min:$e,max:Xe});const dn=a.cs(this.rotation),on=[dn[0]*a.an,dn[1]*a.an,Jr.max];a.ah(on,on,Nr),Fr=(1-on[1])*this.height*.5<_t}return Prst.distanceSq-_t.distanceSq).map(st=>st.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=a.aC(d.lat,-a.ct,a.ct),S=this.projection.project(d.lng,g);return new a.P(S.x*this.worldSize,S.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/a.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(d,g){let S,E;const R=this.centerPoint;if(this.projection.name==="globe"){const B=this.worldSize;S=(g.x-R.x)/B,E=(g.y-R.y)/B}else{const B=this.pointCoordinate(g),U=this.pointCoordinate(R);S=B.x-U.x,E=B.y-U.y}const L=this.locationCoordinate(d);this.setLocation(new a.ag(L.x-S,L.y-E))}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 S=g?a.bU(g,d.lat):void 0,E=this.projection.project(d.lng,d.lat);return new a.ag(E.x,E.y,S)}coordinateLocation(d){return this.projection.unproject(d.x,d.y)}pointRayIntersection(d,g){const S=g??this._centerAltitude,E=[d.x,d.y,0,1],R=[d.x,d.y,1,1];a.aE(E,E,this.pixelMatrixInverse),a.aE(R,R,this.pixelMatrixInverse);const L=R[3];a.cu(E,E,1/E[3]),a.cu(R,R,1/L);const B=E[2],U=R[2];return{p0:E,p1:R,t:B===U?0:(S-B)/(U-B)}}screenPointToMercatorRay(d){const g=[d.x,d.y,0,1],S=[d.x,d.y,1,1];return a.aE(g,g,this.pixelMatrixInverse),a.aE(S,S,this.pixelMatrixInverse),a.cu(g,g,1/g[3]),a.cu(S,S,1/S[3]),g[2]=a.bU(g[2],this._center.lat)*this.worldSize,S[2]=a.bU(S[2],this._center.lat)*this.worldSize,a.cu(g,g,1/this.worldSize),a.cu(S,S,1/this.worldSize),new a.az([g[0],g[1],g[2]],a.ay([],a.ax([],S,g)))}rayIntersectionCoordinate(d){const{p0:g,p1:S,t:E}=d,R=a.bU(g[2],this._center.lat),L=a.bU(S[2],this._center.lat);return new a.ag(a.am(g[0],S[0],E)/this.worldSize,a.am(g[1],S[1],E)/this.worldSize,a.am(R,L,E))}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 S=this.projection.pointCoordinate3D(this,d.x,d.y);if(S)return new a.ag(S[0],S[1],S[2]);let E=0,R=this.horizonLineFromTop();if(d.y>R)return this.pointCoordinate(d,g);const L=.02*R,B=d.clone();for(let U=0;U<10&&R-E>L;U++){B.y=a.am(E,R,.66);const W=this.projection.pointCoordinate3D(this,B.x,B.y);W?(R=B.y,S=W):E=B.y}return S?new a.ag(S[0],S[1],S[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>=a.cv)return!this.isPointAboveHorizon(d);const g=this.pointCoordinate(d);return g.y>=0&&g.y<=1}_coordinatePoint(d,g){const S=g&&this.elevation?this.elevation.getAtPointOrZero(d,this._centerAltitude):this._centerAltitude,E=[d.x*this.worldSize,d.y*this.worldSize,S+d.toAltitude(),1];return a.aE(E,E,this.pixelMatrix),E[3]>0?new a.P(E[0]/E[3],E[1]/E[3]):new a.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:d,left:g}=this._edgeInsets,S=this.height-this._edgeInsets.bottom,E=this.width-this._edgeInsets.right,R=this.pointLocation3D(new a.P(g,d)),L=this.pointLocation3D(new a.P(E,d)),B=this.pointLocation3D(new a.P(E,S)),U=this.pointLocation3D(new a.P(g,S));let W=Math.min(R.lng,L.lng,B.lng,U.lng),Z=Math.max(R.lng,L.lng,B.lng,U.lng),ne=Math.min(R.lat,L.lat,B.lat,U.lat),re=Math.max(R.lat,L.lat,B.lat,U.lat);const ie=Math.pow(2,-this.zoom)/16*270,ce=this.projection.name==="globe"?1:4,le=(be,_e,Re,Me,je)=>{const Xe=(be+Re)/2,$e=(_e+Me)/2,Ke=new a.P(Xe,$e),{lng:De,lat:Be}=this.pointLocation3D(Ke),Ge=Math.max(0,W-De,ne-Be,De-Z,Be-re);W=Math.min(W,De),Z=Math.max(Z,De),ne=Math.min(ne,Be),re=Math.max(re,Be),(jeie)&&(le(be,_e,Xe,$e,je+1),le(Xe,$e,Re,Me,je+1))};if(le(g,d,E,d,1),le(E,d,E,S,1),le(E,S,g,S,1),le(g,S,g,d,1),this.projection.name==="globe"){const[be,_e]=a.cw(this);be?(re=90,Z=180,W=-180):_e&&(ne=-90,Z=180,W=-180)}return new a.aK(new a.aU(W,ne),new a.aU(Z,re))}_getBoundsRectangular(d,g){const{top:S,left:E}=this._edgeInsets,R=this.height-this._edgeInsets.bottom,L=this.width-this._edgeInsets.right,B=new a.P(E,S),U=new a.P(L,S),W=new a.P(L,R),Z=new a.P(E,R);let ne=this.pointCoordinate(B,d),re=this.pointCoordinate(U,d);const ie=this.pointCoordinate(W,g),ce=this.pointCoordinate(Z,g),le=(be,_e)=>(_e.y-be.y)/(_e.x-be.x);return ne.y>1&&re.y>=0?ne=new a.ag((1-ce.y)/le(ce,ne)+ce.x,1):ne.y<0&&re.y<=1&&(ne=new a.ag(-ce.y/le(ce,ne)+ce.x,0)),re.y>1&&ne.y>=0?re=new a.ag((1-ie.y)/le(ie,re)+ie.x,1):re.y<0&&ne.y<=1&&(re=new a.ag(-ie.y/le(ie,re)+ie.x,0)),new a.aK().extend(this.coordinateLocation(ne)).extend(this.coordinateLocation(re)).extend(this.coordinateLocation(ce)).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((S,E)=>{if(E.dem){const R=E.dem.tree;S.min=Math.min(S.min,R.minimums[0]),S.max=Math.max(S.max,R.maximums[0])}return S},{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,S=this.height/2-g*(1-this._horizonShift);return d?Math.max(0,S):S}getMaxBounds(){return this.maxBounds}setMaxBounds(d){this.maxBounds=d,this.minLat=-a.ct,this.maxLat=a.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.maxLngne&&(B=ne-W),ne-Zie&&(L=ie-U),ie-re{for(let ut=0;ut<16;ut++)St[ut]=a.am(pt[ut],Ot[ut],Ut)})(B,B,U,a.cL(this.pitch>=Sp?1:this.pitch/Sp))}else B=U;const W=a.cz([],U,L);let Z=a.cz([],B,L);if(this.projection.isReprojectedInTileSpace){const Be=this.locationCoordinate(this.center),Ge=a.b9([]);a.bx(Ge,Ge,[Be.x*this.worldSize,Be.y*this.worldSize,0]),a.aD(Ge,Ge,a.cA(this)),a.bx(Ge,Ge,[-Be.x*this.worldSize,-Be.y*this.worldSize,0]),a.aD(Z,Z,Ge),a.aD(W,W,Ge),this.inverseAdjustmentMatrix=a.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=a.cC([],Z,[this.worldSize,this.worldSize,this.worldSize/R,1]),this.projMatrix=Z,this.invProjMatrix=a.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=a.cz([],Be,L)}else this.expandedFarZProjMatrix=this.projMatrix;const ne=a.b7([],B);this.frustumCorners=a.cD.fromInvProjectionMatrix(ne,this.horizonLineFromTop(),this.height),this.cameraFrustum=a.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!g);const re=new Float32Array(16);a.b9(re),a.cC(re,re,[1,-1,1]),a.cE(re,re,this._pitch),a.ba(re,re,this.angle);const ie=a.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=a.b8(ie);const ce=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;ie[8]=2*-d.x/this.width,ie[9]=2*(d.y+ce)/this.height,this.skyboxMatrix=a.aD(re,ie,re);const le=this.point,be=le.x,_e=le.y,Re=this.width%2/2,Me=this.height%2/2,je=Math.cos(this.angle),Xe=Math.sin(this.angle),$e=be-Math.round(be)+je*Re+Xe*Me,Ke=_e-Math.round(_e)+je*Me+Xe*Re,De=new Float64Array(Z);if(a.bx(De,De,[$e>.5?$e-1:$e,Ke>.5?Ke-1:Ke,0]),this.alignedProjMatrix=De,Z=a.bb(),a.cC(Z,Z,[this.width/2,-this.height/2,1]),a.bx(Z,Z,[1,-1,0]),this.labelPlaneMatrix=Z,Z=a.bb(),a.cC(Z,Z,[1,-1,1]),a.bx(Z,Z,[-1,-1,0]),a.cC(Z,Z,[2/this.width,2/this.height,1]),this.glCoordMatrix=Z,this.pixelMatrix=a.aD(new Float64Array(16),this.labelPlaneMatrix,W),this._calcFogMatrices(),this._distanceTileDataCache={},Z=a.b7(new Float64Array(16),this.pixelMatrix),!Z)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Z,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=a.cF(this);const Be=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=a.ah(Be,Be,L),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Z;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const d=this.cameraWorldSizeForFog,g=this.cameraPixelsPerMeter,S=this._camera.position,E=1/this.height/this._pixelsPerMercatorPixel,R=[d,d,g];a.bJ(R,R,E),a.bJ(S,S,-1),a.cG(S,S,R);const L=a.bb();a.bx(L,L,S),a.cC(L,L,R),this.mercatorFogMatrix=L,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(d,g,E)}_computeCameraPosition(d){const g=(d=d||this.pixelsPerMeter)/this.pixelsPerMeter,S=this._camera.forward(),E=this.point,R=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*g-d/this.worldSize*this._centerAltitude;return[E.x/this.worldSize-S[0]*R,E.y/this.worldSize-S[1]*R,d/this.worldSize*this._centerAltitude-S[2]*R]}_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),S=this._camera.position[2],E=d[2];let R=1;this.projection.wrap&&(this.center=this.center.wrap()),E>0&&(R=Math.min((g-S)/E,1)),this._camera.position=a.bg([],this._camera.position,d,R),this._updateStateFromCamera()}_updateStateFromCamera(){const d=this._camera.position,g=this._camera.forward(),{pitch:S,bearing:E}=this._camera.getPitchBearing(),R=a.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,L=this._mercatorZfromZoom(this._maxZoom)*Math.cos(a.ap(this._maxPitch)),B=Math.max((d[2]-R)/Math.cos(S),L),U=this._zoomFromMercatorZ(B);a.bg(d,d,g,B),this._pitch=a.aC(S,a.ap(this.minPitch),a.ap(this.maxPitch)),this.angle=a.bs(E,-Math.PI,Math.PI),this._setZoom(a.aC(U,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new a.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,S=a.cv,E=0,R=1/0;for(;S-g>1e-6&&S>g;){const L=g+.5*(S-g),B=this.tileSize*Math.pow(2,L),U=this.getCameraToCenterDistance(this.projection,L,B),W=this.scaleZoom(U/(Math.max(0,d)*this.tileSize)),Z=Math.abs(L-W);ZW||re.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+a.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new a.P(0,0),new a.P(this.width,this.height))}zoomDeltaToMovement(d,g){const S=a.ai(a.ax([],this._camera.position,d)),E=this._zoomFromMercatorZ(S)+g;return S-this._mercatorZfromZoom(E)}getCameraPoint(){if(this.projection.name==="globe"){const d=function([g,S,E],R){const L=[g,S,E,1];a.aE(L,L,R);const B=L[3]=Math.max(L[3],1e-6);return L[0]/=B,L[1]/=B,L[2]/=B,L}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new a.P(d[0],d[1])}{const d=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new a.P(0,d))}}getCameraToCenterDistance(d,g=this.zoom,S=this.worldSize){const E=a.cy(d,g,this.width,this.height,1024),R=d.pixelSpaceConversion(this.center.lat,S,E);let L=.5/Math.tan(.5*this._fov)*this.height*R;return this.isOrthographic&&(L=a.am(1,L,a.cL(this.pitch>=Sp?1:this.pitch/Sp))),L}getWorldToCameraMatrix(){const d=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&a.aD(d,d,this.globeMatrix),d}getFrustum(d){return a.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,d,this.projection.zAxisUnit==="meters")}}const Ya=(_,d)=>{if(d>0&&_.terrain&&a.w("Cutoff is currently disabled on terrain"),d<=0||_.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const g=_.transform,S=g.pitch,E=g.isLODDisabled(!1)?60:30;if(S0,uniformValues:{u_cutoff_params:[g._nearZ,g._farZ,(Z-g._nearZ)/R,(Z-re-g._nearZ)/R]}}},Zf=2048;class Ob{constructor(d,g){this.aabb=d,this.lastCascade=g}}class AI{add(d,g){const S=this.receivers[d.key];S!==void 0?(S.aabb.min[0]=Math.min(S.aabb.min[0],g.min[0]),S.aabb.min[1]=Math.min(S.aabb.min[1],g.min[1]),S.aabb.min[2]=Math.min(S.aabb.min[2],g.min[2]),S.aabb.max[0]=Math.max(S.aabb.max[0],g.max[0]),S.aabb.max[1]=Math.max(S.aabb.max[1],g.max[1]),S.aabb.max[2]=Math.max(S.aabb.max[2],g.max[2])):this.receivers[d.key]=new Ob(g,null)}clear(){this.receivers={}}get(d){return this.receivers[d.key]}computeRequiredCascades(d,g,S){const E=a.cU.fromPoints(d.points);let R=0;for(const L in this.receivers){const B=this.receivers[L];if(!B||!E.intersectsAabb(B.aabb))continue;B.aabb.min=E.closestPoint(B.aabb.min),B.aabb.max=E.closestPoint(B.aabb.max);const U=B.aabb.getCorners();for(let W=0;W1||re[1]<-1||re[1]>1){Z=!1;break}}if(B.lastCascade=W,R=Math.max(R,W),Z)break}}return R+1}}class W0{constructor(d){this.painter=d,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new AI,this._depthMode=new Mr(d.context.gl.LEQUAL,Mr.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 S=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!g||!g.properties)return;const E=g.properties.get("shadow-intensity"),R=g.properties.get("shadow-draw-before-layer");if(!g.shadowsEnabled()||E<=0)return;let L=-1,B=0;for(const _e of S.style.order){const Re=S.style._mergedLayers[_e];Re.hasShadowPass()&&!Re.isHidden(d.zoom)&&(L=B),!R||R!==_e&&R!==Re.slot||(this._drawShadowAfterLayer=B>0?B-1:0),B+=1}if(this._enabled=L>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=L);const U=S.context,W=Zf,Z=Zf;if(this._cascades.length===0||Zf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let _e=0;_e<2;++_e){const Re=U.gl,Me=U.createFramebuffer(W,Z,0,"texture"),je=new a.T(U,{width:W,height:Z,data:null},Re.DEPTH_COMPONENT16);Me.depthAttachment.set(je.texture),this._cascades.push({framebuffer:Me,texture:je,matrix:[],far:0,boundingSphereRadius:0,frustum:new a.cl,scale:0})}}this.shadowDirection=NI(g);let ne=0;if(d.elevation){const _e=d.elevation,Re=[1e4,-1e4];_e.visibleDemTiles.filter(Me=>Me.dem).forEach(Me=>{const je=Me.dem.tree;Re[0]=Math.min(Re[0],je.minimums[0]),Re[1]=Math.max(Re[1],je.maximums[0])}),Re[0]!==1e4&&(ne=(Re[1]-Re[0])*_e.exaggeration())}const re=1.5*d.cameraToCenterDistance,ie=3*re,ce=new Float64Array(16);for(let _e=0;_e=0)return{};const R=function(U,W,Z){const ne=Z/(1<0&&(a.cT(R[1],R[1],[E[0]*L,0,0]),a.cT(R[2],R[2],[E[0]*L,0,0])),E[1]<0?(a.cT(R[0],R[0],[0,E[1]*L,0]),a.cT(R[1],R[1],[0,E[1]*L,0])):E[1]>0&&(a.cT(R[2],R[2],[0,E[1]*L,0]),a.cT(R[3],R[3],[0,E[1]*L,0]));const B={};return B.vertices=R,B.planes=[Fb(R[1],R[0],R[4]),Fb(R[2],R[1],R[5]),Fb(R[3],R[2],R[6]),Fb(R[0],R[3],R[7])],B}addShadowReceiver(d,g,S){this._receivers.add(d,a.cU.fromTileIdAndHeight(d,g,S))}getMaxCascadeForTile(d){const g=this._receivers.get(d);return g&&g.lastCascade?g.lastCascade:0}}function Fb(_,d,g){const S=a.ax([],g,d),E=a.ax([],_,d),R=a.bh([],S,E),L=a.ai(R);return L===0?[0,0,1,0]:(a.bJ(R,R,1/L),[R[0],R[1],R[2],-a.bi(R,d)])}function NI(_){const d=_.properties.get("direction"),g=a.cP(d.x,d.y,d.z);g[2]=a.aC(g[2],0,75);const S=a.cR([g[0],g[1],g[2]]);return a.cQ(S.x,S.y,S.z)}function fd(_,d,g){const S=d.properties.get("color-use-theme")==="none",E=d.properties.get("color"),R=d.properties.get("intensity"),L=d.properties.get("direction"),B=[L.x,L.y,L.z],U=g.properties.get("color-use-theme")==="none",W=g.properties.get("color"),Z=g.properties.get("intensity"),ne=Math.max(a.bi([0,0,1],B),0),re=[0,0,0];a.bJ(re,W.toPremultipliedRenderColor(U?null:_.getLut(d.scope)).toArray01Linear().slice(0,3),Z);const ie=[0,0,0];return a.bJ(ie,E.toPremultipliedRenderColor(S?null:_.getLut(g.scope)).toArray01Linear().slice(0,3),ne*R),a.cW([re[0]>0?re[0]/(re[0]+ie[0]):0,re[1]>0?re[1]/(re[1]+ie[1]):0,re[2]>0?re[2]/(re[2]+ie[2]):0])}function K0(_,d,g,S,E,R){const L=_.zoom,B=_.scale,U=_.worldSize,W=1/U,Z=_.aspect,ne=Math.sqrt(1+Z*Z)*Math.tan(.5*_.fovX),re=ne*ne,ie=S-g,ce=S+g;let le,be;re>ie/ce?(le=S,be=S*ne):(le=.5*ce*(1+re),be=.5*Math.sqrt(ie*ie+2*(S*S+g*g)*re+ce*ce*re*re));const _e=_.projection.pixelsPerMeter(_.center.lat,U),Re=_._camera.getCameraToWorldMercator(),Me=[0,0,-le*W];a.ah(Me,Me,Re);let je=be*W;const Xe=function(Nt){return Nt[0]/=B,Nt[1]/=B,Nt[2]=a.bU(Nt[2],_._center.lat),Nt},$e=_._edgeInsets;if(!($e.left===0&&$e.top===0&&$e.right===0&&$e.bottom===0||$e.left===$e.right&&$e.top===$e.bottom)){const Nt=_._camera.getWorldToCamera(_.worldSize,_.projection.zAxisUnit==="meters"?_e:1),lr=_._camera.getCameraToClipPerspective(_._fov,_.width/_.height,g,S);lr[8]=2*-_.centerOffset.x/_.width,lr[9]=2*_.centerOffset.y/_.height;const Jt=new Float64Array(16);a.cz(Jt,lr,Nt);const er=new Float64Array(16);a.b7(er,Jt);const zt=a.cl.fromInvProjectionMatrix(er,U,L,!0);for(const Pr of zt.points){const Fr=Xe(Pr);je=Math.max(je,a.bK(a.cV([],Me,Fr)))}}je*=E/(E-1);const Ke=Math.acos(d[2]),De=Math.atan2(-d[0],-d[1]),Be=new G0;Be.position=Me,Be.setPitchBearing(Ke,De);const Ge=Be.getWorldToCamera(U,_e),ot=je*U,Je=Math.min(_._mercatorZfromZoom(17)*U*-2,-2*ot),St=Be.getCameraToClipOrthographic(-ot,ot,-ot,ot,Je,(ot+R*_e)/d[2]),pt=new Float64Array(16);a.aD(pt,St,Ge);const Ot=a.cQ(Math.floor(1e6*Me[0])/1e6*U,Math.floor(1e6*Me[1])/1e6*U,0),Ut=.5*E,ut=[0,0,0];a.ah(ut,Ot,pt),a.bJ(ut,ut,Ut);const st=[Math.floor(ut[0]),Math.floor(ut[1]),Math.floor(ut[2])],_t=[0,0,0];a.ax(_t,ut,st),a.bJ(_t,_t,-1/Ut);const jt=new Float64Array(16);return a.b9(jt),a.bx(jt,jt,_t),a.aD(pt,jt,pt),[pt,ot]}class oB extends a.E{constructor(d){super(),this.requestManager=d,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(d,g){return a.cX(this.requestManager.transformRequest(g,a.R.Model).url).then(S=>{const E=a.cY(S),R=new a.cZ(d,g,void 0,void 0,E);return R.computeBoundsAndApplyParent(),R}).catch(S=>{if(S&&S.status===404)return null;this.fire(new a.B(new Error(`Could not load model ${d} from ${g}: ${S.message}`)))})}load(d,g,S={forceReload:!1}){this.models[g]||(this.models[g]={});const E=Object.keys(d),R=[],L=[];for(const B of E){const U=d[B];this.hasURLBeenRequested(U)&&!S.forceReload||(this.modelByURL[U]={modelId:B,scope:g},R.push(this.loadModel(B,U)),L.push(B)),this.models[g][B]||(this.models[g][B]={model:null,numReferences:1})}this.numModelsLoading[g]=(this.numModelsLoading[g]||0)+L.length,Promise.allSettled(R).then(B=>{for(let U=0;U{this.fire(new a.B(new Error(`Could not load models: ${B.message}`)))})}isLoaded(){for(const d in this.numModelsLoading)if(this.numModelsLoading[d]>0)return!1;return!0}hasModel(d,g,S={exactIdMatch:!1}){return!!(S.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,S){this.models[S]||(this.models[S]={}),this.modelUris[S]||(this.modelUris[S]={});const E=this.requestManager.normalizeModelURL(g);if((this.hasModel(d,S,{exactIdMatch:!0})||this.hasModelBeenAdded(d,S))&&this.modelUris[S][d]===E)this.models[S][d].numReferences++;else if(this.hasURLBeenRequested(E)){const{scope:R,modelId:L}=this.modelByURL[E];this.models[R][L].numReferences++}else this.modelUris[S][d]=E,this.load({[d]:this.modelUris[S][d]},S)}addModelURLs(d,g){this.models[g]||(this.models[g]={}),this.modelUris[g]||(this.modelUris[g]={});const S=this.modelUris[g];for(const E in d)S[E]=this.requestManager.normalizeModelURL(d[E])}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 S={};for(const E of d)this.hasModel(E,g,{exactIdMatch:!0})||this.hasURLBeenRequested(E)?this.models[g][E].numReferences++:this.modelUris[g][E]&&!this.hasURLBeenRequested(E)?S[E]=this.modelUris[g][E]:!this.hasURLBeenRequested(E)&&a.c_(E,!1)&&(this.modelUris[g][E]=this.requestManager.normalizeModelURL(E),S[E]=this.modelUris[g][E]);this.load(S,g)}hasURLBeenRequested(d){return this.modelByURL[d]!==void 0}removeModel(d,g,S=!1,E=!1){if(this.models[g]&&this.models[g][d]&&(this.models[g][d].numReferences--,this.models[g][d].numReferences===0||E)){const R=this.modelUris[g][d];S||delete this.modelUris[g][d],delete this.modelByURL[R];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 S=this.models[d][g].model;delete this.models[d][g],S&&S.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 S in this.models[g])this.models[g][S].model&&this.models[g][S].model.upload(d.context)}}const Xj=a.a8.colorTheme,ay=new a.ab({data:new a.ac(Xj.data)});function CI(_){if(!_.metadata||!_.metadata.content_area)return;const d=a.o.devicePixelRatio,{left:g,top:S,width:E,height:R}=_.metadata.content_area,L=g*d,B=S*d;return[L,B,L+E*d,B+R*d]}function Y0(_){if(_)return _.map(([d,g])=>[d*a.o.devicePixelRatio,g*a.o.devicePixelRatio])}class Qj{constructor(d,g,S){this.id=d,this.scope=g,this.sourceCache=S,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 S=this.sourceCache.getSource();if(!(S instanceof yp))return d;const E=g.map(L=>this.sourceCache.getTile(L)),R=S.getImages(E,Array.from(this.pendingRequests));for(const[L,B]of R)d.set(a.I.from({name:L,iconsetId:this.id}),B),this.pendingRequests.delete(L);for(const L of this.pendingRequests)this.missingRequests.add(L);return this.pendingRequests.clear(),d}}class Xf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(d,g,S,E,R){if(SU*this._hysteresisRatio&&(L=this._previousClosestBuildingId):W&&!L&&(L=this._previousClosestBuildingId),this._previousClosestBuildingId=L,L}_calculateDistance(d,g){if(!g.center)return Number.MAX_VALUE;const S=d.lat-g.center[1],E=d.lng-g.center[0];return S*S+E*E}_isBuildingVisible(d,g,S){if(!S)return!1;for(const E of d.floorIds){const R=d.floors[E];if(!R.geometry)continue;const L=R.geometry;if(L.type==="Polygon"){const B=this._convertRingToPoints(L.coordinates[0]);if(a.bw(B,S))return!0}else if(L.type==="MultiPolygon"){const B=this._convertMultiPolygonToPoints(L.coordinates);if(a.d0(S,B))return!0}}return!1}_convertRingToPoints(d){return d.map(g=>new a.P(g[0],g[1]))}_convertMultiPolygonToPoints(d){return d.map(g=>g.length===0?[]:g[0].map(S=>new a.P(S[0],S[1])))}}class lB extends a.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 Xf,this._initialLoadDone=!1,a.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[S,E]of Object.entries(d.buildings))if(this._buildings[S])for(const R of E.floorIds)this._buildings[S].floorIds.add(R),this._buildings[S].floors[R]?this._mergeFloors(this._buildings[S].floors[R],E.floors[R]):(this._buildings[S].floors[R]=E.floors[R],g=!0);else this._buildings[S]=E,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,S=g&&d?d[g]:void 0;if(!S)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let E=null;for(const L of S.floorIds)if(this._activeFloors&&this._activeFloors.has(L)){E=L;break}const R=Array.from(S.floorIds).map(L=>({id:L,name:S.floors[L].name,zIndex:S.floors[L].zIndex})).sort((L,B)=>B.zIndex-L.zIndex).filter((L,B,U)=>B===0||L.zIndex!==U[B-1].zIndex);return{selectedFloorId:E,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:R}}_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 S=this._closestBuildingId;this._closestBuildingId=g,this._onBuildingTransition(S,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 a.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=a.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(g,S){if(g===S)return!0;if(!g||!S||g.size!==S.size)return!1;for(const E of g)if(!S.has(E))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,S=d.height;return[d.pointLocation(new a.P(0,0)),d.pointLocation(new a.P(g,0)),d.pointLocation(new a.P(g,S)),d.pointLocation(new a.P(0,S))].map(E=>new a.P(E.lng,E.lat))}}const Tp=(_,d)=>gr(_,d&&d.filter(g=>g.identifier!=="source.canvas")),cB=a.aJ(us,["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"]),II=a.aJ(us,["setCenter","setZoom","setBearing","setPitch"]),Jj=new Set(["background","sky","slot","custom"]),Bb={version:8,layers:[],sources:{}},eE={duration:300,delay:0};class Du extends a.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({},eE),this._buildingIndex=new D0(this),this.crossTileSymbolIndex=new iy,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 Nn,this._hasDataDrivenEmissive=!1,this.indoorManager=new lB(this),this.dispatcher=g.dispatcher?g.dispatcher:new Kt(yn(),this),this.map.painter&&this.map.painter.context){const E=this.map.painter.context.maxUniformBufferBindings,R=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:E,maxUniformBlockSizeDwords:R,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}g.imageManager?this.imageManager=g.imageManager:(this.imageManager=new Gn(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=g.glyphManager?g.glyphManager:new a.d2(d._requestManager,g.localFontFamily?a.d3.all:g.localIdeographFontFamily?a.d3.ideographs:a.d3.none,g.localFontFamily||g.localIdeographFontFamily,g.useServerFontComposition),g.modelManager?this.modelManager=g.modelManager:(this.modelManager=new oB(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",a.d4()),this.dispatcher.broadcast("setConfig",a.d5());const S=this;this._rtlTextPluginCallback=Du.registerForPluginStateChange(E=>{S.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:E.pluginStatus,pluginURL:E.pluginURL},(R,L)=>{if(a.d6(R),L&&L.every(B=>B))for(const B in S._sourceCaches){const U=S._sourceCaches[B],W=U.getSource().type;W!=="vector"&&W!=="geojson"||U.reload()}})}),this.on("data",E=>{if(E.dataType!=="source"||E.sourceDataType!=="metadata")return;const R=this.getOwnSource(E.sourceId);if(R&&R.vectorLayerIds)for(const L in this._layers){const B=this._layers[L];B.source===R.id&&this._validateLayer(B)}})}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(a.e(d))return d;const g=a.d7(d);if(!g.startsWith("http"))try{return new URL(g,location.href).toString()}catch{return g}return g}return`json://${a.d8(JSON.stringify(d))}`}_diffStyle(d,g,S){this.globalId=this._getGlobalId(d);const E=(R,L)=>{try{L(null,this.setState(R,S))}catch(B){L(B,!1)}};if(typeof d=="string"){const R=this.map._requestManager.normalizeStyleURL(d),L=this.map._requestManager.transformRequest(R,a.R.Style);a.m(L,(B,U)=>{B?this.fire(new a.B(B)):U&&E(U,g)})}else typeof d=="object"&&E(d,g)}loadURL(d,g={}){this.fire(new a.C("dataloading",{dataType:"style"}));const S=typeof g.validate=="boolean"?g.validate:!a.e(d);this.globalId=this._getGlobalId(d),d=this.map._requestManager.normalizeStyleURL(d,g.accessToken),this.resolvedImports.add(d);const E=this.importsCache.get(d);if(E)return this._load(E,S);const R=this.map._requestManager.transformRequest(d,a.R.Style);this._request=a.m(R,(L,B)=>{if(this._request=null,L)this.fire(new a.B(L));else if(B)return this.importsCache.set(d,B),this._load(B,S)})}loadJSON(d,g={}){this.fire(new a.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(d),this._request=a.o.frame(()=>{this._request=null,this._load(d,g.validate!==!1)})}loadEmpty(){this.fire(new a.C("dataloading",{dataType:"style"})),this._load(Bb,!1)}_loadImports(d,g,S){if(this.importDepth>=4)return a.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const E=[];for(const R of d){const L=this._createFragmentStyle(R),B=new Promise(Z=>{L.once("style.import.load",Z),L.once("error",Z)}).then(()=>{this.mergeAll(),this.fire(new a.C("data",{dataType:"style"}))});if(E.push(B),this.resolvedImports.has(R.url)){L.loadEmpty();continue}const U=R.data||this.importsCache.get(R.url);U?(R.data?(L.fire(new a.C("dataloading",{dataType:"style"})),L.globalId=L._getGlobalId(U),queueMicrotask(()=>L._load(U,g))):L.loadJSON(U,{validate:g}),this._isInternalStyle(U)&&(L.globalId=null)):R.url?L.loadURL(R.url,{validate:g}):L.loadEmpty();const W={style:L,id:R.id,config:R.config};if(S){const Z=this.fragments.findIndex(({id:ne})=>ne===S);this.fragments=this.fragments.slice(0,Z).concat(W).concat(this.fragments.slice(Z))}else this.fragments.push(W)}return Promise.allSettled(E)}getImportGlobalIds(d=this,g=new Set){for(const S of d.fragments)S.style.globalId&&g.add(S.style.globalId),this.getImportGlobalIds(S.style,g);return[...g.values()]}_createFragmentStyle(d){const g=this.scope?a.F(d.id,this.scope):d.id;let S;const E=this._initialConfig&&this._initialConfig[g];(d.config||E)&&(S=Object.assign({},d.config,E));const R=new Du(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:S,configOptions:this.options,colorThemeOverride:d["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return R.setEventedParent(this.map,{style:R}),R}_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 R=Object.assign({},Bb,{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(R,g)}if(this.updateConfig(this._config,d.schema),g&&Tp(this,_c(d)))return;this._loaded=!0;for(const R in d.sources)this.addSource(R,d.sources[R],{validate:!1,isInitialLoad:!0});this.stylesheet=a.d9(d);const S=()=>{if(d.iconsets)for(const U in d.iconsets)this.addIconset(U,d.iconsets[U]);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 R=qj(this.stylesheet.layers);if(this._order=R.map(U=>U.id),this.stylesheet.light&&a.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 U=this.stylesheet.lights[0];this.light=new hr(U.properties,U.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new hr(this.stylesheet.light)),this._layers={};for(const U of R){const W=a.de(U,this.scope,this._styleColorTheme.lut,this.options);W.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(W.fqid),W.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(W.fqid),this._hasAppearances=this._hasAppearances||W.getAppearances().length!==0,W.setEventedParent(this,{layer:{id:W.id}}),this._layers[W.id]=W;const Z=this.getOwnLayerSourceCache(W),ne=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Z&&W.canCastShadows()&&ne&&(Z.castsShadows=!0)}if(this.glyphManager.url){const U=new Set;for(const W in this._layers){const Z=this._layers[W];if(Z.type==="symbol"&&Z.layout){const ne=Z.layout.get("text-font");ne&&ne.value&&ne.value.kind==="constant"&&U.add(ne.value.value.join(","))}}for(const W of U)this.glyphManager.prefetchRange(W,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 a.C("data",{dataType:"style"}));const B=this.isRootStyle();d.imports?this._loadImports(d.imports,g).then(()=>{this._reloadImports(),this.fire(new a.C(B?"style.load":"style.import.load"))}).catch(U=>{this.fire(new a.B(new Error("Failed to load imports",U))),this.fire(new a.C(B?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new a.C(B?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const E=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(E){const R=this._evaluateColorThemeData(E);this._loadColorTheme(R).then(()=>{S()}).catch(L=>{a.w(`Couldn't load color theme from the stylesheet: ${L}`),S()})}else this._styleColorTheme.lut=null,S()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(d=>d.style.hasAppearances())}mergeAll(){let d,g,S,E,R,L,B,U,W,Z;const ne={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(re=>{if(re.stylesheet){if(re.light!=null&&(d=re.light),re.stylesheet.lights)for(const ie of re.stylesheet.lights)ie.type==="ambient"&&re.ambientLight!=null&&(g=re.ambientLight),ie.type==="directional"&&re.directionalLight!=null&&(S=re.directionalLight);E=this._prioritizeTerrain(E,re.terrain,re.stylesheet.terrain),re.stylesheet.fog&&re.fog!=null&&(R=re.fog),re.stylesheet.snow&&re.snow!=null&&(L=re.snow),re.stylesheet.rain&&re.rain!=null&&(B=re.rain),re.stylesheet.camera!=null&&(Z=re.stylesheet.camera),re.stylesheet.projection!=null&&(U=re.stylesheet.projection),re.stylesheet.transition!=null&&(W=re.stylesheet.transition),ne[re.scope]=re._styleColorTheme}}),this.light=d,this.ambientLight=g,this.directionalLight=S,this.fog=R,this.snow=L,this.rain=B,this._styleColorThemeForScope=ne,E===null?delete this.terrain:this.terrain=E,this.camera=Z||{"camera-projection":"perspective"},this.projection=U||{name:"mercator"},this.transition=Object.assign({},eE,W),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(d){const g=S=>{for(const E of S.fragments)g(E.style);d(S)};g(this)}_prioritizeTerrain(d,g,S){const E=d&&d.drapeRenderMode===0;return S===null?g&&g.drapeRenderMode===0?g:E?d:null:g!=null&&(!d||E||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={},S={},E={};this.forEachFragmentStyle(R=>{for(const L in R._sourceCaches){const B=a.F(L,R.scope);d[B]=R._sourceCaches[L]}for(const L in R._otherSourceCaches){const B=a.F(L,R.scope);g[B]=R._otherSourceCaches[L]}for(const L in R._symbolSourceCaches){const B=a.F(L,R.scope);S[B]=R._symbolSourceCaches[L]}for(const L in R._fillExtrusionSourceCaches){const B=a.F(L,R.scope);E[B]=R._fillExtrusionSourceCaches[L]}}),this._mergedSourceCaches=d,this._mergedOtherSourceCaches=g,this._mergedSymbolSourceCaches=S,this._mergedFillExtrusionSourceCaches=E}mergeIndoor(){this.forEachFragmentStyle(d=>{if(d.stylesheet&&d.stylesheet.indoor)for(const g of Object.values(d.stylesheet.indoor)){const S=g,E=a.F(S.sourceId,d.scope);this._mergedIndoor[E]=new Set(S.sourceLayers||[])}})}mergeLayers(){const d={},g=[],S={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(L=>{for(const B of L._order){const U=L._layers[B];if(U.type==="slot"){const W=a.da(B);if(d[W])continue;d[W]=[]}U.slot&&d[U.slot]?d[U.slot].push(U):g.push(U)}}),this._mergedOrder=[];let E=-1;const R=(L=[])=>{for(const B of L)if(B.type==="slot"){const U=a.da(B.id);d[U]&&R(d[U]),this._mergedSlots.push(U)}else{const U=a.F(B.id,B.scope);this._mergedOrder.push(U),S[U]=B,B.is3D(!!this.terrain)&&(this._has3DLayers=!0,E=this._mergedOrder.length-1),B.type==="circle"&&(this._hasCircleLayers=!0),B.type==="symbol"&&(this._hasSymbolLayers=!0),B.type==="clip"&&(this._clipLayerPresent=!0)}};if(R(g),this._has3DLayers){const L={};for(let B=0;BL[B]-L[U])}this._mergedLayers=S,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,S,E){const R=Object.assign({},S);for(const B of Object.keys(Xj))R[B]===void 0&&(R[B]=Xj[B].default);const L=new a.aa(ay,g,new Map(E));return L.setTransitionOrValue(R,E),L.untransitioned().possiblyEvaluate(new a.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((S,E)=>{const R="data:image/png;base64,";if(!d||d.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void S();let L=d;L.startsWith(R)||(L=R+L);const B=a.I.from("mapbox-reserved-lut"),U=new Image;U.src=L,U.onerror=()=>{this._styleColorTheme.lutLoading=!1,E(new Error("Failed to load image data"))},U.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==g)return void S();this._styleColorTheme.lutLoading=!1;const{width:W,height:Z,data:ne}=a.o.getImageData(U);if(Z>32)return void E(new Error("The height of the image must be less than or equal to 32 pixels."));if(W!==Z*Z)return void E(new Error("The width of the image must be equal to the height squared."));this.getImage(B)&&this.removeImage(B),this.addImage(B,{data:new a.q({width:W,height:Z},ne),pixelRatio:1,sdf:!1,usvg:!1,version:0});const re=this.imageManager.getImage(B,this.scope);re?(this._styleColorTheme.lut={image:re.data,data:d},S()):E(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,S,E){let R,L,B;const U=a.o.devicePixelRatio>1?"@2x":"";let W=a.m(S.transformRequest(S.normalizeSpriteURL(g,U,".json"),a.R.SpriteJSON),(re,ie)=>{W=null,B||(B=re,R=ie,ne())}),Z=a.n(S.transformRequest(S.normalizeSpriteURL(g,U,".png"),a.R.SpriteImage),(re,ie)=>{Z=null,B||(B=re,L=ie,ne())});function ne(){if(B)E(B);else if(R&&L){const re=a.o.getImageData(L),ie={};for(const ce in R){const{width:le,height:be,x:_e,y:Re,sdf:Me,pixelRatio:je,stretchX:Xe,stretchY:$e,content:Ke}=R[ce],De=new a.q({width:le,height:be});a.q.copy(re,De,{x:_e,y:Re},{x:0,y:0},{width:le,height:be},null),ie[ce]={data:De,pixelRatio:je!==void 0?je:1,sdf:Me!==void 0&&Me,stretchX:Xe,stretchY:$e,content:Ke,usvg:!1,version:0}}E(null,ie)}}return{cancel(){W&&(W.cancel(),W=null),Z&&(Z.cancel(),Z=null)}}}(d,this.map._requestManager,(g,S)=>{if(this._spriteRequest=null,g)this.fire(new a.B(g));else if(S){const E=new Map;for(const R in S)E.set(a.I.from(R),S[R]);this.addImages(E)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new a.C("data",{dataType:"style"}))})}addIconset(d,g){if(g.type==="sprite")return void this._loadSprite(g.url);const S=this.getOwnSourceCache(g.source);if(!S)return void this.fire(new a.B(new Error(`Source "${g.source}" as specified by iconset "${d}" does not exist and cannot be used as an iconset source`)));const E=S.getSource();if(E.type!=="raster-array")return void this.fire(new a.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`)));E.partial=!1;const R=new Qj(d,this.scope,S);this.imageManager.addImageProvider(R,this.scope)}removeIconset(d){this.imageManager.removeImageProvider(d,this.scope)}_loadIconset(d){if(!a.e(d)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(d);const g=this.map._spriteFormat==="auto";var S,E;this._spriteRequest=(E=(R,L)=>{if(this._spriteRequest=null,R)g?this._loadSprite(d):this.fire(new a.B(R));else if(L){const B=new Map;for(const U in L)B.set(a.I.from(U),L[U]);this.addImages(B)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new a.C("data",{dataType:"style"}))},a.b1((S=this.map._requestManager).transformRequest(S.normalizeIconsetURL(d),a.R.Iconset),(R,L)=>{if(R)return void E(R);const B={},U=a.c$(new a.a$(L));for(const W of U.icons){const Z={version:1,pixelRatio:a.o.devicePixelRatio,content:CI(W),stretchX:W.metadata?Y0(W.metadata.stretch_x_areas):void 0,stretchY:W.metadata?Y0(W.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:W};B[W.name]=Z}E(null,B)}))}_validateLayer(d){const g=this.getOwnSource(d.source);if(!g)return;const S=d.sourceLayer;S&&(g.type==="geojson"||g.vectorLayerIds&&g.vectorLayerIds.indexOf(S)===-1)&&this.fire(new a.B(new Error(`Source layer "${S}" 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 S=this.fragments[g];return S&&S.style&&(d.data=S.style.serialize()),d})}_serializeSources(){const d={};for(const g in this._sourceCaches){const S=this._sourceCaches[g].getSource();d[S.id]||(d[S.id]=S.serialize())}return d}_serializeLayers(d){const g=[];for(const S of d){const E=this._layers[S];E&&E.type!=="custom"&&g.push(E.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 S=g._transitionablePaint._values["line-emissive-strength"];if(S&&S.value&&S.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 a.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 a.B(new Error(`The source '${d}' does not exist in the map's style.`)))}precompilePrograms(d,g){const S=this.map.painter;if(S)for(let E=d.minzoom||0;E<(d.maxzoom||25.5);E++){const R=d.getProgramIds();if(R)for(const L of R){const B=d.getDefaultProgramParams(L,g.zoom,this._styleColorTheme.lut);B&&(S.style=this,this.fog&&(S._fogVisible=!0,B.overrideFog=!0,S.getOrCreateProgram(L,B)),S._fogVisible=!1,B.overrideFog=!1,S.getOrCreateProgram(L,B),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(B.overrideRtt=!0,S.getOrCreateProgram(L,B)))}}}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 S=this._changes.isDirty();let E=!1;if(this._changes.isDirty()){const U=this._changes.getLayerUpdatesByScope();for(const W in U){const{updatedIds:Z,removedIds:ne}=U[W];(Z||ne)&&(this._updateWorkerLayers(W,Z,ne),E=!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 R={};for(const U in this._mergedSourceCaches){const W=this._mergedSourceCaches[U];R[U]=W.used,W.used=!1,W.tileCoverLift=0}const L={};for(const U of this._mergedOrder){const W=this._mergedLayers[U];if((W.visibility!=="none"||W.hasTransition())&&W.recalculate(d,this._availableImages),!W.isHidden(d.zoom)){const Z=this.getLayerSourceCache(W);Z&&(Z.used=!0,Z.tileCoverLift=Math.max(Z.tileCoverLift,W.tileCoverLift()))}if(W.type==="fill-extrusion"){const Z=a.F(W.source,W.scope);if(Z in this._mergedFillExtrusionSourceCaches){const ne=W.layout&&W.layout.get("source-max-zoom");if(ne!=null){const re=L[Z];L[Z]=re==null?ne:Math.min(re,ne)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(W,d)}):this.precompilePrograms(W,d))}this._shouldPrecompile&&(this._precompileDone=!0);for(const U in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[U].setMaxzoomOverride(L[U]!=null?L[U]:null);this.terrain&&E&&this.mergeLayers();const B=this.imageManager.getPendingImageProviders();for(const U of B)U.sourceCache.used=!0;for(const U in R){const W=this._mergedSourceCaches[U];R[U]!==W.used&&W.getSource().fire(new a.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:W.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),S&&this.fire(new a.C("data",{dataType:"style"}))}updateImageProviders(){const d=this.imageManager.getPendingImageProviders();for(const g of d){const S=g.resolvePendingRequests(),E=this.getFragmentStyle(g.scope);E&&E.addImages(S)}}_updateTilesForChangedImages(){const d={};for(const g in this._mergedSourceCaches){const S=this._mergedSourceCaches[g].getSource().scope;d[S]=d[S]||this._changes.getUpdatedImages(S),d[S].length!==0&&this._mergedSourceCaches[g].reloadTilesForDependencies(["icons","patterns"],d[S])}for(const g in d)this._changes.resetUpdatedImages(g)}_updateWorkerLayers(d,g,S){const E=this.getFragmentStyle(d);E&&this.dispatcher.broadcast("updateLayers",{layers:g?E._serializeLayers(g):[],scope:d,removedIds:S||[],options:E.options})}setState(d,g){if(this._checkLoaded(),Tp(this,_c(d)))return!1;(d=a.d9(d)).layers=qj(d.layers);const S=function(L,B){if(!L)return[{command:us.setStyle,args:[B]}];let U=[];try{if(!a.b6(L.version,B.version))return[{command:us.setStyle,args:[B]}];if(a.b6(L.center,B.center)||U.push({command:us.setCenter,args:[B.center]}),a.b6(L.zoom,B.zoom)||U.push({command:us.setZoom,args:[B.zoom]}),a.b6(L.bearing,B.bearing)||U.push({command:us.setBearing,args:[B.bearing]}),a.b6(L.pitch,B.pitch)||U.push({command:us.setPitch,args:[B.pitch]}),a.b6(L.sprite,B.sprite)||U.push({command:us.setSprite,args:[B.sprite]}),a.b6(L.glyphs,B.glyphs)||U.push({command:us.setGlyphs,args:[B.glyphs]}),a.b6(L.imports,B.imports)||function(ie=[],ce=[],le){ce=ce||[];const be=(ie=ie||[]).map(ty),_e=ce.map(ty),Re=ie.reduce(O0,{}),Me=ce.reduce(O0,{}),je=be.slice();let Xe,$e,Ke,De;for(Xe=0,$e=0;Xe{ie.source&&W[ie.source]?U.push({command:us.removeLayer,args:[ie.id]}):ne.push(ie)});let re=L.terrain;re&&W[re.source]&&(U.push({command:us.setTerrain,args:[void 0]}),re=void 0),U=U.concat(Z),a.b6(re,B.terrain)||U.push({command:us.setTerrain,args:[B.terrain]}),function(ie,ce,le){ce=ce||[];const be=(ie=ie||[]).map(ty),_e=ce.map(ty),Re=ie.reduce(O0,{}),Me=ce.reduce(O0,{}),je=be.slice(),Xe=Object.create(null);let $e,Ke,De,Be,Ge,ot,Je;for($e=0,Ke=0;$e!(L.command in II));if(S.length===0)return!1;const E=S.filter(L=>!(L.command in cB));if(E.length>0)throw new Error(`Unimplemented: ${E.map(L=>L.command).join(", ")}.`);const R=[];return S.forEach(L=>{R.push(this[L.command](...L.args))}),g&&Promise.all(R).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,S]of d.entries()){if(this.getImage(g))return this.fire(new a.B(new Error(`An image with the name "${g.name}" already exists.`)));this.imageManager.addImage(g,this.scope,S),this._changes.updateImage(g,this.scope)}return this._updateWorkerImages(),this.fire(new a.C("data",{dataType:"style"})),this}addImage(d,g){return this.getImage(d)?this.fire(new a.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 a.C("data",{dataType:"style"})),this)}updateImage(d,g,S=!1){this.imageManager.updateImage(d,this.scope,g),S&&(this._changes.updateImage(d,this.scope),this._updateWorkerImages(),this.fire(new a.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 a.C("data",{dataType:"style"})),this):this.fire(new a.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 a.C("data",{dataType:"style"})),this}addModel(d,g,S={}){return this._checkLoaded(),this._validate(Gt,`models.${d}`,g,null,S)||(this.modelManager.addModel(d,g,this.getActualScope()),this.fire(new a.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 a.C("data",{dataType:"style"})),this):this.fire(new a.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(d,g,S={}){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(hl,`sources.${d}`,g,null,S))return;this.map&&this.map._collectResourceTiming&&(g.collectResourceTiming=!0);const E=Eb(d,g,this.dispatcher,this);E.scope=this.scope,E.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(E.id),source:E.serialize(),sourceId:E.id}));const R=L=>{const B=(L===a.b4.Symbol?"symbol:":L===a.b4.FillExtrusion?"fill-extrusion:":"other:")+E.id,U=a.F(B,this.scope),W=this._sourceCaches[B]=new Pu(U,E,L);L===a.b4.Symbol?this._symbolSourceCaches[E.id]=W:L===a.b4.FillExtrusion?this._fillExtrusionSourceCaches[E.id]=W:this._otherSourceCaches[E.id]=W,W.onAdd(this.map)};R(a.b4.Other),g.type!=="vector"&&g.type!=="geojson"||(R(a.b4.Symbol),g.type==="vector"&&R(a.b4.FillExtrusion)),E.onAdd&&E.onAdd(this.map),S.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 E in this._layers)if(this._layers[E].source===d)return this.fire(new a.B(new Error(`Source "${d}" cannot be removed while layer "${E}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===d)return this.fire(new a.B(new Error(`Source "${d}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const E=Object.entries(this.stylesheet.iconsets).find(([R,L])=>L.type==="source"&&L.source===d);if(E)return this.fire(new a.B(new Error(`Source "${d}" cannot be removed while iconset "${E[0]}" is using it.`)))}const S=this.getOwnSourceCaches(d);for(const E of S){const R=a.da(E.id);delete this._sourceCaches[R],this._changes.discardSourceCacheUpdate(E.id),E.fire(new a.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:E.getSource().id})),E.setEventedParent(null),E.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 S=this.getOwnSourceCache(g);S&&d.push(S.getSource())}return d}areTilesLoaded(){const d=this._mergedSourceCaches;for(const g in d){const S=d[g]._tiles;for(const E in S){const R=S[E];if(R.state!=="loaded"&&R.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 R of d){if(this._validate(he,"lights",R))return;switch(R.type){case"ambient":if(this.ambientLight){const L=this.ambientLight;L.set(R),L.updateTransitions(g)}else this.ambientLight=new Oa(R,Lo(),this.scope,this.options);break;case"directional":if(this.directionalLight){const L=this.directionalLight;L.set(R),L.updateTransitions(g)}else this.directionalLight=new Oa(R,bc(),this.scope,this.options)}}const S=Object.assign(g,{worldview:this.map.getWorldview()}),E=new a.ae(this.z||0,S);this.ambientLight&&this.ambientLight.recalculate(E),this.directionalLight&&this.directionalLight.recalculate(E),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const d=this.directionalLight,g=this.ambientLight;if(!d||!g)return;const S=re=>.2126*(re[0]<=.03928?re[0]/12.92:Math.pow((re[0]+.055)/1.055,2.4))+.7152*(re[1]<=.03928?re[1]/12.92:Math.pow((re[1]+.055)/1.055,2.4))+.0722*(re[2]<=.03928?re[2]/12.92:Math.pow((re[2]+.055)/1.055,2.4)),E=d.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),R=d.properties.get("intensity"),L=d.properties.get("direction"),B=1-a.cP(L.x,L.y,L.z)[2]/90,U=S(E)*R*B,W=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Z=g.properties.get("intensity"),ne=S(W)*Z;return Number(((U+ne)/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(a.db(d)){const g=a.dc(d),S=this.fragments.find(({id:R})=>R===g);if(!S)return;const E=a.da(d);return S.style.getFragmentStyle(E)}{const g=this.fragments.find(({id:S})=>S===d);return g?g.style:void 0}}setFeaturesetSelectors(d){if(!d)return;const g=(S,E="")=>`${S}::${E}`;this._featuresetSelectors={};for(const S in d){const E={},R=this._featuresetSelectors[S]=[];for(const L of d[S].selectors){if(L.featureNamespace){const U=this.getOwnLayer(L.layer);if(!U){a.w(`Layer is undefined for selector: ${L.layer}`);continue}const W=g(U.source,U.sourceLayer);if(W in E&&E[W]!==L.featureNamespace){a.w(`"featureNamespace ${L.featureNamespace} of featureset ${S}'s selector is not associated to the same source, skip this selector`);continue}E[W]=L.featureNamespace}let B;if(L.properties)for(const U in L.properties){const W=a.X(L.properties[U]);W.result==="success"&&(B=B||{},B[U]=W.value)}R.push({layerId:L.layer,namespace:L.featureNamespace,properties:B,uniqueFeatureID:L._uniqueFeatureID})}}}getFeaturesetDescriptors(d){const g=this.getFragmentStyle(d);if(!g||!g.stylesheet.featuresets)return[];const S=[];for(const E in g.stylesheet.featuresets)S.push({featuresetId:E,importId:g.scope?g.scope:void 0});return S}getFeaturesetLayers(d,g){const S=this.getFragmentStyle(g),E=S.stylesheet.featuresets;if(!E||!E[d])return this.fire(new a.B(new Error(`The featureset '${d}' does not exist in the map's style and cannot be queried.`))),[];const R=[];for(const L of E[d].selectors){const B=S.getOwnLayer(L.layer);B&&R.push(B)}return R}getConfigProperty(d,g){const S=this.getFragmentStyle(d);if(!S)return null;const E=a.F(g,S.scope),R=S.options.get(E),L=R?R.value||R.default:null;return L?L.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(d,g){const S=a.F(d,g);return this._mergedIndoor[S]}setIndoorData(d,g){this.indoorManager.setIndoorData(g)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(d,g,S){const E=this.getFragmentStyle(d);if(!E)return;const R=E.stylesheet.schema;if(!R||!R[g])return;const L=a.X(S);if(L.result!=="success")return void Tp(this,L.value);const B=L.value.expression,U=a.F(g,E.scope),W=E.options.get(U);if(!W)return;let Z;const{minValue:ne,maxValue:re,stepValue:ie,type:ce,values:le}=R[g],be=a.X(R[g].default);be.result==="success"&&(Z=be.value.expression),Z?(this.options.set(U,Object.assign({},W,{value:B,default:Z,minValue:ne,maxValue:re,stepValue:ie,type:ce,values:le})),this.updateConfigDependencies(g)):this.fire(new a.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 S=g.stylesheet.schema;if(!S)return null;const E={};for(const R in S){const L=a.F(R,g.scope),B=g.options.get(L),U=B?B.value||B.default:null;E[R]=U?U.serialize():null}return E}setConfig(d,g){const S=this.getFragmentStyle(d);S&&(S.updateConfig(g,S.stylesheet.schema),this.updateConfigDependencies())}getSchema(d){const g=this.getFragmentStyle(d);return g?g.stylesheet.schema:null}setSchema(d,g){const S=this.getFragmentStyle(d);S&&(S.stylesheet.schema=g,S.updateConfig(S._config,g),this.updateConfigDependencies())}updateConfig(d,g){if(this._config=d,d||g)if(g)for(const S in g){let E,R;const L=a.X(g[S].default);if(L.result==="success"&&(E=L.value.expression),d&&d[S]!==void 0){const re=a.X(d[S]);re.result==="success"&&(R=re.value.expression)}const{minValue:B,maxValue:U,stepValue:W,type:Z,values:ne}=g[S];if(E){const re=a.F(S,this.scope);this.options.set(re,{default:E,value:R,minValue:B,maxValue:U,stepValue:W,type:Z,values:ne})}else this.fire(new a.B(new Error(`No schema defined for config option "${S}".`)))}else this.fire(new a.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(d,g=()=>!0){for(const S of d){const E=this.getLayer(S);E&&g(E)&&(E.possiblyEvaluateVisibility(),this._updateLayer(E),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 S=g._styleColorTheme.colorThemeOverride?g._styleColorTheme.colorThemeOverride:g._styleColorTheme.colorTheme;if(S){const E=g._evaluateColorThemeData(S);(!g._styleColorTheme.lut&&E!==""||g._styleColorTheme.lut&&E!==g._styleColorTheme.lut.data)&&g.setColorTheme(S)}}),this._changes.setDirty()}addLayer(d,g,S={}){this._checkLoaded();const E=d.id;if(this._layers[E])return void this.fire(new a.B(new Error(`Layer with id "${E}" already exists on this map`)));let R;if(d.type==="custom"){if(Tp(this,a.dd(d)))return;R=a.de(d,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof d.source=="object"&&(this.addSource(E,d.source),d=a.d9(d),d=Object.assign(d,{source:E})),this._validate(nt,`layers.${E}`,d,{arrayIndex:-1},S))return;R=a.de(d,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(R),R.setEventedParent(this,{layer:{id:E}})}const L=a.F(R.source,R.scope);R.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(L),R.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(L);let B=this._order.length;if(g){const ne=this._order.indexOf(g);if(ne===-1)return void this.fire(new a.B(new Error(`Layer with id "${g}" does not exist on this map.`)));R.slot&&R.slot!==this._layers[g].slot?a.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):B=ne}this._order.splice(B,0,E),this._handleLayerOrderChange(),this._layers[E]=R;const U=this.getOwnLayerSourceCache(R),W=!!this.directionalLight&&this.directionalLight.shadowsEnabled();U&&R.canCastShadows()&&W&&(U.castsShadows=!0);const Z=this._changes.getRemovedLayer(R);if(Z&&R.source&&U&&R.type!=="custom"){this._changes.discardLayerRemoval(R);const ne=a.F(R.source,R.scope);Z.type!==R.type?this._changes.updateSourceCache(ne,"clear"):(this._changes.updateSourceCache(ne,"reload"),U.pause())}this._updateLayer(R),R.onAdd&&R.onAdd(this.map),R.scope=this.scope,this.mergeLayers()}moveLayer(d,g){this._checkLoaded();const S=this._checkLayer(d);if(!S||d===g)return;const E=this._order.indexOf(d);this._order.splice(E,1);let R=this._order.length;if(g){const L=this._order.indexOf(g);if(L===-1)return void this.fire(new a.B(new Error(`Layer with id "${g}" does not exist on this map.`)));S.slot&&S.slot!==this._layers[g].slot?a.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):R=L}this._order.splice(R,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 S=this._order.indexOf(d);this._order.splice(S,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 E=this.getOwnLayerSourceCache(g);if(E&&E.castsShadows){let R=!1;for(const L in this._layers)if(this._layers[L].source===g.source&&this._layers[L].canCastShadows()){R=!0;break}E.castsShadows=R}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,S){this._checkLoaded();const E=this._checkLayer(d);E&&(E.minzoom===g&&E.maxzoom===S||(g!=null&&(E.minzoom=g),S!=null&&(E.maxzoom=S),this._updateLayer(E)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(d,g){this._checkLoaded();const S=this._checkLayer(d);S&&S.slot!==g&&(S.slot=g,this._updateLayer(S))}setFilter(d,g,S={}){this._checkLoaded();const E=this._checkLayer(d);if(E&&!a.b6(E.filter,g))return g==null?(E.filter=void 0,void this._updateLayer(E)):void(this._validate(ht,`layers.${E.id}.filter`,g,{layerType:E.type},S)||(E.filter=a.d9(g),this._updateLayer(E)))}getFilter(d){const g=this._checkLayer(d);if(g)return a.d9(g.filter)}setLayoutProperty(d,g,S,E={}){this._checkLoaded();const R=this._checkLayer(d);if(R&&!a.b6(R.getLayoutProperty(g),S)){if(S!=null&&(!E||E.validate!==!1)&&Tp(R,mt.call(_c,{key:`layers.${d}.layout.${g}`,layerType:R.type,objectKey:g,value:S,styleSpec:a.a8,style:{glyphs:!0,sprite:!0}})))return;R.setLayoutProperty(g,S),R.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(R.fqid),R.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(R.fqid),this._updateLayer(R)}}setLayerProperty(d,g,S,E={}){this._checkLoaded();const R=this._checkLayer(d);R&&(g==="appearances"?(R.setAppearances(S),this._updateLayer(R)):R.isPaintProperty(g)?this.setPaintProperty(d,g,S,E):this.setLayoutProperty(d,g,S,E))}getLayoutProperty(d,g){const S=this._checkLayer(d);if(S)return S.getLayoutProperty(g)}setPaintProperty(d,g,S,E={}){this._checkLoaded();const R=this._checkLayer(d);if(!R||a.b6(R.getPaintProperty(g),S)||S!=null&&(!E||E.validate!==!1)&&Tp(R,it.call(_c,{key:`layers.${d}.paint.${g}`,layerType:R.type,objectKey:g,value:S,styleSpec:a.a8})))return;const L=R.setPaintProperty(g,S);R.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(R.fqid),R.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(R.fqid),L&&this._updateLayer(R),this._changes.updatePaintProperties(R)}getPaintProperty(d,g){const S=this._checkLayer(d);if(S)return S.getPaintProperty(g)}setFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:U,importId:W}=d.target,Z=this.getFragmentStyle(W),ne=Z.getFeaturesetLayers(U);for(const{source:re,sourceLayer:ie}of ne)Z.setFeatureState({id:d.id,source:re,sourceLayer:ie},g)}else if("layerId"in d.target){const{layerId:U}=d.target,W=this.getLayer(U);this.setFeatureState({id:d.id,source:W.source,sourceLayer:W.sourceLayer},g)}return}const S=d.source,E=d.sourceLayer,R=this._checkSource(S);if(!R)return;const L=R.type;if(L==="geojson"&&E)return void this.fire(new a.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(L==="vector"&&!E)return void this.fire(new a.B(new Error("The sourceLayer parameter must be provided for vector source types.")));d.id===void 0&&this.fire(new a.B(new Error("The feature id parameter must be provided.")));const B=this.getOwnSourceCaches(S);for(const U of B)U.setFeatureState(E,d.id,g)}removeFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:U,importId:W}=d.target,Z=this.getFragmentStyle(W),ne=Z.getFeaturesetLayers(U);for(const{source:re,sourceLayer:ie}of ne)Z.removeFeatureState({id:d.id,source:re,sourceLayer:ie},g)}else if("layerId"in d.target){const{layerId:U}=d.target,W=this.getLayer(U);this.removeFeatureState({id:d.id,source:W.source,sourceLayer:W.sourceLayer},g)}return}const S=d.source,E=this._checkSource(S);if(!E)return;const R=E.type,L=R==="vector"?d.sourceLayer:void 0;if(R==="vector"&&!L)return void this.fire(new a.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 a.B(new Error("A feature id is required to remove its specific state property.")));const B=this.getOwnSourceCaches(S);for(const U of B)U.removeFeatureState(L,d.id,g)}getFeatureState(d){if(this._checkLoaded(),"target"in d){let R;if("featuresetId"in d.target){const{featuresetId:L,importId:B}=d.target,U=this.getFragmentStyle(B),W=U.getFeaturesetLayers(L);for(const{source:Z,sourceLayer:ne}of W){const re=U.getFeatureState({id:d.id,source:Z,sourceLayer:ne});if(re&&!R)R=re;else if(!a.b6(R,re))return void this.fire(new a.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,B=this.getLayer(L);R=this.getFeatureState({id:d.id,source:B.source,sourceLayer:B.sourceLayer})}return R}const g=d.source,S=d.sourceLayer,E=this._checkSource(g);if(E){if(E.type!=="vector"||S)return d.id===void 0&&this.fire(new a.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(g)[0].getFeatureState(S,d.id);this.fire(new a.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 a.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)},S=>S!==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),S=a.F(d.source,d.scope),E=this._changes.getUpdatedSourceCaches();d.source&&!E[S]&&g&&g.getSource().type!=="raster"&&(this._changes.updateSourceCache(S,"reload"),g.pause()),d.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(d){const g=B=>this._mergedLayers[B].is3D(!!this.terrain),S=this.order,E={},R=[];for(let B=S.length-1;B>=0;B--){const U=S[B];if(g(U)){E[U]=B;for(const W of d){const Z=W[U];if(Z)for(const ne of Z)R.push(ne)}}}R.sort((B,U)=>U.intersectionZ-B.intersectionZ);const L=[];for(let B=S.length-1;B>=0;B--){const U=S[B];if(g(U))for(let W=R.length-1;W>=0;W--){const Z=R[W].feature;if(Z.layer&&E[Z.layer.id]{if(Jj.has(Z.type))return;const ne=this.getOwnLayerSourceCache(Z),re=R[ne.id]=R[ne.id]||{sourceCache:ne,layers:{},has3DLayers:!1};Z.is3D(!!this.terrain)&&(re.has3DLayers=!0),re.layers[Z.fqid]=re.layers[Z.fqid]||{styleLayer:Z,targets:[]},re.layers[Z.fqid].targets.push({filter:E})};if(g&&g.layers){if(!Array.isArray(g.layers))return this.fire(new a.B(new Error("parameters.layers must be an Array."))),[];for(const Z of g.layers){const ne=this._layers[Z];if(!ne)return this.fire(new a.B(new Error(`The layer '${Z}' does not exist in the map's style and cannot be queried for features.`))),[];L(ne)}}else for(const Z in this._layers)L(this._layers[Z]);const B=this._queryRenderedFeatures(d,R,S),U=this._flattenAndSortRenderedFeatures(B),W=[];for(const Z of U)a.dh(Z.layer.id)===this.scope&&W.push(Z);return W}queryRenderedFeatureset(d,g,S){let E;g&&!Array.isArray(g)&&g.filter&&(this._validate(ht,"queryRenderedFeatures.filter",g.filter,null,g),E=a.dg(g.filter));const R="mock",L=[];if(g&&g.target)L.push(Object.assign({},g,{targetId:R,filter:E}));else{const Z=this.getFeaturesetDescriptors();for(const ne of Z)L.push({targetId:R,filter:E,target:ne});for(const{style:ne}of this.fragments){const re=ne.getFeaturesetDescriptors();for(const ie of re)L.push({targetId:R,filter:E,target:ie})}}const B=this.queryRenderedTargets(d,L,S),U=[],W=new Set;for(const Z of B)for(const ne of Z.variants[R])Xd(ne,Z,W)||U.push(new a.di(Z,ne));return U}queryRenderedTargets(d,g,S){const E={},R=(B,U,W,Z)=>{const ne=E[U.id]=E[U.id]||{sourceCache:U,layers:{},has3DLayers:!1};if(ne.layers[B.fqid]=ne.layers[B.fqid]||{styleLayer:B,targets:[]},B.is3D(!!this.terrain)&&(ne.has3DLayers=!0),!Z)return W.uniqueFeatureID=!1,void ne.layers[B.fqid].targets.push(W);ne.layers[B.fqid].targets.push(Object.assign({},W,{namespace:Z.namespace,properties:Z.properties,uniqueFeatureID:Z.uniqueFeatureID}))};for(const B of g)if("featuresetId"in B.target){const{featuresetId:U,importId:W}=B.target,Z=this.getFragmentStyle(W);if(!Z||!Z._featuresetSelectors)continue;const ne=Z._featuresetSelectors[U];if(!ne){this.fire(new a.B(new Error(`The featureset '${U}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const re of ne){const ie=Z.getOwnLayer(re.layerId);ie&&!Jj.has(ie.type)&&R(ie,Z.getOwnLayerSourceCache(ie),B,re)}}else if("layerId"in B.target){const{layerId:U}=B.target,W=this.getLayer(U);if(!W||Jj.has(W.type))continue;R(W,this.getLayerSourceCache(W),B)}const L=this._queryRenderedFeatures(d,E,S);return this._flattenAndSortRenderedFeatures(L)}_queryRenderedFeatures(d,g,S){const E=[],R=!!this.map._showQueryGeometry,L=wc.createFromScreenPoints(d,S);for(const B in g){const U=TI(L,g[B],this._availableImages,S,R,this.getActualScope());Object.keys(U).length&&E.push(U)}if(this.placement)for(const B in g){if(g[B].sourceCache._renderSourceType!==a.b4.Symbol)continue;const U=kb(L.screenGeometry,g[B],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(U).length&&E.push(U)}return E}querySourceFeatures(d,g){const S=g&&g.filter;S&&this._validate(ht,"querySourceFeatures.filter",S,null,g);let E=[];const R=this.getOwnSourceCaches(d);for(const L of R)E=E.concat($j(L,g));return E}addSourceType(d,g,S){return Du.getSourceType(d)?S(new Error(`A source type called "${d}" already exists.`)):(Du.setSourceType(d,g),g.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:d,url:g.workerSourceURL},S):S(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(d,g,S={}){this._checkLoaded();const E=this.light.getLight();let R=!1;for(const B in d)if(!a.b6(d[B],E[B])){R=!0;break}if(!R)return;const L=this._getTransitionParameters();this.light.setLight(d,g,S),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=a.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&a.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 S=d;const E=!("source"in d)||d.source==null;if(g===1){if(this.disableElevatedTerrain)return;if("source"in S&&typeof S.source=="object"){const B="terrain-dem-src";this.addSource(B,S.source),S=a.d9(S),S=Object.assign(S,{source:B})}const R=Object.assign({},S),L={};if(this.terrain&&E){R.source=this.terrain.get().source;const B=this.terrain?this.getFragmentStyle(this.terrain.scope):null;B&&(L.style=B.serialize())}if(this._validate(pe,"terrain",R,L))return}if(!this.terrain||this.terrain.scope!==this.scope&&!E||this.terrain&&g!==this.terrain.drapeRenderMode){if(!S)return;this._createTerrain(S,g),this.fire(new a.C("data",{dataType:"style"}))}else{const R=this.terrain,L=R.get();for(const B of Object.keys(a.a8.terrain))!S.hasOwnProperty(B)&&a.a8.terrain[B].default&&(S[B]=a.a8.terrain[B].default);for(const B in d)if(!a.b6(d[B],L[B])){R.set(d,this.options),this.stylesheet.terrain=d;const U=this._getTransitionParameters({duration:0});R.updateTransitions(U),this.fire(new a.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(d){const g=this.fog=new ks(d,this.map.transform,this.scope,this.options);this.stylesheet.fog=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}_createSnow(d){const g=this.snow=new hi(d,this.map.transform,this.scope,this.options);this.stylesheet.snow=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}_createRain(d){const g=this.rain=new Vn(d,this.map.transform,this.scope,this.options);this.stylesheet.rain=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}_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(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.fog=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}}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(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.snow=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}}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(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.rain=g.get();const S=this._getTransitionParameters({duration:0});g.updateTransitions(S)}}else this._createRain(d);this._markersNeedUpdate=!0}_reloadColorTheme(){const d=()=>{for(const E in this._layers)this._layers[E].lut=this._styleColorTheme.lut;for(const E in this._sourceCaches)this._sourceCaches[E].clearTiles()},g=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!g)return this._styleColorTheme.lut=null,void d();const S=this._evaluateColorThemeData(g);this._loadColorTheme(S).then(()=>{this.fire(new a.C("colorthemeset")),d()}).catch(E=>{a.w(`Couldn't set color theme: ${E}`)})}setColorTheme(d){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&a.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 S=this.getFragmentStyle(d);S&&(S._styleColorTheme.colorThemeOverride=g,S._reloadColorTheme())}_getTransitionParameters(d){return{now:a.o.now(),transition:Object.assign(this.transition,d)}}updateDrapeFirstLayers(){if(!this.terrain)return;const d=[],g=[];for(const S of this._mergedOrder)this.isLayerDraped(this._mergedLayers[S])?d.push(S):g.push(S);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...d),this._drapedFirstOrder.push(...g)}_createTerrain(d,g){const S=this.terrain=new qt(d,g,this.scope,this.options,this.map.getWorldview());g===1&&(this.stylesheet.terrain=d),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const E=this._getTransitionParameters({duration:0});S.updateTransitions(E)}_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,S,E,R={}){if(R&&R.validate===!1)return!1;const L=Object.assign({},this.serialize());return Tp(this,d.call(_c,Object.assign({key:g,style:L,value:S,styleSpec:a.a8},E)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),a.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 S of g)S.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 S of g)S.resume(),S.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=NI(this.directionalLight));const S=new Set,E=new Set,R=new Set;for(const L in this._mergedLayers){const B=this._mergedLayers[L];B.type==="building"?S.add(B.source):B.type==="raster"&&B.paint&&B.paint.get("raster-elevation-reference")==="ground"&&R.add(B.source),B.hasElevation()&&!E.has(B.source)&&E.add(B.source)}for(const L in this._mergedSourceCaches){const B=this._mergedSourceCaches[L],U=E.has(B._source.id);B._isRasterElevatedOverTerrain=R.has(B._source.id),S.has(B._source.id)&&(B._source.reparseOverscaled=!1),B.update(d,void 0,void 0,g,U)}}_generateCollisionBoxes(){for(const d in this._sourceCaches){const g=this._sourceCaches[d];g.resume(),g.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new a.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new U0),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(d,g,S,E,R){this.pauseablePlacement||(this.pauseablePlacement=new U0);let L=!1,B=!1;const U={},W={};for(const le of this._mergedOrder){const be=this._mergedLayers[le];if(be.type!=="symbol")continue;const _e=a.F(be.source,be.scope);let Re=U[_e];if(!Re){const je=this.getLayerSourceCache(be);if(!je)continue;const Xe=je.getRenderableIds(!0).map($e=>je.getTileByID($e));W[_e]=Xe.slice(),Re=U[_e]=Xe.sort(($e,Ke)=>Ke.tileID.overscaledZ-$e.tileID.overscaledZ||($e.tileID.isLessThan(Ke.tileID)?-1:1))}const Me=this.crossTileSymbolIndex.addLayer(be,Re,d.center.lng,d.projection);L=L||Me}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Z=!!(this.placement&&!d.equals(this.placement.transform)),ne=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!R||this.placement.lastReplacementSourceUpdateTime!==R.updateTime)),re=Z||ne||L,ie=(re||this.pauseablePlacement.isStale())&&S===0,ce=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.o.now(),d.zoom)&&S!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||ie||ce)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(d,this._mergedOrder,g,S,E,this.placement,this.fog&&d.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const le=this.map.painter.maxFrontCutoffRawStart;if(le>0){const be=180*d.pitch/Math.PI;if(be>=15){const _e=Math.min(1,Math.max(0,(be-15)/5)),Re=_e*_e*(3-2*_e);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Re)+le*Re}}}if(this.pauseablePlacement.isDone()?re&&S!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,U,W,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(a.o.now()),B=!0),L&&this.pauseablePlacement.setStale()),B||L){this._buildingIndex.onNewFrame(d.zoom);for(let le=0;leR===d.id)!==-1)return void this.fire(new a.B(new Error(`Import with id '${d.id}' already exists in the map's style.`)));if(!g)return S.push(d),this._loadImports([d],!0);const E=S.findIndex(({id:R})=>R===g);return E===-1&&this.fire(new a.B(new Error(`Import with id "${g}" does not exist on this map.`))),this.stylesheet.imports=S.slice(0,E).concat(d).concat(S.slice(E)),this._loadImports([d],!0,g)}updateImport(d,g){this._checkLoaded();const S=this.stylesheet.imports||[],E=this.getImportIndex(d);return E===-1?this:typeof g=="string"?(this.setImportUrl(d,g),this):(g.url&&g.url!==S[E].url&&this.setImportUrl(d,g.url),a.b6(g.config,S[E].config)||this.setImportConfig(d,g.config,g.data.schema),a.b6(g.data,S[E].data)||this.setImportData(d,g.data),this)}moveImport(d,g){this._checkLoaded();let S=this.stylesheet.imports||[];const E=this.getImportIndex(d);if(E===-1)return this;const R=this.getImportIndex(g);if(R===-1)return this;const L=S[E],B=this.fragments[E];return S=S.filter(({id:U})=>U!==d),this.fragments=this.fragments.filter(({id:U})=>U!==d),this.stylesheet.imports=S.slice(0,R).concat(L).concat(S.slice(R)),this.fragments=this.fragments.slice(0,R).concat(B).concat(this.fragments.slice(R)),this.mergeLayers(),this}setImportUrl(d,g){this._checkLoaded();const S=this.stylesheet.imports||[],E=this.getImportIndex(d);if(E===-1)return this;S[E].url=g;const R=this.fragments[E];return R.style=this._createFragmentStyle(S[E]),R.style.on("style.import.load",()=>this.mergeAll()),R.style.loadURL(g),this}setImportData(d,g){this._checkLoaded();const S=this.getImportIndex(d),E=this.stylesheet.imports||[];return S===-1?this:g?(this.fragments[S].style.setState(g),this._reloadImports(),this):(delete E[S].data,this.setImportUrl(d,E[S].url))}setImportConfig(d,g,S){this._checkLoaded();const E=this.getImportIndex(d),R=this.stylesheet.imports||[];if(E===-1)return this;g?R[E].config=g:delete R[E].config;const L=this.fragments[E];S&&L.style.stylesheet&&(L.style.stylesheet.schema=S);const B=L.style.stylesheet&&L.style.stylesheet.schema;return L.config=g,L.style.updateConfig(g,B),this.updateConfigDependencies(),this}removeImport(d){this._checkLoaded();const g=this.stylesheet.imports||[],S=this.getImportIndex(d);S!==-1&&(g.splice(S,1),this.fragments[S].style._remove(),this.fragments.splice(S,1),this._reloadImports())}getImportIndex(d){const g=(this.stylesheet.imports||[]).findIndex(S=>S.id===d);return g===-1&&this.fire(new a.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 S=this._mergedOtherSourceCaches[g];S&&d.push(S.getSource())}return d}getSource(d,g){const S=this.getSourceCache(d,g);return S&&S.getSource()}getLayerSource(d){const g=this.getLayerSourceCache(d);return g&&g.getSource()}getSourceCache(d,g){const S=a.F(d,g);return this._mergedOtherSourceCaches[S]}getLayerSourceCache(d){const g=a.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 S=d[g];S==="reload"?this.reloadSource(g):S==="clear"&&this.clearSource(g)}}updateLayers(d){const g=this._changes.getUpdatedPaintProperties();for(const S of g){const E=this.getLayer(S);E&&E.updateTransitions(d)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(d){this.stylesheet.glyphs=d,this.glyphManager.setURL(d)}getImages(d,g,S){this.imageManager.getImages(g.images,g.scope,S),this._updateTilesForChangedImages();const E=L=>{if(L){const B=g.images.map(U=>a.I.toString(U));L.setDependencies(g.tileID.key,g.type,B)}},R=a.F(g.source,g.scope);E(this._mergedOtherSourceCaches[R]),E(this._mergedSymbolSourceCaches[R]),g.images.some(L=>L.iconsetId)&&this.fire(new a.C("data",{dataType:"style"}))}rasterizeImages(d,g,S){this.imageManager.rasterizeImages(g,S)}checkAtlasCache(d,g,S){const E=this.imageManager.imageAtlasCache.findCachedAtlas(g.descriptor);S(null,E&&E.contentDescriptor?{iconPositions:E.iconPositions,patternPositions:E.patternPositions,sourceHash:E.contentDescriptor.hash}:null)}getGlyphs(d,g,S){this.glyphManager.getGlyphs(g.stacks,S)}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 a.B(new Error(`There is no source with ID '${d}'`))),!1):g.every(S=>S.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 S=d.type==="fill-extrusion"&&(d.sourceLayer==="building"||d.sourceLayer==="procedural_buildings"),E=d.type==="building";if(d.is3D(!!this.terrain)){if(S||E||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)}}Du.getSourceType=function(_){return jb[_]},Du.setSourceType=function(_,d){jb[_]=d},Du.registerForPluginStateChange=a.dk;var tE=` #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`,rE=` #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;}`,Qf=` #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`,Z0="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;}",nE=` #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`,sE=`#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`,oy=`#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`,ly=`#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`,iE=`#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;}`,$b=`#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`,Kc=`#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 X0=/#include\s+"([^"]+)"/g,fr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,PI=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,RI=new Set(["ifdef","ifndef","elif","if","defined"]),jp=new Set;Vh(tE,jp),Vh(Qf,jp),Vh(rE,jp);const md={"_prelude_fog.vertex.glsl":sE,"_prelude_terrain.vertex.glsl":nE,"_prelude_shadow.vertex.glsl":$b,"_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":oy,"_prelude_shadow.fragment.glsl":Kc,"_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":ly,"_prelude_raster_particle.glsl":iE},cy={};Hn("",nE),Hn(oy,sE),Hn(Kc,$b),Hn(ly,""),Hn(iE,"");const Jf=Hn(rE,Qf),Q0=tE,uy=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Q0,Jf.fragmentSource].join(` `),uB=["precision highp float;",Q0,Jf.vertexSource].join(` `);var LI={background:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`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:Hn("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:Hn(`#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:Hn("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:Hn(`#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:Hn(`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:Hn("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:Hn("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:Hn("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:Hn("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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`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:Hn(`#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:Hn("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:Hn(`#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:Hn(`#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:Hn(`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:Hn(`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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`#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:Hn(`#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:Hn("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:Hn("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:Hn(`#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:Hn(`#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:Hn(`#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:Hn("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:Hn(`#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 }`,Z0),skyboxGradient:Hn(`#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 }`,Z0),skyboxCapture:Hn(` 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:Hn(`#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:Hn(`#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:Hn(`#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:Hn("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:Hn(`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:Hn("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:Hn("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:Hn("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:Hn("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 Vh(_,d){const g=_.split(` `);for(let S of g){if(S=S.trimStart(),S[0]!=="#"||!S.includes("if")||S.startsWith("#endif"))continue;const E=S.match(PI);if(E)for(const R of E)RI.has(R)||d.add(R)}}function MI(_){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(_)}function Hn(_,d){const g=new Set,S=[],E=[];_=_.replace(X0,(L,B)=>(E.push(B),"")),d=d.replace(X0,(L,B)=>(S.push(B),""));let R=new Set(jp);Vh(_,R),Vh(d,R);for(const L of[...S,...E])cy[L]||(cy[L]=new Set,Vh(md[L],cy[L])),R=new Set([...R,...cy[L]]);return{fragmentSource:_=_.replace(fr,(L,B,U,W,Z)=>(g.add(Z),B==="define"?` #ifndef HAS_UNIFORM_u_${Z} ${MI(W)?"flat ":""}in ${U} ${W} ${Z}; #else uniform ${U} ${W} u_${Z}; #endif `:B==="initialize"?` #ifdef HAS_UNIFORM_u_${Z} ${U} ${W} ${Z} = u_${Z}; #endif `:B==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${U} ${W} ${Z}; #endif `:B==="initialize-attribute"?"":void 0)),vertexSource:d=d.replace(fr,(L,B,U,W,Z)=>{const ne=`MATERIAL_ATTRIBUTE_OFFSET_${Z}`,re=W==="float"?"vec2":W,ie=`GET_ATTRIBUTE_${re}(a_${Z}, materialInfo, ${ne})`,ce=Z.match(/color/)?"color":re;return B==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${U} ${W} a_${Z}; #endif `:g.has(Z)?B==="define"?` #ifndef HAS_UNIFORM_u_${Z} uniform lowp float u_${Z}_t; #if !defined(${ne}) in ${U} ${re} a_${Z}; #endif ${MI(W)?"flat ":""}out ${U} ${W} ${Z}; #else uniform ${U} ${W} u_${Z}; #endif `:B==="initialize"?ce==="vec4"||ce==="uvec4"?` #ifndef HAS_UNIFORM_u_${Z} ${Z} = a_${Z}; #else ${U} ${W} ${Z} = u_${Z}; #endif `:` #if !defined(HAS_UNIFORM_u_${Z}) #ifdef ${ne} ${Z} = unpack_mix_${ce}(${ie}, u_${Z}_t); #else ${Z} = unpack_mix_${ce}(a_${Z}, u_${Z}_t); #endif #else ${U} ${W} ${Z} = u_${Z}; #endif `:B==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${U} ${W} a_${Z}; out ${U} ${W} ${Z}; #endif `:B==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} ${Z} = a_${Z}; #endif `:void 0:B==="define"?` #ifndef HAS_UNIFORM_u_${Z} uniform lowp float u_${Z}_t; #if !defined(${ne}) in ${U} ${re} a_${Z}; #endif #else uniform ${U} ${W} u_${Z}; #endif `:B==="define-instanced"?ce==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Z}0; in vec4 a_${Z}1; in vec4 a_${Z}2; in vec4 a_${Z}3; #else uniform ${U} ${W} u_${Z}; #endif `:` #ifdef INSTANCED_ARRAYS in ${U} ${re} a_${Z}; #else uniform ${U} ${W} u_${Z}; #endif `:B==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Z} ${U} ${W} ${Z} = a_${Z}; #endif `:ce==="vec4"||ce==="uvec4"?` #ifndef HAS_UNIFORM_u_${Z} #ifdef ${ne} ${U} ${W} ${Z} = ${ie}; #else ${U} ${W} ${Z} = a_${Z}; #endif #else ${U} ${W} ${Z} = u_${Z}; #endif `:` #ifndef HAS_UNIFORM_u_${Z} #ifdef ${ne} ${U} ${W} ${Z} = unpack_mix_${ce}(${ie}, u_${Z}_t); #else ${U} ${W} ${Z} = unpack_mix_${ce}(a_${Z}, u_${Z}_t); #endif #else ${U} ${W} ${Z} = u_${Z}; #endif `}),usedDefines:R,vertexIncludes:S,fragmentIncludes:E}}class DI{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(d,g,S,E,R,L,B,U){this.context=d;let W=this.boundPaintVertexBuffers.length!==E.length;for(let ne=0;!W&&ne{const Xe=Me.paint.get("hillshade-shadow-color"),$e=Me.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ke=Me.paint.get("hillshade-highlight-color"),De=Me.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Be=Me.paint.get("hillshade-accent-color"),Ge=Me.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",ot=Me.paint.get("hillshade-emissive-strength");let Je=a.ap(Me.paint.get("hillshade-illumination-direction"));if(Me.paint.get("hillshade-illumination-anchor")==="viewport")Je-=_e.transform.angle;else if(_e.style&&_e.style.enable3dLights()&&_e.style.directionalLight){const pt=_e.style.directionalLight.properties.get("direction"),Ot=a.cP(pt.x,pt.y,pt.z);Je=a.ap(Ot[1])}const St=!_e.options.moving;return{u_matrix:je||_e.transform.calculateProjMatrix(Re.tileID.toUnwrapped(),St),u_image:0,u_latrange:aE(0,Re.tileID),u_light:[Me.paint.get("hillshade-exaggeration"),Je],u_shadow:Xe.toPremultipliedRenderColor($e?null:Me.lut),u_highlight:Ke.toPremultipliedRenderColor(De?null:Me.lut),u_emissive_strength:ot,u_accent:Be.toPremultipliedRenderColor(Ge?null:Me.lut)}})(_,g,S,_.terrain?d.projMatrix:null);_.uploadCommonUniforms(B,re,d.toUnwrapped());const{tileBoundsBuffer:ce,tileBoundsIndexBuffer:le,tileBoundsSegments:be}=_.getTileBoundsBuffers(g);re.draw(_,U.TRIANGLES,E,R,L,Zr.disabled,ie,S.id,ce,le,be)}function OI(_,d,g){if(!d.needsDEMTextureUpload)return;const S=_.context,E=S.gl;S.pixelStoreUnpackPremultiplyAlpha.set(!1),d.demTexture=d.demTexture||_.getTileTexture(g.stride);const R=g.getPixels();d.demTexture?d.demTexture.update(R,{premultiply:!1}):d.demTexture=new a.T(S,R,E.R32F,{premultiply:!1}),d.needsDEMTextureUpload=!1}function hB(_,d,g){const S=_.context,E=S.gl;if(!d.dem)return;const R=d.dem;if(S.activeTexture.set(E.TEXTURE1),OI(_,d,R),!d.demTexture)return;d.demTexture.bind(E.NEAREST,E.CLAMP_TO_EDGE);const L=R.dim;S.activeTexture.set(E.TEXTURE0);let B=d.hillshadeFBO;if(!B){const re=new a.T(S,{width:L,height:L,data:null},E.RGBA8);re.bind(E.LINEAR,E.CLAMP_TO_EDGE),B=d.hillshadeFBO=S.createFramebuffer(L,L,1,"renderbuffer"),B.colorAttachment0.set(re.texture)}S.bindFramebuffer.set(B.framebuffer),S.viewport.set([0,0,L,L]);const{tileBoundsBuffer:U,tileBoundsIndexBuffer:W,tileBoundsSegments:Z}=_.getMercatorTileBoundsBuffers(),ne=[];_.linearFloatFilteringSupported()&&ne.push("TERRAIN_DEM_FLOAT_FORMAT"),_.terrain&&_.terrain.renderingToTexture&&_.emissiveMode==="mrt-fallback"&&ne.push("USE_MRT1"),_.getOrCreateProgram("hillshadePrepare",{defines:ne}).draw(_,E.TRIANGLES,Mr.disabled,an.disabled,tn.unblended,Zr.disabled,((re,ie)=>{const ce=ie.stride,le=a.bb();return a.bT(le,0,a.an,-a.an,0,0,1),a.bx(le,le,[0,-a.an,0]),{u_matrix:le,u_image:1,u_dimension:[ce,ce],u_zoom:re.overscaledZ}})(d.tileID,R),g.id,U,W,Z),d.needsHillshadePrepare=!1}class xi{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 FI extends xi{getDefault(){return a.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 fB extends xi{getDefault(){return 1}set(d){(d!==this.current||this.dirty)&&(this.gl.clearDepth(d),this.current=d,this.dirty=!1)}}class zb extends xi{getDefault(){return 0}set(d){(d!==this.current||this.dirty)&&(this.gl.clearStencil(d),this.current=d,this.dirty=!1)}}class mB extends xi{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 BI extends xi{getDefault(){return!0}set(d){(d!==this.current||this.dirty)&&(this.gl.depthMask(d),this.current=d,this.dirty=!1)}}class oE extends xi{getDefault(){return 255}set(d){(d!==this.current||this.dirty)&&(this.gl.stencilMask(d),this.current=d,this.dirty=!1)}}class Ub extends xi{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 lE extends xi{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 Ep extends xi{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;d?g.enable(g.STENCIL_TEST):g.disable(g.STENCIL_TEST),this.current=d,this.dirty=!1}}class kp extends xi{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 dy extends xi{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 Qd extends xi{getDefault(){return this.gl.LESS}set(d){(d!==this.current||this.dirty)&&(this.gl.depthFunc(d),this.current=d,this.dirty=!1)}}class $I extends xi{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 cE extends xi{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 zI extends xi{getDefault(){return a.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 hy extends xi{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 Vb extends xi{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 qb extends xi{getDefault(){return this.gl.BACK}set(d){(d!==this.current||this.dirty)&&(this.gl.cullFace(d),this.current=d,this.dirty=!1)}}class uE extends xi{getDefault(){return this.gl.CCW}set(d){(d!==this.current||this.dirty)&&(this.gl.frontFace(d),this.current=d,this.dirty=!1)}}let Gb=class extends xi{getDefault(){return null}set(_){(_!==this.current||this.dirty)&&(this.gl.useProgram(_),this.current=_,this.dirty=!1)}};class J0 extends xi{getDefault(){return this.gl.TEXTURE0}set(d){(d!==this.current||this.dirty)&&(this.gl.activeTexture(d),this.current=d,this.dirty=!1)}}class UI extends xi{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 VI extends xi{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 qI extends xi{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 fy extends xi{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 GI extends xi{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 pB extends xi{getDefault(){return null}set(d){const g=this.gl;g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,d),this.current=d,this.dirty=!1}}class gB extends xi{getDefault(){return null}set(d){this.gl&&(d!==this.current||this.dirty)&&(this.gl.bindVertexArray(d),this.current=d,this.dirty=!1)}}class yB extends xi{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 dE extends xi{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 hE extends xi{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 ev extends xi{constructor(d,g){super(d),this.context=d,this.parent=g}getDefault(){return null}}class my extends ev{constructor(d,g,S=0){super(d,g),this.attachmentPoint=d.gl.COLOR_ATTACHMENT0+S}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 fE extends ev{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 HI extends ev{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 xB extends fE{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const tv=(_,d,g,S)=>({u_matrix:_,u_image0:0,u_image1:1,u_skirt_height:d,u_ground_shadow_factor:g,u_emissive_texture_available:S}),py=(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be)=>({u_proj_matrix:Float32Array.from(_),u_globe_matrix:d,u_normalize_matrix:Float32Array.from(S),u_merc_matrix:g,u_zoom_transition:E,u_merc_center:R,u_image0:0,u_image1:1,u_frustum_tl:L,u_frustum_tr:B,u_frustum_br:U,u_frustum_bl:W,u_globe_pos:Z,u_globe_radius:ne,u_viewport:re,u_grid_matrix:be?Float32Array.from(be):new Float32Array(9),u_skirt_height:ie,u_far_z_cutoff:ce,u_emissive_texture_available:le});function mE(_,d){return _!=null&&d!=null&&!(!_.hasData()||!d.hasData())&&_.demTexture!=null&&d.demTexture!=null&&_.tileID.key!==d.tileID.key}const Xo=new class{constructor(){this.operations={}}newMorphing(_,d,g,S,E){if(_ in this.operations){const R=this.operations[_];R.to.tileID.key!==g.tileID.key&&(R.queued=g)}else this.operations[_]={startTime:S,phase:0,duration:E,from:d,to:g,queued:null}}getMorphValuesForProxy(_){if(!(_ in this.operations))return null;const d=this.operations[_];return{from:d.from,to:d.to,phase:d.phase}}update(_){for(const d in this.operations){const g=this.operations[d];for(g.phase=(_-g.startTime)/g.duration;g.phase>=1||!this._validOp(g);)if(!this._nextOp(g,_)){delete this.operations[d];break}}}_nextOp(_,d){return!!_.queued&&(_.from=_.to,_.to=_.queued,_.queued=null,_.phase=0,_.startTime=d,!0)}_validOp(_){return _.from.hasData()&&_.to.hasData()}},Hb={0:null,1:"TERRAIN_VERTEX_MORPHING"};function rv(_,d,g){if(d===0)return 0;const S=d<1&&g===514?.25/d:1;return 6*Math.pow(1.5,22-_)*Math.max(d,1)*S}function Wb(_,d){const g=1<<_.z;return!d&&(_.x===0||_.x===g-1)||_.y===0||_.y===g-1}function nv(_,d){if(!_.style||!_.style.enable3dLights())return;const g=_.context,S=g.gl;g.activeTexture.set(S.TEXTURE1),d?d.bind(S.LINEAR,S.CLAMP_TO_EDGE):_.emptyTexture.bind(S.LINEAR,S.CLAMP_TO_EDGE)}const sv=_=>({u_matrix:_});function iv(_,d,g,S,E){if(E>0){const R=a.o.now(),L=(R-_.timeAdded)/E,B=d?(R-d.timeAdded)/E:-1,U=g.getSource(),W=S.coveringZoomLevel({tileSize:U.tileSize,roundZoom:U.roundZoom}),Z=!d||Math.abs(d.tileID.overscaledZ-W)>Math.abs(_.tileID.overscaledZ-W),ne=Z&&_.refreshedUponExpiration?1:a.aC(Z?L:1-B,0,1);return d?{opacity:1,mix:1-ne,isFading:L<1}:{opacity:ne,mix:0,isFading:L<1}}return{opacity:1,mix:0,isFading:!1}}class Kb extends Pu{constructor(d){const g={type:"raster-dem",maxzoom:Math.ceil(d.transform.maxZoom)},S=Eb("mock-dem",g,d.style.dispatcher,d.style);super("mock-dem",S,null),S.setEventedParent(this),this._sourceLoaded=!0}_loadTile(d,g){d.state="loaded",g(null)}}class pE extends Pu{constructor(d){const g=Eb("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,S){if(d.freezeTileCoverage)return;this.transform=d;const E=d.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((R,L)=>{if(R[L.key]="",!this._tiles[L.key]){const B=new a.b0(L,this._source.tileSize*L.overscaleFactor(),d.tileZoom,void 0,void 0,this._source.worldview);B.state="loaded",this._tiles[L.key]=B}return R},{});for(const R in this._tiles)R in E||(this.freeFBO(R),this._tiles[R].unloadVectorData(),delete this._tiles[R])}freeFBO(d){const g=this.proxyCachedFBO[d];if(g!==void 0){const S=Object.values(g);this.renderCachePool.push(...S),delete this.proxyCachedFBO[d]}}deallocRenderCache(){this.renderCache.forEach(d=>d.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Yb extends a.aR{constructor(d,g,S){super(d.overscaledZ,d.wrap,d.canonical.z,d.canonical.x,d.canonical.y),this.proxyTileKey=g,this.projMatrix=S}}class av extends a.bu{constructor(d,g){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=d,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[S,E,R]=function(){const U=new a.dB,W=new a.dC,Z=131;U.reserve(17161),W.reserve(33800);const ne=a.an/128,re=a.an+ne/2,ie=re+ne;for(let le=-ne;lere||le<0||le>re?24575:0,Re=a.aC(Math.round(be),0,a.an),Me=a.aC(Math.round(le),0,a.an);U.emplaceBack(Re+_e,Me)}const ce=(le,be)=>{const _e=be*Z+le;W.emplaceBack(_e+1,_e,_e+Z),W.emplaceBack(_e+Z,_e+Z+1,_e+1)};for(let le=1;le<129;le++)for(let be=1;be<129;be++)ce(be,le);return[0,129].forEach(le=>{for(let be=0;be<130;be++)ce(be,le),ce(le,be)}),[U,W,32768]}(),L=d.context;this.gridBuffer=L.createVertexBuffer(S,a.dx.members),this.gridIndexBuffer=L.createIndexBuffer(E),this.gridSegments=a.dy.simpleSegment(0,0,S.length,E.length),this.gridNoSkirtSegments=a.dy.simpleSegment(0,0,S.length,R),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new pE(g.map),this.orthoMatrix=a.bb(),a.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,a.an,0,a.an,0,1);const B=L.gl;this._overlapStencilMode=new an({func:B.GEQUAL,mask:255},0,255,B.KEEP,B.KEEP,B.REPLACE),this._previousZoom=d.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=g,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Kb(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,S){if(d&&d.terrain){this._style!==d&&(this.style=d,this._evaluationZoom=void 0);const E=d.terrain.properties,R=d.terrain.drapeRenderMode===0,L=d.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=a.o.now();const B=d.terrain&&d.terrain.scope,U=E.get("source"),W=R?this._mockSourceCache:d.getSourceCache(U,B);if(!W)return void a.w(`Couldn't find terrain source "${U}".`);if(this.sourceCache=W,this._attenuationRange=d.terrain.getAttenuationRange(),this._exaggeration=L?this.calculateExaggeration(g):E.get("exaggeration"),!g.projection.requiresDraping&&L&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Z=()=>{this.sourceCache.used&&a.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 ne=this.getScaledDemTileSize();this.sourceCache.update(g,ne,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Z(),this._initializing=!0),Z(),g.updateElevation(!0,S),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,S=d.getFreeCameraOptions().position.z/d.pixelsPerMeter*d.worldSize;this._previousCameraAltitude=S;const E=g!=null?S-g:Number.MAX_VALUE;if(Math.abs(E)<2)return this._exaggeration;const R=d.zoom,L=this._style.terrain;if(!this._previousUpdateTimestamp)return L.getExaggeration(R);let B=R-this._previousZoom;const U=this._previousUpdateTimestamp;let W=R;this._evaluationZoom!=null&&(W=this._evaluationZoom,Math.abs(R-W)>.5&&(B=.5*(R-W+B)),B*E<0&&(W+=B)),this._evaluationZoom=W;const Z=L.getExaggeration(W),ne=Z===L.getExaggeration(Math.max(0,W-.1));if(ne&&Math.abs(Z-this._exaggeration)<.01)return Z;let re=Math.min(.1,.00375*(this._updateTimestamp-U));return(ne||Z<.1||Math.abs(B)<1e-4)&&(re=Math.min(.2,4*re)),a.am(this._exaggeration,Z,re)}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,S=this.painter.transform;this._initializing&&(this._initializing=S._centerAltitude===0&&this.getAtPointOrZero(a.ag.fromLngLat(S.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const E=this.proxyCoords=g.getIds().map(U=>{const W=g.getTileByID(U).tileID;return W.projMatrix=S.calculateProjMatrix(W.toUnwrapped()),W});(function(U,W){const Z=W.transform.pointCoordinate(W.transform.getCameraPoint()),ne=new a.P(Z.x,Z.y);U.sort((re,ie)=>{if(ie.overscaledZ-re.overscaledZ)return ie.overscaledZ-re.overscaledZ;const ce=new a.P(re.canonical.x+(1<{this.proxyToSource[U.key]={}}),this.terrainTileForTile={};const L=this._style._mergedSourceCaches;for(const U in L){const W=L[U];if(!W.used||(W!==this.sourceCache&&this.resetTileLookupCache(W.id),this._setupProxiedCoordsForOrtho(W,d[U],R),W.usedForTerrain))continue;const Z=d[U];(W.getSource().reparseOverscaled||W._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Z)}this.proxiedCoords[g.id]=E.map(U=>new Yb(U,U.key,this.orthoMatrix)),this._assignTerrainTiles(E),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(R),this.renderingToTexture=!1;const B={};this._visibleDemTiles=[];for(const U of this.proxyCoords){const W=this.terrainTileForTile[U.key];if(!W)continue;const Z=W.tileID.key;Z in B||(this._visibleDemTiles.push(W),B[Z]=Z)}}_assignTerrainTiles(d){this._initializing||d.forEach(g=>{if(this.terrainTileForTile[g.key])return;const S=this._findTileCoveringTileID(g,this.sourceCache);S&&(this.terrainTileForTile[g.key]=S)})}_prepareDEMTextures(){const d=this.painter.context,g=d.gl;for(const S in this.terrainTileForTile){const E=this.terrainTileForTile[S],R=E.dem;!R||E.demTexture&&!E.needsDEMTextureUpload||(d.activeTexture.set(g.TEXTURE1),OI(this.painter,E,R))}}_prepareDemTileUniforms(d,g,S,E){if(!g||g.demTexture==null)return!1;const R=d.tileID.canonical,L=Math.pow(2,g.tileID.canonical.z-R.z),B=E||"";return S[`u_dem_tl${B}`]=[R.x*L%1,R.y*L%1],S[`u_dem_scale${B}`]=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((S,E)=>{if(!E.dem)return S;const R=E.dem.tree.minimums[0];return R>0&&d++,S+R},0);return d?g/d:0}_updateEmptyDEMTexture(){const d=this.painter.context,g=d.gl;d.activeTexture.set(g.TEXTURE2);const S=this._getLoadedAreaMinimum(),E=new a.dz({width:1,height:1},new Float32Array([S]));this._emptyDEMTextureDirty=!1;let R=this._emptyDEMTexture;return R?R.update(E,{premultiply:!1}):R=this._emptyDEMTexture=new a.T(d,E,g.R32F,{premultiply:!1}),R}setupElevationDraw(d,g,S){const E=this.painter.context,R=E.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 B=null,U=null,W=1;if(S&&S.morphing&&this._useVertexMorphing){const ie=S.morphing.srcDemTile,ce=S.morphing.dstDemTile;W=S.morphing.phase,ie&&ce&&(this._prepareDemTileUniforms(d,ie,L,"_prev")&&(U=ie),this._prepareDemTileUniforms(d,ce,L)&&(B=ce))}const Z=ie=>ie&&ie.demTexture&&this.painter.linearFloatFilteringSupported()?R.LINEAR:R.NEAREST;let ne=null;var re;if(this.enabled?U&&B?(ne=B.demTexture,E.activeTexture.set(R.TEXTURE4),U.demTexture.bind(Z(U),R.CLAMP_TO_EDGE),L.u_dem_lerp=W):(B=this.terrainTileForTile[d.tileID.key],ne=this._prepareDemTileUniforms(d,B,L)?B.demTexture:this.emptyDEMTexture):ne=this.emptyDEMTexture,E.activeTexture.set(R.TEXTURE2),ne&&(L.u_dem_size=(re=ne).size[0]===1?1:re.size[0]-2,ne.bind(Z(B),R.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(S&&S.useDepthForOcclusion,g,L),S&&S.useMeterToDem&&B){const ie=(1<{if(_e===pt)return;const Ot=[Hb[pt],"PROJECTION_GLOBE_VIEW"];Me&&Ot.push("CUSTOM_ANTIALIASING");const Ut=W.isTileAffectedByFog(St);be=W.getOrCreateProgram("globeRaster",{defines:Ot,overrideFog:Ut}),_e=pt},Xe=W.colorModeForRenderPass(),$e=new Mr(le.LEQUAL,Mr.ReadWrite,W.depthRangeFor3D);Xo.update(ie);const Ke=a.dq(Re),De=[a.aH(Re.center.lng),a.aL(Re.center.lat)],Be=W.globeSharedBuffers,Ge=[Re.width*a.o.devicePixelRatio,Re.height*a.o.devicePixelRatio],ot=Float32Array.from(Re.globeMatrix),Je={useDenormalizedUpVectorScale:!0};{const St=W.transform,pt=rv(St.zoom,Z.exaggeration(),Z.sourceCache._source.tileSize);_e=-1;const Ot=le.TRIANGLES;for(const Ut of re){const ut=ne.getTile(Ut),st=an.disabled,_t=Z.prevTerrainTileForTile[Ut.key],jt=Z.terrainTileForTile[Ut.key];mE(_t,jt)&&Xo.newMorphing(Ut.key,_t,jt,ie,250),nv(W,ut.emissiveTexture),ce.activeTexture.set(le.TEXTURE0),ut.texture&&ut.texture.bind(le.LINEAR,le.CLAMP_TO_EDGE);const Nt=Xo.getMorphValuesForProxy(Ut.key),lr=Nt?1:0;Nt&&Object.assign(Je,{morphing:{srcDemTile:Nt.from,dstDemTile:Nt.to,phase:a.dn(Nt.phase)}});const Jt=a.dr(Ut.canonical),er=a.ds(Jt.getCenter().lat),zt=a.dt(Ut.canonical,Jt,er,St.worldSize/St._pixelsPerMercatorPixel),Pr=a.du(a.dv(Ut.canonical)),Fr=W.emissiveMode==="mrt-fallback"?1:0,br=py(St.expandedFarZProjMatrix,ot,Ke,Pr,a.al(St.zoom),De,St.frustumCorners.TL,St.frustumCorners.TR,St.frustumCorners.BR,St.frustumCorners.BL,St.globeCenterInViewSpace,St.globeRadius,Ge,pt,St._farZ,Fr,zt);if(je(Ut,lr),be&&(Z.setupElevationDraw(ut,be,Je),W.uploadCommonUniforms(ce,be,Ut.toUnwrapped()),Be)){const[Nr,Jr,dn]=Be.getGridBuffers(er,pt!==0);be.draw(W,Ot,$e,st,Xe,Zr.backCCW,br,"globe_raster",Nr,Jr,dn)}}}if(Be&&(W.renderDefaultNorthPole||W.renderDefaultSouthPole)){const St=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Me&&St.push("CUSTOM_ANTIALIASING"),be=W.getOrCreateProgram("globeRaster",{defines:St});for(const pt of re){const{x:Ot,y:Ut,z:ut}=pt.canonical,st=Ut===0,_t=Ut===(1<Nr.draw(W,le.TRIANGLES,$e,an.disabled,Xe,Zr.disabled,py(Re.expandedFarZProjMatrix,zt,zt,Pr,0,De,Re.frustumCorners.TL,Re.frustumCorners.TR,Re.frustumCorners.BR,Re.frustumCorners.BL,Re.globeCenterInViewSpace,Re.globeRadius,Ge,0,Re._farZ,Fr),"globe_pole_raster",Jr,lr,Jt);Z.setupElevationDraw(er,be,Je),W.uploadCommonUniforms(ce,be,pt.toUnwrapped()),st&&W.renderDefaultNorthPole&&br(be,jt),_t&&W.renderDefaultSouthPole&&(zt=a.cC(a.bb(),zt,[1,-1,1]),br(be,Nt))}}}})(E,R,L,B,U);else{const W=E.context,Z=W.gl;let ne,re;const ie=E.shadowRenderer,ce=Ya(E,E.longestCutoffRange),le=Xe=>{if(re===Xe)return;const $e=[];$e.push(Hb[Xe]),ce.shouldRenderCutoff&&$e.push("RENDER_CUTOFF"),ie&&($e.push("RENDER_SHADOWS"),ie.useNormalOffset&&$e.push("NORMAL_OFFSET")),ne=E.getOrCreateProgram("terrainRaster",{defines:$e}),re=Xe},be=E.colorModeForRenderPass(),_e=new Mr(Z.LEQUAL,Mr.ReadWrite,E.depthRangeFor3D);Xo.update(U);const Re=E.transform,Me=rv(Re.zoom,R.exaggeration(),R.sourceCache._source.tileSize);let je=[0,0,0];if(ie){const Xe=E.style.directionalLight,$e=E.style.ambientLight;Xe&&$e&&(je=fd(E.style,Xe,$e))}{re=-1;const Xe=Z.TRIANGLES,[$e,Ke]=[R.gridIndexBuffer,R.gridSegments];for(const De of B){const Be=L.getTile(De),Ge=an.disabled,ot=R.prevTerrainTileForTile[De.key],Je=R.terrainTileForTile[De.key];mE(ot,Je)&&Xo.newMorphing(De.key,ot,Je,U,250),nv(E,Be.emissiveTexture),W.activeTexture.set(Z.TEXTURE0),Be.texture&&Be.texture.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const St=Xo.getMorphValuesForProxy(De.key),pt=St?1:0;let Ot;St&&(Ot={morphing:{srcDemTile:St.from,dstDemTile:St.to,phase:a.dn(St.phase)}});const Ut=E.emissiveMode==="mrt-fallback"?1:0,ut=tv(De.projMatrix,Wb(De.canonical,Re.renderWorldCopies)?Me/10:Me,je,Ut);if(le(pt),!ne)continue;R.setupElevationDraw(Be,ne,Ot);const st=De.toUnwrapped();ie&&ie.setupShadows(st,ne),E.uploadCommonUniforms(W,ne,st,null,ce),ne.draw(E,Xe,_e,Ge,be,Zr.backCCW,ut,"terrain_raster",R.gridBuffer,$e,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,S=this.painter.context,E=this.proxySourceCache,R=this.proxiedCoords[E.id],L=this._drapedRenderBatches.shift(),B=g.style.order,U=[];this._updateFBOs(g.emissiveMode==="mrt-fallback");let W=0;for(const Z of R){const ne=E.getTileByID(Z.proxyTileKey),re=E.proxyCachedFBO[Z.key]?E.proxyCachedFBO[Z.key][d]:void 0,ie=re!==void 0?E.renderCache[re]:this.pool[W++],ce=re!==void 0;if(ne.texture=ie.tex,ne.emissiveTexture=ie.emissiveTex,ce&&!ie.dirty){U.push(ne.tileID);continue}S.bindFramebuffer.set(ie.fb.framebuffer);const le=S.gl;let be;le.drawBuffers(g.emissiveMode==="mrt-fallback"?[le.COLOR_ATTACHMENT0,le.COLOR_ATTACHMENT1]:[le.COLOR_ATTACHMENT0]),this.renderedToTile=!1,ie.dirty&&(S.clear({color:a.aq.transparent,stencil:0}),ie.dirty=!1);for(let _e=L.start;_e<=L.end;++_e){const Re=g.style._mergedLayers[B[_e]];if(Re.isHidden(g.transform.zoom))continue;const Me=g.style.getLayerSourceCache(Re),je=Me?this.proxyToSource[Z.key][Me.id]:[Z];if(!je)continue;const Xe=je;S.viewport.set([0,0,ie.fb.width,ie.fb.height]),be!==(Me?Me.id:null)&&(this._setupStencil(ie,je,Re,Me),be=Me?Me.id:null),g.renderLayer(g,Me,Re,Xe)}if(le.drawBuffers([le.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const _e of this._pendingGroundEffectLayers){const Re=g.style._mergedLayers[B[_e]];if(Re.isHidden(g.transform.zoom))continue;const Me=g.style.getLayerSourceCache(Re),je=Me?this.proxyToSource[Z.key][Me.id]:[Z];if(!je)continue;const Xe=je;S.viewport.set([0,0,ie.fb.width,ie.fb.height]),be!==(Me?Me.id:null)&&(this._setupStencil(ie,je,Re,Me),be=Me?Me.id:null),g.renderLayer(g,Me,Re,Xe)}this.renderedToTile?(ie.dirty=!0,U.push(ne.tileID)):ce||--W,W===5&&(W=0,this.renderToBackBuffer(U))}return this.renderToBackBuffer(U),this.renderingToTexture=!1,S.bindFramebuffer.set(null),S.viewport.set([0,0,g.width,g.height]),L.end+1}postRender(){}isLayerOrderingCorrect(d){const g=d.order.length;let S=-1,E=g;for(let R=0;RS}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,S){if(!this._visibleDemTiles)return null;const E=this._visibleDemTiles.filter(R=>R.dem).map(R=>{const L=R.tileID,B=1<(R.t!==null?R.t:Number.MAX_VALUE)-(L.t!==null?L.t:Number.MAX_VALUE));for(const R of E){if(R.t==null)return null;const L=R.tile.dem.tree.raycast(R.minx,R.miny,R.maxx,R.maxy,d,g,S);if(L!=null)return L}return null}_createFBO(){const d=this.painter.context,g=d.gl,S=this.drapeBufferSize;d.activeTexture.set(g.TEXTURE0);const E=new a.T(d,{width:S[0],height:S[1],data:null},g.RGBA8);E.bind(g.LINEAR,g.CLAMP_TO_EDGE);const R=d.createFramebuffer(S[0],S[1],1,null);let L;return R.colorAttachment0.set(E.texture),this._emissiveTexture&&(L=new a.T(d,{width:S[0],height:S[1],data:null},g.R8),L.bind(g.LINEAR,g.CLAMP_TO_EDGE),R.createColorAttachment(d,1),R.colorAttachment1.set(L.texture)),R.depthAttachment=new xB(d,R.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=d.createRenderbuffer(d.gl.DEPTH_STENCIL,S[0],S[1]),this._stencilRef=0,R.depthAttachment.set(this._sharedDepthStencil),d.clear({stencil:0})):R.depthAttachment.set(this._sharedDepthStencil),d.extTextureFilterAnisotropic&&g.texParameterf(g.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax),{fb:R,tex:E,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 S=d.fb,E=this.painter.context,R=E.gl,L=this.drapeBufferSize;if(g){const B=new a.T(E,{width:L[0],height:L[1],data:null},R.R8);B.bind(R.LINEAR,R.CLAMP_TO_EDGE),d.emissiveTex=B,S.createColorAttachment(E,1),S.colorAttachment1.set(B.texture)}else d.emissiveTex=void 0,S.removeColorAttachment(E,1);d.dirty=!0}_initFBOPool(){for(;this.pool.length{const g=this._style._mergedLayers[d],S=g.isHidden(this.painter.transform.zoom);return g.type==="hillshade"||g.type==="custom"?!S&&g.shouldRedrape():!S&&g.hasTransition()})}_clearLineLayersFromRenderCache(){let d=!1;for(const S of this._style.getSources())if(S instanceof Zl){d=!0;break}if(!d)return;const g={};for(let S=0;SU>B.end)||a.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=S}_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 B=0;B=0;L--){const B=S[L];if(g.getTileByID(B.key),g.proxyCachedFBO[B.key]!==void 0){const U=d[B.key],W=this.proxyToSource[B.key];let Z=0;for(const ne in W){const re=W[ne],ie=U[ne];if(!ie||ie.length!==re.length||re.some((ce,le)=>ce!==ie[le]||E[ne]&&E[ne].hasOwnProperty(ce.key))){Z=-1;break}++Z}for(const ne in g.proxyCachedFBO[B.key])g.renderCache[g.proxyCachedFBO[B.key][ne]].dirty=Z<0||Z!==Object.values(U).length}}const R=[...this._drapedRenderBatches];R.sort((L,B)=>B.end-B.start-(L.end-L.start));for(const L of R)for(const B of S){if(g.proxyCachedFBO[B.key])continue;let U=g.renderCachePool.pop();U===void 0&&g.renderCache.length<50&&(U=g.renderCache.length,g.renderCache.push(this._createFBO())),U!==void 0&&(g.proxyCachedFBO[B.key]={},g.proxyCachedFBO[B.key][L.start]=U,g.renderCache[U].dirty=!0)}this._tilesDirty={}}_setupStencil(d,g,S,E){if(!E||!this._sourceTilesOverlap[E.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const R=this.painter.context,L=R.gl;if(g.length<=1)return void(this._overlapStencilType=!1);let B;if(S.isTileClipped())B=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);B=1,this._overlapStencilMode.test={func:L.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+B>255&&(R.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=B,this._overlapStencilMode.ref=this._stencilRef,S.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):an.disabled}_renderTileClippingMasks(d,g){const S=this.painter,E=this.painter.context,R=E.gl;S._tileClippingMaskIDs={},E.setColorMode(tn.disabled),E.setDepthMode(Mr.disabled);const L=S.getOrCreateProgram("clippingMask");for(const B of d){const U=S._tileClippingMaskIDs[B.key]=--g;L.draw(S,R.TRIANGLES,Mr.disabled,new an({func:R.ALWAYS,mask:0},U,255,R.KEEP,R.KEEP,R.REPLACE),tn.disabled,Zr.disabled,sv(B.projMatrix),"$clipping",S.tileExtentBuffer,S.quadTriangleIndexBuffer,S.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 S=[d.x,d.y,1,1];a.aE(S,S,g.pixelMatrixInverse),a.cu(S,S,1/S[3]),S[0]/=g.worldSize,S[1]/=g.worldSize;const E=g._camera.position,R=a.bU(1,g.center.lat),L=[E[0],E[1],E[2]/R,0],B=a.cV([],S.slice(0,3),L);a.ay(B,B);const U=this.raycast(L,B,this._exaggeration);return U!==null&&U?(a.bg(L,L,B,U),L[3]=L[2],L[2]*=R,L):null}_setupProxiedCoordsForOrtho(d,g,S){if(d.getSource()instanceof a.aV)return this._setupProxiedCoordsForImageSource(d,g,S);this._findCoveringTileCache[d.id]=this._findCoveringTileCache[d.id]||{};const E=this.proxiedCoords[d.id]=[],R=this.proxyCoords;for(let U=0;UZ.overscaledZ-W.overscaledZ)}_setupProxiedCoordsForImageSource(d,g,S){if(!d.getSource().loaded())return;const E=this.proxiedCoords[d.id]=[],R=this.proxyCoords,L=d.getSource(),B=L.tileID;if(!B)return;const U=new a.P(B.x,B.y)._div(1<(ne.min.x=Math.min(ne.min.x,re.x-U.x),ne.min.y=Math.min(ne.min.y,re.y-U.y),ne.max.x=Math.max(ne.max.x,re.x-U.x),ne.max.y=Math.max(ne.max.y,re.y-U.y),ne),{min:new a.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new a.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Z=(ne,re)=>{const ie=ne.wrap+ne.canonical.x/(1<be+W.max.x||ce+le<_e+W.min.y||ce>_e+W.max.y};for(let ne=0;neL.key===g.tileID.key);if(R)return R}if(g.tileID.key!==d.key){const R=d.canonical.z-g.tileID.canonical.z;let L,B,U;E=a.bb();const W=g.tileID.wrap-d.wrap<0?(L=a.an>>R,B=L*((g.tileID.canonical.x<=ne){const re=d.canonical.z-ne;g.getSource().reparseOverscaled?(B=Math.max(d.canonical.z+2,g.transform.tileZoom),L=new a.aR(B,d.wrap,ne,d.canonical.x>>re,d.canonical.y>>re)):re!==0&&(B=ne,L=new a.aR(B,d.wrap,ne,d.canonical.x>>re,d.canonical.y>>re))}L.key!==d.key&&(W.push(L.key),S=g.getTile(L))}const Z=ne=>{W.forEach(re=>{E[re]=ne}),W.length=0};for(B-=1;B>=U&&(!S||!S.hasData());B--){S&&Z(S.tileID.key);const ne=L.calculateScaledKey(B);if(S=g.getTileByID(ne),S&&S.hasData())break;const re=E[ne];if(re===null)break;re===void 0?W.push(ne):S=g.getTileByID(re)}return Z(S?S.tileID.key:null),S&&S.hasData()?S:null}findDEMTileFor(d){return this.enabled?this._findTileCoveringTileID(d,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(d,g){let S=this._tilesDirty[d];S||(S=this._tilesDirty[d]={}),S[g.key]=!0}}function gE(_,d,g){const S=function(B,U,W){const Z=a.bi(U,B),ne=a.bi(W,[.2126,.7152,.0722]),re=(ce,le,be)=>(1-be)*ce+be*le,ie=re(1-.3*Math.min(ne,1),1,Math.min(Z+1,1));return re(.92,1,Math.asin(a.aC(U[2],-1,1))/Math.PI+.5)*ie}(_,[0,0,1],d),E=[0,0,0];a.bJ(E,g.slice(0,3),S);const R=[0,0,0];a.bJ(R,d.slice(0,3),_[2]);const L=[0,0,0];return a.cT(L,E,R),a.cW(L)}const WI=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],KI=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Ap{static cacheKey(d,g,S,E){const R=[g];E&&R.push(E.cacheKey);for(const L of S)(typeof L=="string"&&L.includes(" ")||d.usedDefines.has(L))&&R.push(L);return R.join("/")}constructor(d,g,S,E,R,L){const B=d.gl;this.program=B.createProgram(),this.configuration=E,this.name=g,this.fixedDefines=[...L];const U=`#version 300 es ${(E?E.defines():[]).concat(L.map(le=>`#define ${le}`)).join(` `)}`,W=[U,uy];for(const le of S.fragmentIncludes)W.push(md[le]);W.push(S.fragmentSource);const Z=W.join(` `),ne=[U,uB];for(const le of S.vertexIncludes)ne.push(md[le]);this.forceManualRenderingForInstanceIDShaders=d.forceManualRenderingForInstanceIDShaders&&S.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&ne.push("uniform int u_instanceID;"),ne.push(S.vertexSource);let re=ne.join(` `);this.forceManualRenderingForInstanceIDShaders&&(re=re.replaceAll("gl_InstanceID","u_instanceID"));const ie=B.createShader(B.FRAGMENT_SHADER);if(B.isContextLost())return void(this.failedToCreate=!0);B.shaderSource(ie,Z),B.compileShader(ie),B.attachShader(this.program,ie);const ce=B.createShader(B.VERTEX_SHADER);B.isContextLost()?this.failedToCreate=!0:(B.shaderSource(ce,re),B.compileShader(ce),B.attachShader(this.program,ce),this.attributes={},B.linkProgram(this.program),B.deleteShader(ce),B.deleteShader(ie),this.fixedUniforms=R(d),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=E?E.getUniforms(d):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(le=>({u_instanceID:new a.bX(le)}))(d)),(L.includes("TERRAIN")||L.includes("ELEVATED")||g.includes("symbol")||g.includes("circle"))&&(this.terrainUniforms=(le=>({u_dem:new a.bX(le),u_dem_prev:new a.bX(le),u_dem_tl:new a.b_(le),u_dem_scale:new a.bZ(le),u_dem_tl_prev:new a.b_(le),u_dem_scale_prev:new a.bZ(le),u_dem_size:new a.bZ(le),u_dem_lerp:new a.bZ(le),u_exaggeration:new a.bZ(le),u_depth:new a.bX(le),u_depth_size_inv:new a.b_(le),u_depth_range_unpack:new a.b_(le),u_occluder_half_size:new a.bZ(le),u_occlusion_depth_offset:new a.bZ(le),u_meter_to_dem:new a.bZ(le),u_label_plane_matrix_inv:new a.b$(le)}))(d)),L.includes("GLOBE")&&(this.globeUniforms=(le=>({u_tile_tl_up:new a.bY(le),u_tile_tr_up:new a.bY(le),u_tile_br_up:new a.bY(le),u_tile_bl_up:new a.bY(le),u_tile_up_scale:new a.bZ(le)}))(d)),L.includes("FOG")&&(this.fogUniforms=(le=>({u_fog_matrix:new a.b$(le),u_fog_range:new a.b_(le),u_fog_color:new a.cO(le),u_fog_horizon_blend:new a.bZ(le),u_fog_vertical_limit:new a.b_(le),u_fog_temporal_offset:new a.bZ(le),u_frustum_tl:new a.bY(le),u_frustum_tr:new a.bY(le),u_frustum_br:new a.bY(le),u_frustum_bl:new a.bY(le),u_globe_pos:new a.bY(le),u_globe_radius:new a.bZ(le),u_globe_transition:new a.bZ(le),u_is_globe:new a.bX(le),u_viewport:new a.b_(le)}))(d)),L.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(le=>({u_cutoff_params:new a.cO(le)}))(d)),L.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(le=>({u_lighting_ambient_color:new a.bY(le),u_lighting_directional_dir:new a.bY(le),u_lighting_directional_color:new a.bY(le),u_ground_radiance:new a.bY(le)}))(d)),L.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(le=>({u_light_matrix_0:new a.b$(le),u_light_matrix_1:new a.b$(le),u_fade_range:new a.b_(le),u_shadow_normal_offset:new a.bY(le),u_shadow_intensity:new a.bZ(le),u_shadow_texel_size:new a.bZ(le),u_shadow_map_resolution:new a.bZ(le),u_shadow_direction:new a.bY(le),u_shadow_bias:new a.bY(le),u_shadowmap_0:new a.bX(le),u_shadowmap_1:new a.bX(le)}))(d)))}getAttributeLocation(d,g){let S=this.attributes[g];return S===void 0&&(S=this.attributes[g]=d.getAttribLocation(this.program,g)),S}setTerrainUniformValues(d,g){if(!this.terrainUniforms)return;const S=this.terrainUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const E in g)S[E]&&S[E].set(this.program,E,g[E])}}setGlobeUniformValues(d,g){if(!this.globeUniforms)return;const S=this.globeUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const E in g)S[E]&&S[E].set(this.program,E,g[E])}}setFogUniformValues(d,g){if(!this.fogUniforms)return;const S=this.fogUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const E in g)S[E].set(this.program,E,g[E])}}setCutoffUniformValues(d,g){if(!this.cutoffUniforms)return;const S=this.cutoffUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const E in g)S[E].set(this.program,E,g[E])}}setLightsUniformValues(d,g){if(!this.lightsUniforms)return;const S=this.lightsUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const E in g)S[E].set(this.program,E,g[E])}}setShadowUniformValues(d,g){if(this.failedToCreate||!this.shadowUniforms)return;const S=this.shadowUniforms;d.program.set(this.program);for(const E in g)S[E].set(this.program,E,g[E])}_drawDebugWireframe(d,g,S,E,R,L,B,U,W,Z){const ne=d.options.wireframe;if(ne.terrain===!1&&ne.layers2D===!1&&ne.layers3D===!1)return;const re=d.context;if(!(!(!ne.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!ne.layers2D||d._terrain&&d._terrain.renderingToTexture||!WI.includes(this.name))||!(!ne.layers3D||!KI.includes(this.name))))return;const ie=re.gl,ce=d.wireframeDebugCache.getLinesFromTrianglesBuffer(d.frameCounter,R,re);if(!ce)return;const le=[...this.fixedDefines,"DEBUG_WIREFRAME"],be=d.getOrCreateProgram(this.name,{config:this.configuration,defines:le});re.program.set(be.program);const _e=(je,Xe,$e)=>{if(Xe[je]&&$e[je])for(const Ke in Xe[je])$e[je][Ke]&&$e[je][Ke].set($e.program,Ke,Xe[je][Ke].current)};W&&W.setUniforms(be.program,re,be.binderUniforms,B,{zoom:U}),_e("fixedUniforms",this,be),_e("terrainUniforms",this,be),_e("globeUniforms",this,be),_e("fogUniforms",this,be),_e("lightsUniforms",this,be),_e("shadowUniforms",this,be),ce.bind(),re.setColorMode(new tn([ie.ONE,ie.ONE_MINUS_SRC_ALPHA,ie.ZERO,ie.ONE],a.aq.transparent,[!0,!0,!0,!1])),re.setDepthMode(new Mr(g.func===ie.LESS?ie.LEQUAL:g.func,Mr.ReadOnly,g.range)),re.setStencilMode(an.disabled);const Re=3*L.primitiveLength*2,Me=3*L.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const je=Z||1;for(let Xe=0;Xe1?ie.drawElementsInstanced(ie.LINES,Re,ie.UNSIGNED_SHORT,Me,Z):ie.drawElements(ie.LINES,Re,ie.UNSIGNED_SHORT,Me);R.bind(),re.program.set(this.program),re.setDepthMode(g),re.setStencilMode(S),re.setColorMode(E)}checkUniforms(d,g,S){if(this.fixedDefines.includes(g)){for(const E of Object.keys(S))if(!S[E].initialized)throw new Error(`Program '${this.name}', from draw '${d}': uniform ${E} not set but required by ${g} being defined`)}}draw(d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be){const _e=d.context,Re=_e.gl;if(this.failedToCreate)return;_e.program.set(this.program),_e.setDepthMode(S),_e.setStencilMode(E),_e.setColorMode(R),_e.setCullFace(L);for(const[De,Be]of this.fixedUniformsEntries)Be.set(this.program,De,B[De]);ce&&ce.setUniforms(this.program,_e,this.binderUniforms,re,{zoom:ie});const Me={[Re.POINTS]:1,[Re.LINES]:2,[Re.TRIANGLES]:3,[Re.LINE_STRIP]:1}[g];this.checkUniforms(U,"RENDER_SHADOWS",this.shadowUniforms);const je=le||[],Xe=ce?ce.getPaintVertexBuffers():[],$e=g===Re.TRIANGLES&&Z,Ke=be&&be>0?1:void 0;for(const De of ne.get()){const Be=De.vaos||(De.vaos={});if((Be[U]||(Be[U]=new DI)).bind(_e,this,W,Xe,Z,De.vertexOffset,je,Ke),this.forceManualRenderingForInstanceIDShaders){const Ge=be||1;for(let ot=0;ot1?Re.drawElementsInstanced(g,De.primitiveLength*Me,Re.UNSIGNED_SHORT,De.primitiveOffset*Me*2,be):Z?Re.drawElements(g,De.primitiveLength*Me,Re.UNSIGNED_SHORT,De.primitiveOffset*Me*2):Re.drawArrays(g,De.vertexOffset,De.vertexLength);$e&&this._drawDebugWireframe(d,S,E,R,Z,De,re,ie,ce,be)}}}function YI(_,d,g=0){const S=Math.pow(2,d.tileID.overscaledZ),E=d.tileSize*Math.pow(2,_.transform.tileZoom)/S,R=E*(d.tileID.canonical.x+d.tileID.wrap*S),L=E*d.tileID.canonical.y;return{u_image:0,u_texsize:d.imageAtlasTexture?d.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/a.aA(d,1,_.transform.tileZoom),u_pixel_coord_upper:[R>>16,L>>16],u_pixel_coord_lower:[65535&R,65535&L],u_pattern_transition:g}}const Zb={terrain:0,flat:1},vB=a.bb(),ZI=(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re=[0,0,1])=>{const Me=d.style.light,je=Me.properties.get("position"),Xe=[je.x,je.y,je.z],$e=a.dE();Me.properties.get("anchor")==="viewport"&&(a.dF($e,-d.transform.angle),a.dG(Xe,Xe,$e));const Ke=Me.properties.get("color").toPremultipliedRenderColor(null),De=d.transform,Be={u_matrix:_,u_lightpos:Xe,u_lightintensity:Me.properties.get("intensity"),u_lightcolor:[Ke.r,Ke.g,Ke.b],u_vertical_gradient:+g,u_opacity:S,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:vB,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:Zb[W],u_base_type:Zb[Z],u_ao:E,u_edge_radius:R,u_width_scale:L,u_flood_light_color:ce,u_vertical_scale:le,u_flood_light_intensity:be,u_ground_shadow_factor:_e,u_front_cutoff_params:Re};return De.projection.name==="globe"&&(Be.u_tile_id=[B.canonical.x,B.canonical.y,1<({u_matrix:_,u_edge_radius:d,u_width_scale:g,u_vertical_scale:S,u_height_type:Zb[E],u_base_type:Zb[R]}),bB=(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e)=>{const Re=ZI(_,d,g,S,E,R,L,B,W,Z,ne,re,ie,ce,le,be,1,[0,0,0]),Me={u_height_factor:-Math.pow(2,B.overscaledZ)/U.tileSize/8};return Object.assign(Re,YI(d,U,_e),Me)},Xb=(_,d,g)=>({u_matrix:_,u_emissive_strength:d,u_ground_shadow_factor:g}),Qb=(_,d,g,S,E,R=0)=>Object.assign(Xb(_,d,E),YI(g,S,R)),XI=(_,d,g,S)=>({u_matrix:_,u_world:g,u_emissive_strength:d,u_ground_shadow_factor:S}),gy=(_,d,g,S,E,R,L=0)=>Object.assign(Qb(_,d,g,S,R,L),{u_world:E}),QI=(_,d)=>({u_matrix:_,u_depth_bias:d}),JI=(_,d)=>({u_matrix:_,u_ground_shadow_factor:d}),ov=(_,d,g,S,E)=>({u_matrix:_,u_camera_pos:[d[0],d[1],d[2]],u_depth_bias:g,u_height_scale:S,u_reset_depth:E}),Jb=(_,d,g)=>({u_image:_,u_opacity:d,u_blend_mode:g}),em=(_,d,g,S,E,R,L,B,U,W=[0,0,1])=>({u_matrix:_,u_normal_matrix:d,u_opacity:g,u_faux_facade_ao_intensity:S,u_camera_pos:E,u_tile_to_meter:R,u_facade_emissive_chance:L,u_flood_light_color:B,u_flood_light_intensity:U,u_front_cutoff_params:W}),ew=_=>({u_matrix:_}),tw=_=>({u_matrix:_}),eP=(_,d,g,S,E,R,L,B)=>{const U=a.an/R.tileSize;return{u_matrix:_,u_inv_rot_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(B),u_extrude_scale:[g.pixelsToGLUnits[0]/U,g.pixelsToGLUnits[1]/U],u_zoom_transition:S,u_tile_id:L,u_merc_center:E}},tm=(_,d,g,S)=>({u_matrix:_,u_inv_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(S),u_viewport_size:[g.width,g.height]}),lv=(_,d,g=1)=>({u_matrix:_,u_color:d,u_overlay:0,u_overlay_scale:g}),rw=a.bb(),tP=(_,d,g,S,E,R,L)=>{const B=_.transform,U=B.projection.name==="globe",W=U?a.dH(B.zoom,d.canonical)*B._pixelsPerMercatorPixel:a.aA(g,1,R),Z={u_matrix:d.projMatrix,u_extrude_scale:W,u_intensity:L,u_inv_rot_matrix:rw,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(U){Z.u_inv_rot_matrix=S,Z.u_merc_center=E,Z.u_tile_id=[d.canonical.x,d.canonical.y,1<({u_matrix:d,u_normalize_matrix:g,u_globe_matrix:S,u_merc_matrix:E,u_grid_matrix:R,u_tl_parent:L,u_scale_parent:Z,u_fade_t:ne.mix,u_opacity:ne.opacity*re.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:re.paint.get("raster-brightness-min"),u_brightness_high:re.paint.get("raster-brightness-max"),u_saturation_factor:a.dJ(re.paint.get("raster-saturation")),u_contrast_factor:a.dI(re.paint.get("raster-contrast")),u_spin_weights:nP(re.paint.get("raster-hue-rotate")),u_perspective_transform:ie,u_raster_elevation:ce,u_zoom_transition:B,u_merc_center:U,u_cutoff_params:W,u_colorization_mix:yE(a.dK,be,Re),u_colorization_offset:nw(a.dK,_e,Re),u_color_ramp:le,u_texture_offset:[je/(Me+2*je),Me/(Me+2*je)],u_texture_res:[Me+2*je,Me+2*je],u_emissive_strength:Xe,u_zbias_factor:xE(_)});function nP(_){_*=Math.PI/180;const d=Math.sin(_),g=Math.cos(_);return[(2*g+1)/3,(-Math.sqrt(3)*d-g+1)/3,(Math.sqrt(3)*d-g+1)/3]}const Jd=.05,wB=(_,d,g,S,E,R,L,B,U,W,Z,ne)=>({u_matrix:_,u_normalize_matrix:d,u_globe_matrix:g,u_merc_matrix:S,u_grid_matrix:E,u_tl_parent:R,u_scale_parent:W,u_fade_t:Z.mix,u_opacity:Z.opacity,u_image0:0,u_image1:1,u_raster_elevation:ne,u_zoom_transition:L,u_merc_center:B,u_cutoff_params:U}),SB=(_,d,g,S,E,R,L,B,U,W)=>({u_particle_texture:_,u_particle_texture_side_len:d,u_tile_offset:g,u_velocity:S,u_color_ramp:R,u_velocity_res:E,u_max_speed:L,u_uv_offset:B,u_data_scale:[255*U[0],255*U[1]],u_data_offset:W,u_particle_pos_scale:1.1,u_particle_pos_offset:[Jd,Jd]}),sP=(_,d,g,S,E,R,L,B,U,W)=>({u_particle_texture:_,u_particle_texture_side_len:d,u_velocity:g,u_velocity_res:S,u_max_speed:E,u_speed_factor:R,u_reset_rate:L,u_rand_seed:Math.random(),u_uv_offset:B,u_data_scale:[255*U[0],255*U[1]],u_data_offset:W,u_particle_pos_scale:1.1,u_particle_pos_offset:[Jd,Jd]}),iP=a.bb(),sw=(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re,Me,je,Xe,$e,Ke)=>{const De=E.transform,Be={u_is_size_zoom_constant:+(_==="constant"||_==="source"),u_is_size_feature_constant:+(_==="constant"||_==="camera"),u_size_t:d?d.uSizeT:0,u_size:d?d.uSize:0,u_camera_to_center_distance:De.getCameraToCenterDistance(Re),u_rotate_symbol:+g,u_aspect_ratio:De.width/De.height,u_fade_change:E.options.fadeDuration?E.symbolFadeChange:1,u_matrix:R,u_label_plane_matrix:L,u_coord_matrix:B,u_is_text:+W,u_elevation_from_sea:U?1:0,u_pitch_with_map:+S,u_texsize:Z,u_texsize_icon:ne,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:iP,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:iP,u_up_vector:[0,-1,0],u_color_adj_mat:Xe,u_icon_transition:$e||0,u_gamma_scale:S?E.transform.getCameraToCenterDistance(Re)*Math.cos(E.terrain?0:E.transform._pitch):1,u_device_pixel_ratio:a.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Ke||1,u_ground_shadow_factor:Me,u_inv_matrix:a.b7(a.bb(),L),u_normal_scale:je,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 Re.name==="globe"&&(Be.u_tile_id=[ie.canonical.x,ie.canonical.y,1<({u_matrix:_,u_emissive_strength:d,u_opacity:g,u_color:S}),rm=(_,d,g,S,E,R,L,B,U)=>Object.assign(function(W,Z,ne,re,ie,ce){const{width:le,height:be}=re.imageManager.getPixelSize(Z),_e=Math.pow(2,ce.tileID.overscaledZ),Re=ce.tileSize*Math.pow(2,re.transform.tileZoom)/_e,Me=Re*(ce.tileID.canonical.x+ce.tileID.wrap*_e),je=Re*ce.tileID.canonical.y;return{u_image:0,u_pattern_tl:ne.tl,u_pattern_br:ne.br,u_texsize:[le,be],u_pattern_size:ne.displaySize,u_pattern_units_to_pixels:ie?[re.transform.width,-1*re.transform.height]:[1/a.aA(ce,1,re.transform.tileZoom),1/a.aA(ce,1,re.transform.tileZoom)],u_pixel_coord_upper:[Me>>16,je>>16],u_pixel_coord_lower:[65535&Me,65535&je]}}(0,R,L,S,B,U),{u_matrix:_,u_emissive_strength:d,u_opacity:g}),yy=new Float32Array(a.b9([])),Np=(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie=[0,0,0],ce,le,be)=>{const _e=E.style.light,Re=_e.properties.get("position"),Me=[-Re.x,-Re.y,Re.z],je=a.dE();_e.properties.get("anchor")==="viewport"&&(a.dF(je,-E.transform.angle),a.dG(Me,Me,je));const Xe=Z.alphaMode==="MASK",$e=_e.properties.get("color").toNonPremultipliedRenderColor(null),Ke=re.paint.get("model-ambient-occlusion-intensity"),De=re.paint.get("model-color").constantOr(a.aq.white).toNonPremultipliedRenderColor(null);return De.a=re.paint.get("model-color-mix-intensity").constantOr(0),be&&(De.r=be[0],De.g=be[1],De.b=be[2],De.a=be[3]),le&&(De.r=le.color.r,De.g=le.color.g,De.b=le.color.b,De.a=le.colorMix,ne=le.emissionStrength,R*=le.opacity),{u_matrix:_,u_lighting_matrix:d,u_normal_matrix:g,u_node_matrix:S||yy,u_lightpos:Me,u_lightintensity:_e.properties.get("intensity"),u_lightcolor:[$e.r,$e.g,$e.b],u_camera_pos:ie,u_opacity:R,u_baseTextureIsAlpha:0,u_alphaMask:+Xe,u_alphaCutoff:Z.alphaCutoff,u_baseColorFactor:L.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:B.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:U,u_roughnessFactor:W,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:ne,u_occlusionTextureTransform:ce||[0,0,0,0]}},vE=(_,d=yy,g=yy)=>({u_matrix:_,u_instance:d,u_node_matrix:g}),iw={fillExtrusion:_=>({u_matrix:new a.b$(_),u_lightpos:new a.bY(_),u_lightintensity:new a.bZ(_),u_lightcolor:new a.bY(_),u_vertical_gradient:new a.bZ(_),u_opacity:new a.bZ(_),u_edge_radius:new a.bZ(_),u_width_scale:new a.bZ(_),u_ao:new a.b_(_),u_height_type:new a.bX(_),u_base_type:new a.bX(_),u_tile_id:new a.bY(_),u_zoom_transition:new a.bZ(_),u_inv_rot_matrix:new a.b$(_),u_merc_center:new a.b_(_),u_up_dir:new a.bY(_),u_height_lift:new a.bZ(_),u_flood_light_color:new a.bY(_),u_vertical_scale:new a.bZ(_),u_flood_light_intensity:new a.bZ(_),u_ground_shadow_factor:new a.bY(_),u_front_cutoff_params:new a.bY(_)}),fillExtrusionDepth:_=>({u_matrix:new a.b$(_),u_edge_radius:new a.bZ(_),u_width_scale:new a.bZ(_),u_vertical_scale:new a.bZ(_),u_height_type:new a.bX(_),u_base_type:new a.bX(_)}),fillExtrusionPattern:_=>({u_matrix:new a.b$(_),u_lightpos:new a.bY(_),u_lightintensity:new a.bZ(_),u_lightcolor:new a.bY(_),u_vertical_gradient:new a.bZ(_),u_height_factor:new a.bZ(_),u_edge_radius:new a.bZ(_),u_width_scale:new a.bZ(_),u_ao:new a.b_(_),u_height_type:new a.bX(_),u_base_type:new a.bX(_),u_tile_id:new a.bY(_),u_zoom_transition:new a.bZ(_),u_inv_rot_matrix:new a.b$(_),u_merc_center:new a.b_(_),u_up_dir:new a.bY(_),u_height_lift:new a.bZ(_),u_image:new a.bX(_),u_texsize:new a.b_(_),u_pixel_coord_upper:new a.b_(_),u_pixel_coord_lower:new a.b_(_),u_tile_units_to_pixels:new a.bZ(_),u_opacity:new a.bZ(_),u_pattern_transition:new a.bZ(_)}),fillExtrusionGroundEffect:_=>({u_matrix:new a.b$(_),u_opacity:new a.bZ(_),u_ao_pass:new a.bZ(_),u_meter_to_tile:new a.bZ(_),u_ao:new a.b_(_),u_flood_light_intensity:new a.bZ(_),u_flood_light_color:new a.bY(_),u_attenuation:new a.bZ(_),u_edge_radius:new a.bZ(_),u_fb:new a.bX(_),u_fb_size:new a.bZ(_),u_dynamic_offset:new a.bZ(_)}),fill:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_ground_shadow_factor:new a.bY(_)}),fillPattern:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_image:new a.bX(_),u_texsize:new a.b_(_),u_pixel_coord_upper:new a.b_(_),u_pixel_coord_lower:new a.b_(_),u_tile_units_to_pixels:new a.bZ(_),u_ground_shadow_factor:new a.bY(_),u_pattern_transition:new a.bZ(_)}),fillOutline:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_world:new a.b_(_),u_ground_shadow_factor:new a.bY(_)}),fillOutlinePattern:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_world:new a.b_(_),u_image:new a.bX(_),u_texsize:new a.b_(_),u_pixel_coord_upper:new a.b_(_),u_pixel_coord_lower:new a.b_(_),u_tile_units_to_pixels:new a.bZ(_),u_ground_shadow_factor:new a.bY(_),u_pattern_transition:new a.bZ(_)}),lineBlendComposite:_=>({u_image:new a.bX(_),u_opacity:new a.bZ(_),u_blend_mode:new a.bX(_)}),building:_=>({u_matrix:new a.b$(_),u_normal_matrix:new a.b$(_),u_opacity:new a.bZ(_),u_faux_facade_ao_intensity:new a.bZ(_),u_camera_pos:new a.bY(_),u_tile_to_meter:new a.bZ(_),u_facade_emissive_chance:new a.bZ(_),u_flood_light_color:new a.bY(_),u_flood_light_intensity:new a.bZ(_),u_front_cutoff_params:new a.bY(_)}),buildingBloom:_=>({u_matrix:new a.b$(_)}),buildingDepth:_=>({u_matrix:new a.b$(_)}),elevatedStructuresDepth:_=>({u_matrix:new a.b$(_),u_depth_bias:new a.bZ(_)}),elevatedStructures:_=>({u_matrix:new a.b$(_),u_ground_shadow_factor:new a.bY(_)}),elevatedStructuresDepthReconstruct:_=>({u_matrix:new a.b$(_),u_camera_pos:new a.bY(_),u_depth_bias:new a.bZ(_),u_height_scale:new a.bZ(_),u_reset_depth:new a.bZ(_)}),circle:a.dO,collisionBox:_=>({u_matrix:new a.b$(_),u_inv_rot_matrix:new a.b$(_),u_camera_to_center_distance:new a.bZ(_),u_extrude_scale:new a.b_(_),u_zoom_transition:new a.bZ(_),u_merc_center:new a.b_(_),u_tile_id:new a.bY(_)}),collisionCircle:_=>({u_matrix:new a.b$(_),u_inv_matrix:new a.b$(_),u_camera_to_center_distance:new a.bZ(_),u_viewport_size:new a.b_(_)}),debug:_=>({u_color:new a.dl(_),u_matrix:new a.b$(_),u_overlay:new a.bX(_),u_overlay_scale:new a.bZ(_)}),clippingMask:_=>({u_matrix:new a.b$(_)}),heatmap:_=>({u_extrude_scale:new a.bZ(_),u_intensity:new a.bZ(_),u_matrix:new a.b$(_),u_inv_rot_matrix:new a.b$(_),u_merc_center:new a.b_(_),u_tile_id:new a.bY(_),u_zoom_transition:new a.bZ(_),u_up_dir:new a.bY(_)}),heatmapTexture:_=>({u_image:new a.bX(_),u_color_ramp:new a.bX(_),u_opacity:new a.bZ(_)}),hillshade:_=>({u_matrix:new a.b$(_),u_image:new a.bX(_),u_latrange:new a.b_(_),u_light:new a.b_(_),u_shadow:new a.dl(_),u_highlight:new a.dl(_),u_emissive_strength:new a.bZ(_),u_accent:new a.dl(_)}),hillshadePrepare:_=>({u_matrix:new a.b$(_),u_image:new a.bX(_),u_dimension:new a.b_(_),u_zoom:new a.bZ(_)}),line:a.dN,linePattern:a.dM,raster:_=>({u_matrix:new a.b$(_),u_normalize_matrix:new a.b$(_),u_globe_matrix:new a.b$(_),u_merc_matrix:new a.b$(_),u_grid_matrix:new a.dm(_),u_tl_parent:new a.b_(_),u_scale_parent:new a.bZ(_),u_fade_t:new a.bZ(_),u_opacity:new a.bZ(_),u_image0:new a.bX(_),u_image1:new a.bX(_),u_brightness_low:new a.bZ(_),u_brightness_high:new a.bZ(_),u_saturation_factor:new a.bZ(_),u_contrast_factor:new a.bZ(_),u_spin_weights:new a.bY(_),u_perspective_transform:new a.b_(_),u_raster_elevation:new a.bZ(_),u_zoom_transition:new a.bZ(_),u_merc_center:new a.b_(_),u_cutoff_params:new a.cO(_),u_colorization_mix:new a.cO(_),u_colorization_offset:new a.bZ(_),u_color_ramp:new a.bX(_),u_texture_offset:new a.b_(_),u_texture_res:new a.b_(_),u_emissive_strength:new a.bZ(_),u_zbias_factor:new a.bZ(_)}),rasterParticle:_=>({u_matrix:new a.b$(_),u_normalize_matrix:new a.b$(_),u_globe_matrix:new a.b$(_),u_merc_matrix:new a.b$(_),u_grid_matrix:new a.dm(_),u_tl_parent:new a.b_(_),u_scale_parent:new a.bZ(_),u_fade_t:new a.bZ(_),u_opacity:new a.bZ(_),u_image0:new a.bX(_),u_image1:new a.bX(_),u_raster_elevation:new a.bZ(_),u_zoom_transition:new a.bZ(_),u_merc_center:new a.b_(_),u_cutoff_params:new a.cO(_)}),rasterParticleTexture:_=>({u_texture:new a.bX(_),u_opacity:new a.bZ(_)}),rasterParticleDraw:_=>({u_particle_texture:new a.bX(_),u_particle_texture_side_len:new a.bZ(_),u_tile_offset:new a.b_(_),u_velocity:new a.bX(_),u_color_ramp:new a.bX(_),u_velocity_res:new a.b_(_),u_max_speed:new a.bZ(_),u_uv_offset:new a.b_(_),u_data_scale:new a.b_(_),u_data_offset:new a.bZ(_),u_particle_pos_scale:new a.bZ(_),u_particle_pos_offset:new a.b_(_)}),rasterParticleUpdate:_=>({u_particle_texture:new a.bX(_),u_particle_texture_side_len:new a.bZ(_),u_velocity:new a.bX(_),u_velocity_res:new a.b_(_),u_max_speed:new a.bZ(_),u_speed_factor:new a.bZ(_),u_reset_rate:new a.bZ(_),u_rand_seed:new a.bZ(_),u_uv_offset:new a.b_(_),u_data_scale:new a.b_(_),u_data_offset:new a.bZ(_),u_particle_pos_scale:new a.bZ(_),u_particle_pos_offset:new a.b_(_)}),symbol:_=>({u_is_size_zoom_constant:new a.bX(_),u_is_size_feature_constant:new a.bX(_),u_size_t:new a.bZ(_),u_size:new a.bZ(_),u_camera_to_center_distance:new a.bZ(_),u_rotate_symbol:new a.bX(_),u_aspect_ratio:new a.bZ(_),u_fade_change:new a.bZ(_),u_matrix:new a.b$(_),u_label_plane_matrix:new a.b$(_),u_coord_matrix:new a.b$(_),u_is_text:new a.bX(_),u_elevation_from_sea:new a.bX(_),u_pitch_with_map:new a.bX(_),u_texsize:new a.b_(_),u_texsize_icon:new a.b_(_),u_texture:new a.bX(_),u_texture_icon:new a.bX(_),u_gamma_scale:new a.bZ(_),u_device_pixel_ratio:new a.bZ(_),u_tile_id:new a.bY(_),u_zoom_transition:new a.bZ(_),u_inv_rot_matrix:new a.b$(_),u_merc_center:new a.b_(_),u_camera_forward:new a.bY(_),u_tile_matrix:new a.b$(_),u_up_vector:new a.bY(_),u_ecef_origin:new a.bY(_),u_is_halo:new a.bX(_),u_icon_transition:new a.bZ(_),u_color_adj_mat:new a.b$(_),u_scale_factor:new a.bZ(_),u_ground_shadow_factor:new a.bY(_),u_inv_matrix:new a.b$(_),u_normal_scale:new a.bZ(_),u_lutTexture:new a.bX(_),u_zoom:new a.bZ(_),u_spp_fill_np_color:new a.cO(_),u_spp_halo_np_color:new a.cO(_),u_spp_opacity:new a.bZ(_),u_spp_halo_width:new a.bZ(_),u_spp_halo_blur:new a.bZ(_),u_spp_emissive_strength:new a.bZ(_),u_spp_occlusion_opacity:new a.bZ(_),u_spp_z_offset:new a.bZ(_),u_spp_translate_rotation:new a.b_(_)}),background:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_opacity:new a.bZ(_),u_color:new a.dl(_)}),backgroundPattern:_=>({u_matrix:new a.b$(_),u_emissive_strength:new a.bZ(_),u_opacity:new a.bZ(_),u_image:new a.bX(_),u_pattern_tl:new a.b_(_),u_pattern_br:new a.b_(_),u_texsize:new a.b_(_),u_pattern_size:new a.b_(_),u_pixel_coord_upper:new a.b_(_),u_pixel_coord_lower:new a.b_(_),u_pattern_units_to_pixels:new a.b_(_)}),terrainRaster:_=>({u_matrix:new a.b$(_),u_image0:new a.bX(_),u_image1:new a.bX(_),u_skirt_height:new a.bZ(_),u_ground_shadow_factor:new a.bY(_),u_emissive_texture_available:new a.bZ(_)}),skybox:_=>({u_matrix:new a.b$(_),u_sun_direction:new a.bY(_),u_cubemap:new a.bX(_),u_opacity:new a.bZ(_),u_temporal_offset:new a.bZ(_)}),skyboxGradient:_=>({u_matrix:new a.b$(_),u_color_ramp:new a.bX(_),u_center_direction:new a.bY(_),u_radius:new a.bZ(_),u_opacity:new a.bZ(_),u_temporal_offset:new a.bZ(_)}),skyboxCapture:_=>({u_matrix_3f:new a.dm(_),u_sun_direction:new a.bY(_),u_sun_intensity:new a.bZ(_),u_color_tint_r:new a.cO(_),u_color_tint_m:new a.cO(_),u_luminance:new a.bZ(_)}),globeRaster:_=>({u_proj_matrix:new a.b$(_),u_globe_matrix:new a.b$(_),u_normalize_matrix:new a.b$(_),u_merc_matrix:new a.b$(_),u_zoom_transition:new a.bZ(_),u_merc_center:new a.b_(_),u_image0:new a.bX(_),u_image1:new a.bX(_),u_grid_matrix:new a.dm(_),u_skirt_height:new a.bZ(_),u_far_z_cutoff:new a.bZ(_),u_frustum_tl:new a.bY(_),u_frustum_tr:new a.bY(_),u_frustum_br:new a.bY(_),u_frustum_bl:new a.bY(_),u_globe_pos:new a.bY(_),u_globe_radius:new a.bZ(_),u_viewport:new a.b_(_),u_emissive_texture_available:new a.bZ(_)}),globeAtmosphere:_=>({u_frustum_tl:new a.bY(_),u_frustum_tr:new a.bY(_),u_frustum_br:new a.bY(_),u_frustum_bl:new a.bY(_),u_horizon:new a.bZ(_),u_transition:new a.bZ(_),u_fadeout_range:new a.bZ(_),u_atmosphere_fog_color:new a.cO(_),u_high_color:new a.cO(_),u_space_color:new a.cO(_),u_temporal_offset:new a.bZ(_),u_horizon_angle:new a.bZ(_)}),model:_=>({u_matrix:new a.b$(_),u_lighting_matrix:new a.b$(_),u_normal_matrix:new a.b$(_),u_node_matrix:new a.b$(_),u_lightpos:new a.bY(_),u_lightintensity:new a.bZ(_),u_lightcolor:new a.bY(_),u_camera_pos:new a.bY(_),u_opacity:new a.bZ(_),u_baseColorFactor:new a.cO(_),u_emissiveFactor:new a.cO(_),u_metallicFactor:new a.bZ(_),u_roughnessFactor:new a.bZ(_),u_baseTextureIsAlpha:new a.bX(_),u_alphaMask:new a.bX(_),u_alphaCutoff:new a.bZ(_),u_baseColorTexture:new a.bX(_),u_metallicRoughnessTexture:new a.bX(_),u_normalTexture:new a.bX(_),u_occlusionTexture:new a.bX(_),u_emissionTexture:new a.bX(_),u_lutTexture:new a.bX(_),u_color_mix:new a.cO(_),u_aoIntensity:new a.bZ(_),u_emissive_strength:new a.bZ(_),u_occlusionTextureTransform:new a.cO(_)}),modelDepth:_=>({u_matrix:new a.b$(_),u_instance:new a.b$(_),u_node_matrix:new a.b$(_)}),groundShadow:_=>({u_matrix:new a.b$(_),u_ground_shadow_factor:new a.bY(_)}),stars:_=>({u_matrix:new a.b$(_),u_up:new a.bY(_),u_right:new a.bY(_),u_intensity_multiplier:new a.bZ(_)}),snowParticle:_=>({u_modelview:new a.b$(_),u_projection:new a.b$(_),u_time:new a.bZ(_),u_cam_pos:new a.bY(_),u_velocityConeAperture:new a.bZ(_),u_velocity:new a.bZ(_),u_horizontalOscillationRadius:new a.bZ(_),u_horizontalOscillationRate:new a.bZ(_),u_boxSize:new a.bZ(_),u_billboardSize:new a.bZ(_),u_simpleShapeParameters:new a.b_(_),u_screenSize:new a.b_(_),u_thinningCenterPos:new a.b_(_),u_thinningShape:new a.bY(_),u_thinningAffectedRatio:new a.bZ(_),u_thinningParticleOffset:new a.bZ(_),u_particleColor:new a.cO(_),u_direction:new a.bY(_)}),rainParticle:_=>({u_modelview:new a.b$(_),u_projection:new a.b$(_),u_time:new a.bZ(_),u_cam_pos:new a.bY(_),u_texScreen:new a.bX(_),u_velocityConeAperture:new a.bZ(_),u_velocity:new a.bZ(_),u_boxSize:new a.bZ(_),u_rainDropletSize:new a.b_(_),u_distortionStrength:new a.bZ(_),u_rainDirection:new a.bY(_),u_color:new a.cO(_),u_screenSize:new a.b_(_),u_thinningCenterPos:new a.b_(_),u_thinningShape:new a.bY(_),u_thinningAffectedRatio:new a.bZ(_),u_thinningParticleOffset:new a.bZ(_),u_shapeDirectionalPower:new a.bZ(_),u_shapeNormalPower:new a.bZ(_),u_mode:new a.bZ(_)}),vignette:_=>({u_vignetteShape:new a.bY(_),u_vignetteColor:new a.cO(_)}),occlusion:_=>({u_matrix:new a.b$(_),u_anchorPos:new a.bY(_),u_screenSizePx:new a.b_(_),u_occluderSizePx:new a.b_(_),u_color:new a.cO(_)})};class pd{constructor(d,g,S,E){this.id=pd.uniqueIdxCounter,pd.uniqueIdxCounter++,this.context=d;const R=d.gl;this.buffer=R.createBuffer(),this.dynamicDraw=!!S,this.context.unbindVAO(),d.bindElementBuffer.set(this.buffer),R.bufferData(R.ELEMENT_ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?R.DYNAMIC_DRAW:R.STATIC_DRAW),this.dynamicDraw||E||g.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(d){this.id=pd.uniqueIdxCounter,pd.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)}}pd.uniqueIdxCounter=0;const _E={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class aP{constructor(d,g,S,E,R,L){this.length=g.length,this.attributes=S,this.itemSize=g.bytesPerElement,this.dynamicDraw=E,this.instanceCount=L,this.context=d;const B=d.gl;this.buffer=B.createBuffer(),d.bindVertexBuffer.set(this.buffer),B.bufferData(B.ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?B.DYNAMIC_DRAW:B.STATIC_DRAW),this.dynamicDraw||R||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 S of this.attributes){const E=g.getAttributeLocation(d,S.name);E!==-1&&d.enableVertexAttribArray(E)}}setVertexAttribPointers(d,g,S){for(const E of this.attributes){const R=g.getAttributeLocation(d,E.name);if(R!==-1){const L=E.offset+this.itemSize*(S||0);E.type==="Float32"?d.vertexAttribPointer(R,E.components,d.FLOAT,!1,this.itemSize,L):d.vertexAttribIPointer(R,E.components,d[_E[E.type]],this.itemSize,L)}}}setVertexAttribDivisor(d,g,S){for(let E=0;E0&&d.vertexAttribDivisor(R,S)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class uv{constructor(d,g,S,E,R){this.context=d,this.width=g,this.height=S;const L=this.framebuffer=d.gl.createFramebuffer();E>0&&(this.colorAttachment0=new my(d,L,0)),E>1&&(this.colorAttachment1=new my(d,L,1)),R&&(this.depthAttachmentType=R,this.depthAttachment=R==="renderbuffer"?new fE(d,L):new HI(d,L))}static createWithTexture(d,g,S,E,R){const L=d.gl;if(d.activeTexture.set(L.TEXTURE1),d.viewport.set([0,0,S,E]),g&&g.width===S&&g.height===E)return L.bindTexture(L.TEXTURE_2D,g.colorAttachment0.get()),d.bindFramebuffer.set(g.framebuffer),g;g&&g.destroy();const B=new a.T(d,{width:S,height:E,data:null},d.extRenderToTextureHalfFloat?d.gl.RGBA16F:d.gl.RGBA8);B.bind(L.LINEAR,L.CLAMP_TO_EDGE);const U=d.createFramebuffer(S,E,1,null);if(U.colorAttachment0.set(B.texture),R){const W=d.createRenderbuffer(L.DEPTH24_STENCIL8,S,E);d.bindFramebuffer.set(U.framebuffer),L.framebufferRenderbuffer(L.FRAMEBUFFER,L.DEPTH_STENCIL_ATTACHMENT,L.RENDERBUFFER,W),U._stencilRbo=W}return U}createColorAttachment(d,g){g===0?this.colorAttachment0=new my(d,this.framebuffer,0):g===1&&(this.colorAttachment1=new my(d,this.framebuffer,1))}removeColorAttachment(d,g){const S=this.context.gl;let E;g===0?(E=this.colorAttachment0.get(),this.colorAttachment0=void 0):g===1&&(E=this.colorAttachment1.get(),this.colorAttachment1=void 0),E&&S.deleteTexture(E)}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 xy{constructor(d,g){this.gl=d,this.clearColor=new FI(this),this.clearDepth=new fB(this),this.clearStencil=new zb(this),this.colorMask=new mB(this),this.depthMask=new BI(this),this.stencilMask=new oE(this),this.stencilFunc=new Ub(this),this.stencilOp=new lE(this),this.stencilTest=new Ep(this),this.depthRange=new kp(this),this.depthTest=new dy(this),this.depthFunc=new Qd(this),this.blend=new $I(this),this.blendFunc=new cE(this),this.blendColor=new zI(this),this.blendEquation=new hy(this),this.cullFace=new Vb(this),this.cullFaceSide=new qb(this),this.frontFace=new uE(this),this.program=new Gb(this),this.activeTexture=new J0(this),this.viewport=new UI(this),this.bindFramebuffer=new VI(this),this.bindRenderbuffer=new qI(this),this.bindTexture=new fy(this),this.bindVertexBuffer=new GI(this),this.bindElementBuffer=new pB(this),this.bindVertexArrayOES=new gB(this),this.pixelStoreUnpack=new yB(this),this.pixelStoreUnpackPremultiplyAlpha=new dE(this),this.pixelStoreUnpackFlipY=new hE(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,S){return new pd(this,d,g,S)}createVertexBuffer(d,g,S,E,R){return new aP(this,d,g,S,E,R)}createRenderbuffer(d,g,S){const E=this.gl,R=E.createRenderbuffer();return this.bindRenderbuffer.set(R),E.renderbufferStorage(E.RENDERBUFFER,d,g,S),this.bindRenderbuffer.set(null),R}createFramebuffer(d,g,S,E){return new uv(this,d,g,S,E)}clear({color:d,depth:g,stencil:S,colorMask:E}){const R=this.gl;let L=0;d&&(L|=R.COLOR_BUFFER_BIT,this.clearColor.set(d.toNonPremultipliedRenderColor(null)),this.colorMask.set(E||[!0,!0,!0,!0])),g!==void 0&&(L|=R.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(g),this.depthMask.set(!0)),S!==void 0&&(L|=R.STENCIL_BUFFER_BIT,this.clearStencil.set(S),this.stencilMask.set(255)),R.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){a.b6(d.blendFunction,tn.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 Cp;function jr(_,d,g,S,E,R,L){const B=_.context,U=B.gl,W=_.transform,Z=[a.aH(W.center.lng),a.aL(W.center.lat)],ne=g.layout.get("symbol-placement"),re=g.layout.get("text-variable-anchor"),ie=g.layout.get("icon-rotation-alignment")==="map",ce=g.layout.get("text-rotation-alignment")==="map",le=ne!=="point",be=[];let _e=0,Re=0;for(let De=0;De0){const Fr=a.bb(),br=Jt;a.cz(Fr,ot.placementInvProjMatrix,W.glCoordMatrix),a.cz(Fr,Fr,ot.placementViewportMatrix),be.push({circleArray:zt,circleOffset:Re,transform:br,invTransform:Fr,projection:ot.getProjection()}),_e+=zt.length/4,Re=_e}if(!er)continue;_.terrain&&_.terrain.setupElevationDraw(Ge,lr);const Pr=jt?[Be.canonical.x,Be.canonical.y,1<=0&&(ie[Me.associatedIconIndex]={x:Je,y:St,z:pt,angle:_t})}else ny($e,ne)}if(W){re.clear();const Re=_.icon.placedSymbolArray;for(let Me=0;Me{let hn=[0,0,0];if(hs){const si=_.style.directionalLight,Is=_.style.ambientLight;si&&Is&&(hn=fd(_.style,si,Is))}return hn},jn=hs=>{if(_.context.disableSymbolUBO)return;hs.push("USE_PAINT_PROPERTIES_UBO");const hn=Math.floor(_.context.maxUniformBlockSize/4),si=Math.floor(hn/4);hs.push(`MAX_UBO_SIZE_VEC4 ${si}u`)},ln=hs=>{Be.depthOcclusionForSymbolsAndCircles&&(g.hasOcclusionOpacityProperties||_.terrain)&&(hs.push("DEPTH_D24"),hs.push("DEPTH_OCCLUSION"))},ts=hs=>{g.lut&&!$e&&(g.lut.texture||(g.lut.texture=new a.dR(_.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),hs.push("APPLY_LUT_ON_GPU"))},Cs=()=>{const hs=Ge&&g.layout.get("symbol-placement")!=="point",hn=[];ln(hn),ts(hn);const si=hs||dn,Is=zt.elevationType==="road",Yi=_.shadowRenderer,Mn=Is&&Je&&!!Yi&&Yi.enabled,Ms=Kr(Mn),ha=Is&&Je&&!_.terrain?ut:Ut,Do=g.paint.get("icon-image-cross-fade");_.terrainRenderModeElevated()&&Je&&hn.push("PITCH_WITH_MAP_TERRAIN"),Pr&&(hn.push("PROJECTION_GLOBE_VIEW"),si&&hn.push("PROJECTED_POS_ON_VIEWPORT")),Do>0&&zt.hasAnySecondaryIcon&&hn.push("ICON_TRANSITION"),!zt.icon.zOffsetVertexBuffer||Is&&_.terrain||hn.push("Z_OFFSET"),_e===0&&Re===0&&Me===0&&je===1||hn.push("COLOR_ADJUSTMENT"),zt.sdfIcons&&hn.push("RENDER_SDF"),Mn&&hn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Is&&Je&&!_.terrain&&zt.icon.orientationVertexBuffer&&hn.push("ELEVATED_ROADS"),jn(hn);const Sa=Ke.disableSymbolUBO?zt.icon.programConfigurations.get(g.id):null,io=_.getOrCreateProgram("symbol",{config:Sa,defines:hn}),kc=er.imageAtlasTexture?er.imageAtlasTexture.size:[0,0],ys=zt.iconSizeData,Qc=a.bj(ys,Be.zoom),Jc=Je||!Be.isOrthographic,Vs=Kf(br,er.tileID.canonical,Je,Ge,Be,zt.getProjection(),Nr),Ys=ry(br,er.tileID.canonical,Je,Ge,Be,zt.getProjection(),Nr),js=zt.icon.uboBinder&&zt.icon.uboBinder.cachedHeader&&256&zt.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:B,qi=_.translatePosMatrix(Ys,er,js,W,!0),Qo=_.translatePosMatrix(br,er,js,W),Ti=si?dv:Vs,Ac=Ge&&!Je&&!hs;let sm=lr;!jt&&!Be.mercatorFromTransition||Ge||(sm=qh(Be));const Fp=Pr?sm:lr,Bp=g.getColorAdjustmentMatrix(_e,Re,Me,je),Ty=sw(ys.kind,Qc,Ac,Je,_,Qo,Ti,qi,Xe,!1,kc,[0,0],0,Jt,Fr,st,on,Fp,zt.getProjection(),Ms,Tn,Bp,Do,null),Zh=er.imageAtlasTexture?er.imageAtlasTexture:null,sh=g.layout.get("icon-size").constantOr(0)!==1||zt.iconsNeedLinear,jy=zt.sdfIcons||_.options.rotating||_.options.zooming||sh||Jc?De.LINEAR:De.NEAREST,Ql=zt.sdfIcons&&g.paint.get("icon-halo-width").constantOr(1)!==0,im=_.terrain&&Je&&hs?a.b7(a.bb(),Vs):dv;if(hs&&zt.icon){const am=a.bu.getAtTileOffsetFunc(Jt,Be.center.lat,Be.worldSize,zt.getProjection()),om=ud(br,er.tileID.canonical,Je,Ge,Be,zt.getProjection(),Nr),Nw=g.layout.get("icon-size-scale-range"),Ey=a.aC(_.scaleFactor,Nw[0],Nw[1]);Tc(zt,br,_,!1,om,Ys,Je,le,am,Jt,Ey)}return{program:io,buffers:zt.icon,uniformValues:Ty,atlasTexture:Zh,atlasTextureIcon:null,atlasInterpolation:jy,atlasInterpolationIcon:null,isSDF:zt.sdfIcons,hasHalo:Ql,depthMode:ha,tile:er,renderWithShadows:Mn,labelPlaneMatrixInv:im}},li=()=>{const hs=ot&&g.layout.get("symbol-placement")!=="point",hn=[],si=hs||_t||dn,Is=zt.elevationType==="road",Yi=_.shadowRenderer,Mn=Is&&St&&!!Yi&&Yi.enabled,Ms=Kr(Mn),ha=Is&&St&&!_.terrain?ut:Ut;_.terrainRenderModeElevated()&&St&&hn.push("PITCH_WITH_MAP_TERRAIN"),Pr&&(hn.push("PROJECTION_GLOBE_VIEW"),si&&hn.push("PROJECTED_POS_ON_VIEWPORT")),!zt.text.zOffsetVertexBuffer||Is&&_.terrain||hn.push("Z_OFFSET"),zt.iconsInText&&hn.push("RENDER_TEXT_AND_SYMBOL"),hn.push("RENDER_SDF"),Mn&&hn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Is&&St&&!_.terrain&&zt.text.orientationVertexBuffer&&hn.push("ELEVATED_ROADS"),ln(hn),jn(hn);const Do=Ke.disableSymbolUBO?zt.text.programConfigurations.get(g.id):null,Sa=_.getOrCreateProgram("symbol",{config:Do,defines:hn});let io,kc=[0,0],ys=null;const Qc=zt.textSizeData;zt.iconsInText&&(kc=er.imageAtlasTexture?er.imageAtlasTexture.size:[0,0],ys=er.imageAtlasTexture?er.imageAtlasTexture:null,io=St||!Be.isOrthographic||_.options.rotating||_.options.zooming||Qc.kind==="composite"||Qc.kind==="camera"?De.LINEAR:De.NEAREST);const Jc=er.glyphAtlasTexture?er.glyphAtlasTexture.size:[0,0],Vs=g.layout.get("text-size-scale-range"),Ys=a.aC(_.scaleFactor,Vs[0],Vs[1]),js=a.bj(Qc,Be.zoom,Ys),qi=Kf(br,er.tileID.canonical,St,ot,Be,zt.getProjection(),Nr),Qo=ry(br,er.tileID.canonical,St,ot,Be,zt.getProjection(),Nr),Ti=zt.text.uboBinder&&zt.text.uboBinder.cachedHeader&&256&zt.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:U,Ac=_.translatePosMatrix(Qo,er,Ti,Z,!0),sm=_.translatePosMatrix(br,er,Ti,Z),Fp=si?dv:qi,Bp=ot&&!St&&!hs;let Ty=lr;!jt&&!Be.mercatorFromTransition||ot||(Ty=qh(Be));const Zh=sw(Qc.kind,js,Bp,St,_,sm,Fp,Ac,Xe,!0,Jc,kc,0,Jt,Fr,st,on,Pr?Ty:lr,zt.getProjection(),Ms,Tn,null,null,Ys),sh=er.glyphAtlasTexture?er.glyphAtlasTexture:null,jy=De.LINEAR,Ql=g.paint.get("text-halo-width").constantOr(1)!==0,im=_.terrain&&St&&hs?a.b7(a.bb(),qi):dv;if(hs&&zt.text){const am=a.bu.getAtTileOffsetFunc(Jt,Be.center.lat,Be.worldSize,zt.getProjection()),om=ud(br,er.tileID.canonical,St,ot,Be,zt.getProjection(),Nr);Tc(zt,br,_,!0,om,Qo,St,be,am,Jt,Ys)}return{program:Sa,buffers:zt.text,uniformValues:Zh,atlasTexture:sh,atlasTextureIcon:ys,atlasInterpolation:jy,atlasInterpolationIcon:io,isSDF:!0,hasHalo:Ql,depthMode:ha,tile:er,renderWithShadows:Mn,labelPlaneMatrixInv:im}},Fs=zt.icon.segments.get().length,ds=zt.text.segments.get().length,_n=Fs&&!L.onlyText?Cs():null,bn=ds&&!L.onlyIcons?li():null,Bs=g.paint.get("icon-opacity").constantOr(1),mi=g.paint.get("text-opacity").constantOr(1);if(pt&&zt.canOverlap){Ot=!0;const hs=Bs&&!L.onlyText?zt.icon.segments.get():[],hn=mi&&!L.onlyIcons?zt.text.segments.get():[];for(const si of hs)Nt.push({segments:new a.dy([si]),sortKey:si.sortKey,state:_n});for(const si of hn)Nt.push({segments:new a.dy([si]),sortKey:si.sortKey,state:bn})}else L.onlyText||Nt.push({segments:Bs?zt.icon.segments:new a.dy([]),sortKey:0,state:_n}),L.onlyIcons||Nt.push({segments:mi?zt.text.segments:new a.dy([]),sortKey:0,state:bn})}Ot&&Nt.sort((Jt,er)=>Jt.sortKey-er.sortKey);for(const Jt of Nt){const er=Jt.state;if(er)if(_.terrain?_.terrain.setupElevationDraw(er.tile,er.program,{useDepthForOcclusion:Be.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:er.labelPlaneMatrixInv}):_.setupDepthForOcclusion(Be.depthOcclusionForSymbolsAndCircles,er.program),Ke.activeTexture.set(De.TEXTURE0),er.atlasTexture&&er.atlasTexture.bind(er.atlasInterpolation,De.CLAMP_TO_EDGE,!0),er.atlasTextureIcon&&(Ke.activeTexture.set(De.TEXTURE1),er.atlasTextureIcon&&er.atlasTextureIcon.bind(er.atlasInterpolationIcon,De.CLAMP_TO_EDGE,!0)),er.renderWithShadows&&_.shadowRenderer.setupShadows(er.tile.tileID.toUnwrapped(),er.program,"vector-tile"),_.uploadCommonLightUniforms(_.context,er.program),er.hasHalo){const zt=er.uniformValues;zt.u_is_halo=1,ow(er.buffers,Jt.segments,g,_,er.program,er.depthMode,E,R,zt,2),zt.u_is_halo=0}else{if(er.isSDF){const zt=er.uniformValues;er.hasHalo&&(zt.u_is_halo=1,ow(er.buffers,Jt.segments,g,_,er.program,er.depthMode,E,R,zt,1)),zt.u_is_halo=0}ow(er.buffers,Jt.segments,g,_,er.program,er.depthMode,E,R,er.uniformValues,1)}}}function ow(_,d,g,S,E,R,L,B,U,W){const Z=S.context,ne=Z.gl,re=[_.dynamicLayoutVertexBuffer,_.opacityVertexBuffer,_.iconTransitioningVertexBuffer,_.globeExtVertexBuffer,_.zOffsetVertexBuffer,_.orientationVertexBuffer];_.featureIdBuffer&&re.push(_.featureIdBuffer);const ie=_.uboBinder?null:_.programConfigurations.get(g.id);if(_.uboBinder){_.uboBinder.layer=g;const be=S.transform.zoom,_e=S.style.getBrightness?S.style.getBrightness():null,Re=_.uboBinder.getConstantUniformValues(be,_e);U.u_spp_fill_np_color=Re.fill_np_color,U.u_spp_halo_np_color=Re.halo_np_color,U.u_spp_opacity=Re.opacity,U.u_spp_halo_width=Re.halo_width,U.u_spp_halo_blur=Re.halo_blur,U.u_spp_emissive_strength=Re.emissive_strength,U.u_spp_occlusion_opacity=Re.occlusion_opacity,U.u_spp_z_offset=Re.z_offset;const Me=g.paint.get(_.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),je=_.uboBinder.cachedHeader&&256&_.uboBinder.cachedHeader.dataDrivenMask&&Me==="map"?S.transform.angle:0;U.u_spp_translate_rotation=[Math.cos(je),Math.sin(je)]}const{batchIndices:ce,batchSegments:le}=_.getBatchGrouping(d);for(const be of ce){const _e=le.get(be);_.uboBinder&&_.uboBinder.bind(Z,E.program,be),E.draw(S,ne.TRIANGLES,R,L,B,Zr.disabled,U,g.id,_.layoutVertexBuffer,_.indexBuffer,_e,g.paint,S.transform.zoom,ie,re,W)}}function lw(_,d,g,S,E,R){const L=g.paint.get("line-width"),B=g.paint.get("line-emissive-strength").isConstant(),U=g.paint.get("line-emissive-strength").constantOr(0),W=g.paint.get("line-occlusion-opacity"),Z=g.layout.get("line-elevation-reference"),ne=g.layout.get("line-width-unit")==="meters",re=Z==="sea",ie=!(!_.terrain||!_.terrain.enabled),ce=_.context,le=ce.gl;if(g.hasElevatedBuckets&&_.transform.projection.name==="globe")return;const be=g.layout.get("line-cross-slope"),_e=be!==void 0,Re=be<1,Me=E||_.colorModeForDrapableLayerRenderPass(B?U:null),je=_.terrain&&_.terrain.renderingToTexture||R,Xe=je?1:a.o.devicePixelRatio,$e=g.paint.get("line-dasharray"),Ke=$e.constantOr(1),De=g.layout.get("line-cap"),Be=$e.constantOr(null),Ge=De.constantOr(null),ot=g.paint.get("line-pattern"),Je=ot.constantOr(1),St=g.paint.get("line-pattern-cross-fade"),pt=ot.constantOr(null),Ot=g.paint.get("line-opacity").constantOr(1);let Ut=!Je&&Ot!==1||_.depthOcclusion&&W>0&&W<1;const ut=g.paint.get("line-gradient"),st=Je?"linePattern":"line",_t=a.dU(g);let jt;if(je&&_.terrain&&_.terrain.clipOrMaskOverlapStencilType()&&(Ut=!1),W!==0&&_.depthOcclusion){const zt=g.paint._values["line-opacity"];zt&&zt.value&&zt.value.kind==="constant"?jt=zt.value:a.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&&_t.push("VARIABLE_LINE_WIDTH"),je&&(_.emissiveMode!=="dual-source-blending"||B?_.emissiveMode==="mrt-fallback"&&_t.push("USE_MRT1"):_t.push("DUAL_SOURCE_BLENDING"));const Nt={},lr=(zt,Pr,Fr,br,Nr,Jr)=>{for(const dn of zt){const on=d.getTile(dn);if(Je&&!on.patternsLoaded())continue;const Tn=on.getBucket(g);if(!Tn||Tn.elevationType!=="none"&&!Nr||Tn.elevationType==="none"&&Nr)continue;_.prepareDrawTile();const Kr=[...Pr],jn=_.shadowRenderer,ln=Tn.elevationType==="road"&&!!jn&&jn.enabled;let ts=[0,0,0];if(ln){const Mn=_.style.directionalLight,Ms=_.style.ambientLight;Mn&&Ms&&(ts=fd(_.style,Mn,Ms)),Kr.push("RENDER_SHADOWS","NORMAL_OFFSET")}const Cs=Tn.programConfigurations.get(g.id);let li=!1;if(pt&&on.imageAtlas){const Mn=a.dV.from(pt),Ms=Mn.getPrimary().scaleSelf(Xe).toString(),ha=on.imageAtlas.patternPositions.get(Ms),Do=Mn.getSecondary(),Sa=Do?on.imageAtlas.patternPositions.get(Do.scaleSelf(Xe).toString()):null;li=!!ha&&!!Sa,ha&&Cs.setConstantPatternPositions(ha,Sa)}St>0&&(li||Cs.getPatternTransitionVertexBuffer("line-pattern"))&&Kr.push("LINE_PATTERN_TRANSITION"),Tn.elevationGroundScaleVertexBuffer&&Kr.push("ELEVATION_GROUND_SCALE");const Fs=_.isTileAffectedByFog(dn),ds=_.getOrCreateProgram(st,{config:Cs,defines:Kr,overrideFog:Fs});if(!Je&&Be&&Ge&&on.lineAtlas){const Mn=on.lineAtlas.getDash(Be,Ge);Mn&&Cs.setConstantPatternPositions(Mn)}ln&&jn.setupShadows(on.tileID.toUnwrapped(),ds,"vector-tile");let[_n,bn]=g.paint.get("line-trim-offset");(Ge==="round"||Ge==="square")&&_n!==bn&&(_n===0&&(_n-=1),bn===1&&(bn+=1));const Bs=je?dn.projMatrix:null,mi=ne?1/Tn.tileToMeter/a.aA(on,1,_.transform.zoom):1,hs=ne?1/Tn.tileToMeter/a.aA(on,1,Math.floor(_.transform.zoom)):1,hn=Ke?g.paint._values["line-floorwidth"]:null;let si;if(hn&&hn.value.kind==="constant"){const Mn=Tn.zoom;Mn in Nt||(Nt[Mn]=Math.max(.01,g.widthExpression().evaluate({zoom:Mn}))),si=hn.value.value;const Ms=Math.floor(_.transform.zoom);hn.value.value=Nt[Mn]*Math.pow(2,Ms-on.tileID.overscaledZ)}const Is=Je?a.dW(_,on,g,Bs,Xe,mi,hs,[_n,bn],ts,St):a.dX(_,on,g,Bs,Tn.lineClipsArray.length,Xe,mi,hs,[_n,bn],ts);if(ut){const Mn=Tn.gradients[g.id];let Ms=Mn.texture;if(g.gradientVersion!==Mn.version){let ha=256;if(g.stepInterpolant){const Do=d.getSource().maxzoom,Sa=dn.canonical.z===Do?Math.ceil(1<<_.transform.maxZoom-dn.canonical.z):1;ha=a.aC(a.dY(Tn.maxLineLength/a.an*1024*Sa),256,ce.maxTextureSize)}Mn.gradient=a.dZ({expression:g.gradientExpression(),evaluationKey:"lineProgress",resolution:ha,image:Mn.gradient||void 0,clips:Tn.lineClipsArray}),Mn.texture?Mn.texture.update(Mn.gradient):Mn.texture=new a.T(ce,Mn.gradient,le.RGBA8),Mn.version=g.gradientVersion,Ms=Mn.texture}ce.activeTexture.set(le.TEXTURE1),Ms.bind(g.stepInterpolant?le.NEAREST:le.LINEAR,le.CLAMP_TO_EDGE)}Ke&&(ce.activeTexture.set(le.TEXTURE0),on.lineAtlasTexture&&on.lineAtlasTexture.bind(le.LINEAR,le.REPEAT),Cs.updatePaintBuffers()),Je&&(ce.activeTexture.set(le.TEXTURE0),on.imageAtlasTexture&&on.imageAtlasTexture.bind(le.LINEAR,le.CLAMP_TO_EDGE),Cs.updatePaintBuffers()),Nr&&_.terrain.setupElevationDraw(on,ds),_.uploadCommonUniforms(ce,ds,dn.toUnwrapped());const Yi=Mn=>{jt!=null&&(jt.value=Ot*W),ds.draw(_,le.TRIANGLES,Fr,Mn,Me,Zr.disabled,Is,g.id,Tn.layoutVertexBuffer,Tn.indexBuffer,Tn.segments,g.paint,_.transform.zoom,Cs,[Tn.layoutVertexBuffer2,Tn.patternVertexBuffer,Tn.zOffsetVertexBuffer,Tn.elevationGroundScaleVertexBuffer]),jt!=null&&(jt.value=Ot)};if(Ut&&!Nr){const Mn=_.stencilModeForClipping(dn).ref;Mn===0&&je&&ce.clear({stencil:0});const Ms={func:le.EQUAL,mask:255};Is.u_alpha_discard_threshold=.8,Yi(new an(Ms,Mn,255,le.KEEP,le.KEEP,le.INVERT)),Is.u_alpha_discard_threshold=0,Yi(new an(Ms,Mn,255,le.KEEP,le.KEEP,le.KEEP))}else Is.u_alpha_discard_threshold=Ut&&Nr&&Jr?.8:0,Yi(Nr?br:_.stencilModeForClipping(dn));si!==void 0&&(hn.value.value=si)}};let Jt=_.depthModeForSublayer(0,Mr.ReadOnly);const er=new Mr(_.depthOcclusion?le.GREATER:le.LEQUAL,Mr.ReadOnly,_.depthRangeFor3D);if(g.hasNonElevatedBuckets){const zt=!je&&_.terrain;W!==0&&zt?a.w(`Occlusion opacity for layer ${g.id} is supported on terrain only if the layer has line-z-offset enabled.`):zt?a.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${g.id}.`):lr(S,_t,Jt,an.disabled,!1,!0)}if(g.hasElevatedBuckets){Z==="hd-road-markup"?ie||(Jt=er,_t.push("ELEVATED_ROADS")):(_t.push("ELEVATED"),Jt=er,_e&&_t.push(Re?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),re&&_t.push("ELEVATION_REFERENCE_SEA"));const zt=Ut?_.stencilModeFor3D():an.disabled;_.forceTerrainMode=!0,lr(S,_t,Jt,zt,!0,!0),Ut&&lr(S,_t,Jt,zt,!0,!1),_.forceTerrainMode=!1}Ut&&(_.resetStencilClippingMasks(),je&&ce.clear({stencil:0})),W===0||_.depthOcclusion||je||_.layersWithOcclusionOpacity.push(_.currentLayer)}const Gh={additive:{clearColor:new a.aq(0,0,0,0),colorMode:tn.additive,compositeUniformValue:1},multiply:{clearColor:new a.aq(1,1,1,1),colorMode:tn.multiply,compositeUniformValue:0}};function bE(_,d){const g=1<<_.canonical.z,S=(d.x*g-_.canonical.x-_.wrap*g)*a.an,E=(d.y*g-_.canonical.y)*a.an,R=a.d_(d.z,d.y);return a.cQ(S,E,R)}function hv(_,d,g,S,E){if(!g.layout||g.layout.get("fill-elevation-reference")==="none"||g.paint.get("fill-opacity").constantOr(1)===0)return;const R=_.context.gl,L=new Mr(_.context.gl.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D),B=new Mr(_.context.gl.GREATER,Mr.ReadWrite,_.depthRangeFor3D),U=function(ie){let ce=.01;return ie.isOrthographic&&(ce=a.am(1e-4,ce,a.cL(ie.pitch>=Sp?1:ie.pitch/Sp))),2*ce}(_.transform),W=_.transform.getFreeCameraOptions().position,Z="elevatedStructuresDepthReconstruct",ne=_.getOrCreateProgram(Z,{defines:["DEPTH_RECONSTRUCTION"]}),re=_.getOrCreateProgram(Z);for(const ie of S){const ce=d.getTile(ie),le=ce.getBucket(g);if(!le)continue;const be=le.elevatedStructures;if(!be)continue;const _e=le.elevationBufferData.heightRange,Re=bE(ie.toUnwrapped(),W),Me=_.translatePosMatrix(ie.projMatrix,ce,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor"));let je,Xe,$e,Ke;if(E==="initialize"){if(!_e||_e.min>=1||be.depthSegments.segments[0].primitiveLength===0)continue;je=ov(Me,Re,U,1,0),Xe=L,$e=be.depthSegments,Ke=ne}else if(E==="reset"){if(!_e||_e.min>=0||be.maskSegments.segments[0].primitiveLength===0)continue;je=ov(Me,Re,0,0,1),Xe=B,$e=be.maskSegments,Ke=ne}else if(E==="geometry"){if(be.depthSegments.segments[0].primitiveLength===0)continue;je=ov(Me,Re,U,1,0),Xe=L,$e=be.depthSegments,Ke=re}Ke.draw(_,R.TRIANGLES,Xe,an.disabled,tn.disabled,Zr.disabled,je,g.id,be.vertexBuffer,be.indexBuffer,$e,g.paint,_.transform.zoom)}}function fv(_,d,g,S){const{painter:E,sourceCache:R,layer:L,coords:B,colorMode:U,elevationType:W,terrainEnabled:Z,pass:ne}=_,re=E.context.gl,ie=L.paint.get("fill-pattern"),ce=L.paint.get("fill-pattern-cross-fade"),le=ie.constantOr(null);let be=W;W!=="road"||d&&!Z||(be="none");const _e=be==="road",Re=_.painter.shadowRenderer,Me=_e&&!!Re&&Re.enabled,je=new Mr(E.context.gl.LEQUAL,Mr.ReadOnly,E.depthRangeFor3D);let Xe=[0,0,0];if(Me){const Be=E.style.directionalLight,Ge=E.style.ambientLight;Be&&Ge&&(Xe=fd(E.style,Be,Ge))}const $e=ie&&ie.constantOr(1),Ke=E.terrain&&E.terrain.renderingToTexture,De=(Be,Ge)=>{let ot,Je,St,pt,Ot;Ge?(ot=$e&&!L.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",St=re.LINES):(ot=$e?"fillPattern":"fill",St=re.TRIANGLES);for(const Ut of B){const ut=R.getTile(Ut);if($e&&!ut.patternsLoaded())continue;const st=ut.getBucket(L);if(!st)continue;const _t=d?st.elevationBufferData:st.bufferData;if(_t.isEmpty())continue;E.prepareDrawTile();const jt=_t.programConfigurations.get(L.id),Nt=E.isTileAffectedByFog(Ut),lr=[],Jt=[];_e&&(lr.push("ELEVATED_ROADS"),Jt.push(_t.elevatedLayoutVertexBuffer)),Me&&lr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ke&&g&&lr.push("USE_MRT1"),$e&&(E.context.activeTexture.set(re.TEXTURE0),ut.imageAtlasTexture&&ut.imageAtlasTexture.bind(re.LINEAR,re.CLAMP_TO_EDGE),jt.updatePaintBuffers());let er=!1;if(le&&ut.imageAtlas){const Nr=ut.imageAtlas,Jr=a.dV.from(le),dn=Jr.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),on=Jr.getSecondary(),Tn=Nr.patternPositions.get(dn),Kr=on?Nr.patternPositions.get(on.scaleSelf(a.o.devicePixelRatio).toString()):null;er=!!Tn&&!!Kr,Tn&&jt.setConstantPatternPositions(Tn,Kr)}ce>0&&(er||jt.getPatternTransitionVertexBuffer("fill-pattern"))&&lr.push("FILL_PATTERN_TRANSITION");const zt=E.getOrCreateProgram(ot,{config:jt,overrideFog:Nt,defines:lr}),Pr=E.translatePosMatrix(Ut.projMatrix,ut,L.paint.get("fill-translate"),L.paint.get("fill-translate-anchor"));Me&&Re.setupShadows(ut.tileID.toUnwrapped(),zt,"vector-tile");const Fr=L.paint.get("fill-emissive-strength");if(Ge){pt=_t.lineIndexBuffer,Ot=_t.lineSegments;const Nr=E.terrain&&E.terrain.renderingToTexture?E.terrain.drapeBufferSize:[re.drawingBufferWidth,re.drawingBufferHeight];Je=ot==="fillOutlinePattern"&&$e?gy(Pr,Fr,E,ut,Nr,Xe,ce):XI(Pr,Fr,Nr,Xe)}else pt=_t.indexBuffer,Ot=_t.triangleSegments,Je=$e?Qb(Pr,Fr,E,ut,Xe,ce):Xb(Pr,Fr,Xe);E.uploadCommonUniforms(E.context,zt,Ut.toUnwrapped());let br=Be;(W==="road"&&!Z||W==="offset")&&(br=je),zt.draw(E,St,br,S||E.stencilModeForClipping(Ut),U,Zr.disabled,Je,L.id,_t.layoutVertexBuffer,pt,Ot,L.paint,E.transform.zoom,jt,Jt)}};E.renderPass===ne&&De(E.depthModeForSublayer(1,E.renderPass==="opaque"?Mr.ReadWrite:Mr.ReadOnly),!1),be==="none"&&E.renderPass==="translucent"&&L.paint.get("fill-antialias")&&De(E.depthModeForSublayer(L.getPaintProperty("fill-outline-color")?2:0,Mr.ReadOnly),!0)}function Ip(_,d,g,S,E,R,L,B){g.resetLayerRenderingStats(_);const U=_.context,W=U.gl,Z=_.transform,ne=g.paint.get("fill-extrusion-pattern"),re=g.paint.get("fill-extrusion-pattern-cross-fade"),ie=ne.constantOr(null),ce=ne.constantOr(1),le=g.paint.get("fill-extrusion-opacity"),be=_.style.enable3dLights(),_e=g.paint.get(be&&!ce?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Re=[g.paint.get("fill-extrusion-ambient-occlusion-intensity"),_e],Me=g.layout.get("fill-extrusion-edge-radius"),je=Me>0&&!g.paint.get("fill-extrusion-rounded-roof"),Xe=je?0:Me,$e=Z.projection.name==="globe"?a.e1():0,Ke=Z.projection.name==="globe",De=Ke?a.al(Z.zoom):0,Be=[a.aH(Z.center.lng),a.aL(Z.center.lat)],Ge=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ot=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ge?null:g.lut).toArray01().slice(0,3),Je=g.paint.get("fill-extrusion-flood-light-intensity"),St=g.paint.get("fill-extrusion-vertical-scale"),pt=g.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Ot=g.paint.get("fill-extrusion-height-alignment"),Ut=g.paint.get("fill-extrusion-base-alignment"),ut=Ya(_,g.paint.get("fill-extrusion-cutoff-fade-range")),st=g.paint.get("fill-extrusion-front-cutoff"),_t=cw(Z.pitch,st,!!_.terrain),jt=_t[2]<1;jt&&(_.maxFrontCutoffRawStart=Math.max(_.maxFrontCutoffRawStart,st[0]));const Nt=[];let lr;Ke&&Nt.push("PROJECTION_GLOBE_VIEW"),Re[0]>0&&Nt.push("FAUX_AO"),je&&Nt.push("ZERO_ROOF_RADIUS"),B&&Nt.push("HAS_CENTROID"),Je>0&&Nt.push("FLOOD_LIGHT"),ut.shouldRenderCutoff&&Nt.push("RENDER_CUTOFF"),jt&&Nt.push("RENDER_FRONT_CUTOFF"),pt&&Nt.push("RENDER_WALL_MODE");const Jt=_.renderPass==="shadow",er=_.shadowRenderer,zt=Jt&&!!er,Pr=Jt?Zr.disabled:Zr.backCCW;_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0);let Fr=[0,0,0];if(er){const Jr=_.style.directionalLight,dn=_.style.ambientLight;Jr&&dn&&(Fr=fd(_.style,Jr,dn)),Jt||(Nt.push("RENDER_SHADOWS"),er.useNormalOffset&&Nt.push("NORMAL_OFFSET")),lr=Nt.concat(["SHADOWS_SINGLE_CASCADE"])}const br=zt?"fillExtrusionDepth":ce?"fillExtrusionPattern":"fillExtrusion",Nr=g.getLayerRenderingStats();for(const Jr of S){const dn=d.getTile(Jr),on=dn.getBucket(g);if(!on||on.projection.name!==Z.projection.name)continue;let Tn=!1;er&&(Tn=er.getMaxCascadeForTile(Jr.toUnwrapped())===0);const Kr=_.isTileAffectedByFog(Jr),jn=on.programConfigurations.get(g.id);let ln=!1;if(ie&&dn.imageAtlas){const bn=dn.imageAtlas,Bs=a.dV.from(ie),mi=Bs.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),hs=Bs.getSecondary(),hn=bn.patternPositions.get(mi),si=hs?bn.patternPositions.get(hs.scaleSelf(a.o.devicePixelRatio).toString()):null;ln=!!hn&&!!si,hn&&jn.setConstantPatternPositions(hn,si)}re>0&&(ln||jn.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Nt.push("FILL_EXTRUSION_PATTERN_TRANSITION");const ts=_.getOrCreateProgram(br,{config:jn,defines:Tn?lr:Nt,overrideFog:Kr});if(_.terrain&&_.terrain.setupElevationDraw(dn,ts,{useMeterToDem:!0}),!on.centroidVertexBuffer){const bn=ts.getAttributeLocation(W,"a_centroid_pos");bn!==-1&&W.vertexAttribI4ui(bn,0,0,0,0)}!Jt&&er&&er.setupShadows(dn.tileID.toUnwrapped(),ts,"vector-tile"),ce&&(_.context.activeTexture.set(W.TEXTURE0),dn.imageAtlasTexture&&dn.imageAtlasTexture.bind(W.LINEAR,W.CLAMP_TO_EDGE),jn.updatePaintBuffers());const Cs=g.paint.get("fill-extrusion-vertical-gradient"),li=1/on.tileToMeter;let Fs;if(Jt&&er){if(uw(dn.tileID,on.maxHeight,_))continue;const bn=er.calculateShadowPassMatrixFromTile(dn.tileID.toUnwrapped());Fs=_B(bn,Xe,li,St,Ot,Ut)}else{const bn=_.translatePosMatrix(Jr.expandedProjMatrix,dn,g.paint.get("fill-extrusion-translate"),g.paint.get("fill-extrusion-translate-anchor")),Bs=Z.projection.createInversionMatrix(Z,Jr.canonical);Fs=ce?bB(bn,_,Cs,le,Re,Xe,li,Jr,dn,$e,Ot,Ut,De,Be,Bs,ot,St,re):ZI(bn,_,Cs,le,Re,Xe,li,Jr,$e,Ot,Ut,De,Be,Bs,ot,St,Je,Fr,_t)}_.uploadCommonUniforms(U,ts,Jr.toUnwrapped(),null,ut);let ds=on.segments;if(Z.projection.name==="mercator"&&!Jt&&(ds=on.getVisibleSegments(dn.tileID,_.terrain,_.transform.getFrustum(0)),!ds.get().length))continue;if(Nr)if(Jt)for(const bn of ds.get())Nr.numRenderedVerticesInShadowPass+=bn.primitiveLength;else for(const bn of ds.get())Nr.numRenderedVerticesInTransparentPass+=bn.primitiveLength;const _n=[];(_.terrain||B)&&_n.push(on.centroidVertexBuffer),Ke&&_n.push(on.layoutVertexExtBuffer),pt&&_n.push(on.wallVertexBuffer),ts.draw(_,U.gl.TRIANGLES,E,R,L,Pr,Fs,g.id,on.layoutVertexBuffer,on.indexBuffer,ds,g.paint,_.transform.zoom,jn,_n)}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1)}class wE{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function cw(_,d,g){if(!(d[2]<1)||g)return[0,0,1];const S=180*_/Math.PI;if(S<15)return[-.5,d[1],d[2]];const E=Math.min(1,Math.max(0,(S-15)/5)),R=E*E*(3-2*E);return[-.5*(1-R)+d[0]*R,d[1],d[2]]}function eh(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie,ce,le,be,_e,Re,Me,je){const Xe=d.context,$e=Xe.gl,Ke=d.transform,De=d.transform.zoom,Be=[],Ge=_.translate,ot=_.translateAnchor,Je=_.edgeRadius,St=Ya(d,_.cutoffFadeRange);Z==="clear"?(Be.push("CLEAR_SUBPASS"),Me&&(Be.push("CLEAR_FROM_TEXTURE"),Xe.activeTexture.set($e.TEXTURE0),Me.bind($e.LINEAR,$e.CLAMP_TO_EDGE))):Z==="sdf"?Be.push("SDF_SUBPASS"):Z==="emissive"&&(Be.push("USE_MRT1"),Xe.activeTexture.set($e.TEXTURE0),Me.bind($e.LINEAR,$e.CLAMP_TO_EDGE)),_e&&Be.push("HAS_CENTROID"),St.shouldRenderCutoff&&Be.push("RENDER_CUTOFF");const pt=(Ot,Ut,ut,st,_t)=>{let jt=Be;Ut.groundRadiusBuffer!=null&&(jt=Be.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Nt=Ut.programConfigurations.get(S.id),lr=d.isTileAffectedByFog(Ot),Jt=d.getOrCreateProgram("fillExtrusionGroundEffect",{config:Nt,defines:jt,overrideFog:lr}),er=((Pr,Fr,br,Nr,Jr,dn,on,Tn,Kr,jn,ln)=>({u_matrix:Fr,u_opacity:br,u_ao_pass:Nr?1:0,u_meter_to_tile:Jr,u_ao:dn,u_flood_light_intensity:on,u_flood_light_color:Tn,u_attenuation:Kr,u_edge_radius:jn,u_fb:0,u_fb_size:ln,u_dynamic_offset:1}))(0,st,ne,W,_t,[re,ie*_t],ce,le,be,De>=17?0:Je*_t,Me?Me.size[0]:0),zt=[];_e&&zt.push(Ut.hiddenByLandmarkVertexBuffer),Ut.groundRadiusBuffer!=null&&zt.push(Ut.groundRadiusBuffer),d.uploadCommonUniforms(Xe,Jt,Ot.toUnwrapped(),null,St),Jt.draw(d,Xe.gl.TRIANGLES,R,L,B,U,er,S.id,Ut.vertexBuffer,Ut.indexBuffer,ut,S.paint,De,Nt,zt)};for(const Ot of E){const Ut=g.getTile(Ot),ut=Ut.getBucket(S);if(!ut||ut.projection.name!==Ke.projection.name||!ut.groundEffect||ut.groundEffect&&!ut.groundEffect.hasData())continue;const st=ut.groundEffect,_t=1/ut.tileToMeter;{const jt=d.translatePosMatrix(Ot.projMatrix,Ut,Ge,ot),Nt=st.getDefaultSegment();pt(Ot,st,Nt,jt,_t)}if(Re)for(let jt=0;jt<4;jt++){const Nt=a.d$[jt](Ot),lr=g.getTile(Nt);if(!lr)continue;const Jt=lr.getBucket(S);if(!Jt||Jt.projection.name!==Ke.projection.name||!Jt.groundEffect||Jt.groundEffect&&!Jt.groundEffect.hasData())continue;const er=Jt.groundEffect;let zt,Pr;jt===0?(zt=[-a.an,0,0],Pr=1):jt===1?(zt=[a.an,0,0],Pr=0):jt===2?(zt=[0,-a.an,0],Pr=3):(zt=[0,a.an,0],Pr=2);const Fr=er.regionSegments[Pr];if(!Fr)continue;const br=new Float32Array(16);a.bx(br,Ot.projMatrix,zt),pt(Ot,er,Fr,d.translatePosMatrix(br,Ut,Ge,ot),_t)}}}function lP(_,d,g,S,E,R,L){S.centroidVertexArray.length===0&&S.createCentroidsBuffer();const B=R?R.findDEMTileFor(g):null;if(!(B&&B.dem||L))return;R&&B&&B.dem&&S.selfDEMTileTimestamp!==B.dem._timestamp&&(S.borderDoneWithNeighborZ=[-1,-1,-1,-1],S.selfDEMTileTimestamp=B.dem._timestamp);const U=(_e,Re)=>{(_e.flags|Re.flags)&a.e3?(_e.flags|=a.e3,Re.flags|=a.e3):(_e.flags&=~a.e3,Re.flags&=~a.e3)},W=_e=>new a.P(Math.ceil((_e+a.e4)*a.e5),0),Z=(_e,Re,Me)=>{const je=Math.ceil((_e+a.e4)*a.e5),Xe=Math.floor(Math.max(0,Math.min(a.an-1,Me))/4);return new a.P(je,Xe<<5|(3&Re)<<3|7)},ne=_e=>{const Re=d.getSource().minzoom,Me=Xe=>{const $e=d.getTileByID(Xe);if($e&&$e.hasData())return $e.getBucket(E)},je=[0,-1,1];for(const Xe of je){if(_e.overscaledZ+Xe(re[0]=Math.min(_e.min.y,Re.min.y),re[1]=Math.max(_e.max.y,Re.max.y),re[2]=a.an-Re.min.x>_e.max.x?Re.min.x-a.an:_e.max.x,re),ce=(_e,Re)=>(re[0]=Math.min(_e.min.x,Re.min.x),re[1]=Math.max(_e.max.x,Re.max.x),re[2]=a.an-Re.min.y>_e.max.y?Re.min.y-a.an:_e.max.y,re),le=[(_e,Re)=>ie(_e,Re),(_e,Re)=>ie(Re,_e),(_e,Re)=>ce(_e,Re),(_e,Re)=>ce(Re,_e)],be=(_e,Re,Me,je,Xe,$e,Ke)=>{if(!R)return 0;const De=[[$e?Me:_e,$e?_e:Me,0],[$e?Me:Re,$e?Re:Me,0]],Be=Ke<0?a.an+Ke:Ke,Ge=[$e?Be:(_e+Re)/2,$e?(_e+Re)/2:Be,0];return Me===0&&Ke<0||Me!==0&&Ke>0?R.getForTilePoints(Xe,[Ge],!0,je):De.push(Ge),R.getForTilePoints(g,De,!0,B),Math.max(De[0][2],De[1][2],Ge[2])/R.exaggeration()};for(let _e=0;_e<4;_e++){const Re=S.borderFeatureIndices[_e];if(Re.length===0)continue;const Me=a.d$[_e](g),je=ne(Me);if(!(je&&je instanceof a.e0))continue;const Xe=R?R.findDEMTileFor(Me):null;if(!(Xe&&Xe.dem||L)||(R&&Xe&&Xe.dem&&S.borderDEMTileTimestamp[_e]!==Xe.dem._timestamp&&(S.borderDoneWithNeighborZ[_e]=-1,S.borderDEMTileTimestamp[_e]=Xe.dem._timestamp),S.borderDoneWithNeighborZ[_e]===je.canonical.z))continue;je.centroidVertexArray.length===0&&je.createCentroidsBuffer();const $e=(_e<2?1:5)-_e,Ke=je.borderDoneWithNeighborZ[$e]!==S.canonical.z,De=je.borderFeatureIndices[$e];let Be=0;if(S.canonical.z!==je.canonical.z){for(const St of Re)S.showCentroid(S.featuresOnBorder[St]);if(Ke)for(const St of De)je.showCentroid(je.featuresOnBorder[St]);S.borderDoneWithNeighborZ[_e]=je.canonical.z,je.borderDoneWithNeighborZ[$e]=S.canonical.z;continue}const Ge=new Map,ot=new Set,Je=new Set;for(let St=0;St1||ut.intersectsCount()>1;{let Jt=0;if(Xe&&Xe.dem&&!lr){const er=le[_e](Ot,st),zt=_e%2?a.an-1:0;Jt=be(er[0],Math.min(a.an-1,er[1]),zt,Xe,Me,_e<2,er[2])}Ot.centroidXY=Z(Jt,_e,Nt),st.centroidXY=Z(Jt,$e,Nt)}if(S.writeCentroidToBuffer(Ot),je.writeCentroidToBuffer(st),pt.buildingId!==void 0){for(const Jt of S.centroidData)Jt.buildingId===pt.buildingId&&Jt!==Ot&&(Jt.centroidXY=Ot.centroidXY,S.writeCentroidToBuffer(Jt));for(const Jt of je.centroidData)Jt.buildingId===pt.buildingId&&Jt!==st&&(Jt.centroidXY=st.centroidXY,je.writeCentroidToBuffer(Jt))}}for(const St of Re){if(ot.has(St))continue;const pt=S.featuresOnBorder[St],Ot=S.centroidData[pt.centroidDataIndex],Ut=pt.borders[_e];let ut;for(;BeUt[0]+3||st[0]>Ut[0]-3)break;je.showCentroid(ut),Be++}if(ut&&BeUt[1]-3||(_t++,++Be===De.length))break;ut=je.featuresOnBorder[De[Be]]}for(;st=De.length){S.showCentroid(pt);continue}ut=je.featuresOnBorder[De[st]];let jt=!1;if(_t>=1){const Jt=ut.borders[$e];Math.abs(Ut[0]-Jt[0])<3&&Math.abs(Ut[1]-Jt[1])<3&&(_t=1,jt=!0,Be=st+1)}else if(_t===0){S.showCentroid(pt);continue}const Nt=je.centroidData[ut.centroidDataIndex];L&&jt&&U(Ot,Nt);const lr=pt.intersectsCount()>1||ut.intersectsCount()>1;if(_t>1)Be=st,Ot.centroidXY=Nt.centroidXY=new a.P(0,0);else if(Xe&&Xe.dem&&!lr){const Jt=le[_e](Ot,Nt),er=_e%2?a.an-1:0,zt=be(Jt[0],Math.min(a.an-1,Jt[1]),er,Xe,Me,_e<2,Jt[2]);Ot.centroidXY=Nt.centroidXY=W(zt)}else lr?Ot.centroidXY=Nt.centroidXY=new a.P(0,0):(Ot.centroidXY=S.encodeBorderCentroid(pt),Nt.centroidXY=je.encodeBorderCentroid(ut));S.writeCentroidToBuffer(Ot),je.writeCentroidToBuffer(Nt)}else S.showCentroid(pt)}S.borderDoneWithNeighborZ[_e]=je.canonical.z,je.borderDoneWithNeighborZ[$e]=S.canonical.z}(S.needsCentroidUpdate||!S.centroidVertexBuffer&&S.centroidVertexArray.length!==0)&&S.uploadCentroid(_)}const cP=[1,0,0],uP=[0,1,0],SE=[0,0,1];function uw(_,d,g){const S=g.transform,E=g.shadowRenderer;if(!E)return!0;const R=_.toUnwrapped(),L=S.tileSize*E._cascades[g.currentShadowCascade].scale;let B=d;if(S.elevation){const ce=S.elevation.getMinMaxForTile(_);ce&&(B+=ce.max)}const U=S.scaleZoom(L);B/=a.e2(S.center.lat,U);const W=[...E.shadowDirection];W[2]=-W[2];const Z=E.computeSimplifiedTileShadowVolume(R,B,L,W);if(!Z)return!1;const ne=[cP,uP,SE,W,[W[0],0,W[2]],[0,W[1],W[2]]],re=a.cl.fromInvProjectionMatrix(S.invProjMatrix,S.worldSize,U,S.projection.name!=="globe"),ie=E.getCurrentCascadeFrustum();return re.intersectsPrecise(Z.vertices,Z.planes,ne)===0||ie.intersectsPrecise(Z.vertices,Z.planes,ne)===0}function mv(_){const{painter:d,source:g,layer:S,coords:E}=_;let R=_.defines;const L=d.context,B=d.renderPass==="shadow",U=d.renderPass==="light-beam",W=d.shadowRenderer,Z=a.e2(d.transform.center.lat,d.transform.zoom),ne=Ya(d,S.paint.get("building-cutoff-fade-range"));ne.shouldRenderCutoff&&(R=R.concat("RENDER_CUTOFF"));const re=S.paint.get("building-front-cutoff"),ie=re[2]<1&&!d.terrain,ce=cw(d.transform.pitch,re,!!d.terrain);ie&&(R=R.concat("RENDER_FRONT_CUTOFF"),d.maxFrontCutoffRawStart=Math.max(d.maxFrontCutoffRawStart,re[0])),_.floodLightIntensity>0&&(R=R.concat("FLOOD_LIGHT"));for(const le of E){const be=g.getTile(le),_e=be.getBucket(S);if(!_e)continue;W&&W.getMaxCascadeForTile(le.toUnwrapped())===0&&(R=R.concat("SHADOWS_SINGLE_CASCADE"));const Re=_e.programConfigurations.get(S.id);let Me,je,Xe,$e=d.translatePosMatrix(le.expandedProjMatrix,be,[0,0],"map");if($e=a.cC(a.bb(),$e,[1,1,_.verticalScale]),B&&W){if(uw(be.tileID,_e.maxHeight*Z,d))continue;let De=W.calculateShadowPassMatrixFromTile(be.tileID.toUnwrapped());De=a.cC(a.bb(),De,[1,1,_.verticalScale]),Xe=tw(De),Me=je=d.getOrCreateProgram("buildingDepth",{config:Re,defines:R,overrideFog:!1})}else if(U)Me=je=d.getOrCreateProgram("buildingBloom",{config:Re,defines:R,overrideFog:!1}),Xe=ew($e);else{const De=d.transform.calculatePosMatrix(le.toUnwrapped(),d.transform.worldSize);a.cC(De,De,[1,1,_.verticalScale]);const Be=a.bb();a.cC(Be,De,[1,-1,1/Z]),a.b7(Be,Be),a.e6(Be,Be);const Ge=d.transform.getFreeCameraOptions().position,ot=1<{if(U){const Ge=De.entranceBloom;Be.draw(d,L.gl.TRIANGLES,_.depthMode,an.disabled,_.blendMode,Zr.disabled,Xe,S.id,Ge.layoutVertexBuffer,Ge.indexBuffer,Ge.segmentsBucket,S.paint,d.transform.zoom,Re,[Ge.layoutAttenuationBuffer,Ge.layoutColorBuffer])}else{const Ge=De.segmentsBucket;let ot=[De.layoutNormalBuffer,De.layoutCentroidBuffer,De.layoutColorBuffer,De.layoutFloodLightDataBuffer];De.layoutFacadePaintBuffer&&(ot=ot.concat([De.layoutFacadeDataBuffer,De.layoutFacadeVerticalRangeBuffer,De.layoutFacadePaintBuffer])),Be.draw(d,L.gl.TRIANGLES,_.depthMode,an.disabled,_.blendMode,B?Zr.disabled:Zr.backCW,Xe,S.id,De.layoutVertexBuffer,De.indexBuffer,Ge,S.paint,d.transform.zoom,Re,ot)}};d.uploadCommonUniforms(L,je,le.toUnwrapped(),null,ne),_e.buildingWithoutFacade&&Ke(_e.buildingWithoutFacade,je),_e.buildingWithFacade&&(Me!==je&&d.uploadCommonUniforms(L,Me,le.toUnwrapped(),null,ne),Ke(_e.buildingWithFacade,Me))}}function TE(_,d,g,S,E,R,L,B,U,W,Z,ne,re,ie){const ce=_.context.gl,le=_.depthModeForSublayer(1,Mr.ReadOnly,ce.LEQUAL,!0),be=.1*(1-(_e=Z))+3*_e;var _e;const Re=_._showOverdrawInspector,Me=ne,je=new wE;Re||eh(je,_,d,g,S,le,new an({func:ce.ALWAYS,mask:255},255,255,ce.KEEP,ce.KEEP,ce.REPLACE),new tn([ce.ONE,ce.ONE,ce.ONE,ce.ONE],a.aq.transparent,[!1,!1,!1,!0],ce.MIN),Zr.disabled,E,"sdf",R,L,B,U,W,be,Me,!1,void 0);{const Xe=Re?an.disabled:new an({func:ce.EQUAL,mask:255},255,255,ce.KEEP,ce.DECR,ce.DECR),$e=Re?_.colorModeForRenderPass():new tn([ce.ONE_MINUS_DST_ALPHA,ce.DST_ALPHA,ce.ONE,ce.ONE],a.aq.transparent,[!0,!0,!0,!0]);eh(je,_,d,g,S,le,Xe,$e,Zr.disabled,E,"color",R,L,B,U,W,be,Me,!1,void 0)}}function jE(_){return[_[0]*a.e7,_[1]*a.e7,_[2]*a.e7,0]}function dw(_,d,g,S,E,R,L,B,U){const W=S.getSource(),Z=g.globeSharedBuffers;if(!Z)return;let ne,re,ie;if(d&&(ne=S.getTile(d)),W instanceof a.aV?(re=W.texture,ie=a.dw(0,0,g.transform)):ne&&d&&(re=ne.texture,ie=a.dw(d.canonical.z,d.canonical.x,g.transform)),!re||!ie)return;_||(ie=a.cC(a.bb(),ie,[1,-1,1]));const ce=g.context,le=ce.gl,be=E.paint.get("raster-resampling")==="nearest"?le.NEAREST:le.LINEAR,_e=g.colorModeForDrapableLayerRenderPass(R),Re=L.defines;Re.push("GLOBE_POLES");const Me=new Mr(le.LEQUAL,Mr.ReadWrite,g.depthRangeFor3D),je=Float32Array.from(g.transform.expandedFarZProjMatrix),Xe=Float32Array.from(a.du(a.dv(new a.cn(0,0,0))));g.terrain&&g.terrain.prepareDrawTile(),ce.activeTexture.set(le.TEXTURE0),re.bind(be,le.CLAMP_TO_EDGE),ce.activeTexture.set(le.TEXTURE1),re.bind(be,le.CLAMP_TO_EDGE),"useMipmap"in re&&ce.extTextureFilterAnisotropic&&g.transform.pitch>20&&le.texParameterf(le.TEXTURE_2D,ce.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ce.extTextureFilterAnisotropicMax);const[$e,Ke,De,Be]=d?Z.getPoleBuffers(d.canonical.z,!1):Z.getPoleBuffers(0,!0),Ge=E.paint.get("raster-elevation");let ot;_?(ot=$e,g.renderDefaultNorthPole=Ge!==0):(ot=Ke,g.renderDefaultSouthPole=Ge!==0);const Je=jE(L.mix),St=((Ot,Ut,ut,st,_t,jt,Nt,lr,Jt,er,zt,Pr,Fr,br)=>rP(Ot,Ut,ut,st,new Float32Array(16),new Float32Array(9),[0,0],_t,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Nt,[0,0],Jt,2,zt,Pr,Fr,1,0,br))(g,je,Xe,ie,a.al(g.transform.zoom),0,E,0,Ge,0,Je,L.offset,L.range,R),pt=g.getOrCreateProgram("raster",{defines:Re});g.uploadCommonUniforms(ce,pt,null),pt.draw(g,le.TRIANGLES,Me,U,_e,B,St,E.id,ot,De,Be)}function EE(_){if(_.isOrthographic)return[0,0,0,0];const d=_._nearZ,g=_.projection.farthestPixelDistance(_),S=g-d,E=.2*_.height,R=d+E;return[d,g,(R-E-d)/S,(R-d)/S]}function dP(_,d,g,S){if(_)return d instanceof yp&&_ instanceof xp?d.getTextureDescriptor(_,g,!0):{texture:_.texture,mix:jE(S.mix),offset:S.offset,buffer:0,tileSize:1}}var kE=a.e8([{name:"a_index",type:"Int16",components:1}]);class hP{constructor(d,g,S,E){const R={width:S[0],height:S[1],data:null},L=d.gl;this.targetColorTexture=new a.T(d,R,L.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new a.T(d,R,L.RGBA8,{useMipmap:!1}),this.context=d,this.updateParticleTexture(g,E),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 S=this.context.gl,E=g.width*g.height;this.particleTexture0=new a.T(this.context,g,S.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new a.T(this.context,g,S.RGBA8,{premultiply:!1,useMipmap:!1});const R=new a.e9;R.reserve(E);for(let L=0;L0){const Je=a.ec(g.canonical,U),St=a.ed(Je);re=a.aD(new Float32Array(16),U.globeMatrix,St),a.aD(re,U.projMatrix,re)}const ie=a.bb();ie[12]+=2*E/(a.o.devicePixelRatio*U.width),ie[13]+=2*R/(a.o.devicePixelRatio*U.height),a.aD(re,ie,re);const ce=_.getOrCreateProgram("debug",{defines:ne}),le=d.getTileByID(g.key);_.terrain&&_.terrain.setupElevationDraw(le,ce);const be=Mr.disabled,_e=an.disabled,Re=_.colorModeForRenderPass(),Me="$debug";B.activeTexture.set(W.TEXTURE0),_.emptyTexture.bind(W.LINEAR,W.CLAMP_TO_EDGE),Z?le._makeGlobeTileDebugBuffers(_.context,U):le._makeDebugTileBoundsBuffers(_.context,U.projection);const je=le._tileDebugBuffer||_.debugBuffer,Xe=le._tileDebugIndexBuffer||_.debugIndexBuffer,$e=le._tileDebugSegments||_.debugSegments;if(ce.draw(_,W.LINE_STRIP,be,_e,Re,Zr.disabled,lv(re,S.toPremultipliedRenderColor(null)),Me,je,Xe,$e,null,null,null,[le._globeTileDebugBorderBuffer]),L){const Je=le.latestRawTileData,St=Math.floor((Je&&Je.byteLength||0)/1024);let pt=g.canonical.toString();g.overscaledZ!==g.canonical.z&&(pt+=` => ${g.overscaledZ}`),pt+=` ${le.state}`,pt+=` ${St}kb`,function(Ot,Ut){Ot.initDebugOverlayCanvas();const ut=Ot.debugOverlayCanvas,st=Ot.context.gl,_t=Ot.debugOverlayCanvas.getContext("2d");_t.clearRect(0,0,ut.width,ut.height),_t.shadowColor="white",_t.shadowBlur=2,_t.lineWidth=1.5,_t.strokeStyle="white",_t.textBaseline="top",_t.font="bold 36px Open Sans, sans-serif",_t.fillText(Ut,5,5),_t.strokeText(Ut,5,5),Ot.debugOverlayTexture.update(ut),Ot.debugOverlayTexture.bind(st.LINEAR,st.CLAMP_TO_EDGE)}(_,pt)}const Ke=d.getTile(g).tileSize,De=512/Math.min(Ke,512)*(g.overscaledZ/U.zoom)*.5,Be=le._tileDebugTextBuffer||_.debugBuffer,Ge=le._tileDebugTextIndexBuffer||_.quadTriangleIndexBuffer,ot=le._tileDebugTextSegments||_.debugSegments;ce.draw(_,W.TRIANGLES,be,_e,tn.alphaBlended,Zr.disabled,lv(re,a.aq.transparent.toPremultipliedRenderColor(null),De),Me,Be,Ge,ot,null,null,null,[le._globeTileDebugTextBuffer])}function mP(_,d,g,S){hw(_,0,d+g/2,_.transform.width,g,S)}function PE(_,d,g,S){hw(_,d-g/2,0,g,_.transform.height,S)}function hw(_,d,g,S,E,R){const L=_.context,B=L.gl;B.enable(B.SCISSOR_TEST),B.scissor(d*a.o.devicePixelRatio,g*a.o.devicePixelRatio,S*a.o.devicePixelRatio,E*a.o.devicePixelRatio),L.clear({color:R}),B.disable(B.SCISSOR_TEST)}const kB=a.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:jc}=kB;function th(_,d,g,S){_.emplaceBack(d,g,S)}class ml{constructor(d){this.vertexArray=new a.ee,this.indices=new a.dC,th(this.vertexArray,-1,-1,1),th(this.vertexArray,1,-1,1),th(this.vertexArray,-1,1,1),th(this.vertexArray,1,1,1),th(this.vertexArray,-1,-1,-1),th(this.vertexArray,1,-1,-1),th(this.vertexArray,-1,1,-1),th(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,jc),this.indexBuffer=d.createIndexBuffer(this.indices),this.segment=a.dy.simpleSegment(0,0,36,12)}}function Yc(_,d,g,S,E,R){const L=_.context.gl,B=d.paint.get("sky-atmosphere-color"),U=d.paint.get("sky-atmosphere-halo-color"),W=d.paint.get("sky-atmosphere-sun-intensity"),Z=((ne,re,ie,ce,le)=>({u_matrix_3f:ne,u_sun_direction:re,u_sun_intensity:ie,u_color_tint_r:[ce.r,ce.g,ce.b,ce.a],u_color_tint_m:[le.r,le.g,le.b,le.a],u_luminance:5e-5}))(a.eg(a.dE(),S),E,W,B.toPremultipliedRenderColor(null),U.toPremultipliedRenderColor(null));L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+R,d.skyboxTexture,0),g.draw(_,L.TRIANGLES,Mr.disabled,an.disabled,tn.unblended,Zr.frontCW,Z,"skyboxCapture",d.skyboxGeometry.vertexBuffer,d.skyboxGeometry.indexBuffer,d.skyboxGeometry.segment)}const pP=a.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class RE{constructor(d){const g=new a.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 S=new a.dC;S.emplaceBack(0,1,2),S.emplaceBack(2,3,0),this.vertexBuffer=d.createVertexBuffer(g,pP.members),this.indexBuffer=d.createIndexBuffer(S),this.segments=a.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const LE=a.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 ME{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class gP{constructor(d){this.colorModeAlphaBlendedWriteRGB=new tn([1,Vi,1,Vi],a.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new tn([1,0,1,0],a.aq.transparent,[!1,!1,!1,!0]),this.params=new ME,this.updateNeeded=!0}update(d){const g=d.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new RE(g);const S=this.params.sizeRange,E=this.params.intensityRange,R=function(Z){const ne=a.em(30),re=[];for(let ie=0;ie{const De=R.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ke&&De.push("ALPHA_PASS");const Be=d.getOrCreateProgram("globeAtmosphere",{defines:De}),Ge=((Je,St,pt,Ot,Ut,ut,st,_t,jt,Nt,lr,Jt)=>({u_frustum_tl:Je,u_frustum_tr:St,u_frustum_br:pt,u_frustum_bl:Ot,u_horizon:Ut,u_transition:ut,u_fadeout_range:st,u_atmosphere_fog_color:_t.toArray01(),u_high_color:jt.toArray01(),u_space_color:Nt.toArray01(),u_temporal_offset:lr,u_horizon_angle:Jt}))(R.frustumCorners.TL,R.frustumCorners.TR,R.frustumCorners.BR,R.frustumCorners.BL,R.frustumCorners.horizon,B,be,Z,re,ce,Re,Xe);d.uploadCommonUniforms(S,Be);const ot=this.atmosphereBuffer;ot&&Be.draw(d,E.TRIANGLES,L,an.disabled,Ke?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Zr.backCW,Ge,Ke?"atmosphere_glow_alpha":"atmosphere_glow",ot.vertexBuffer,ot.indexBuffer,ot.segments)};$e(!1),$e(!0)}drawStars(d,g){const S=a.aC(g.properties.get("star-intensity"),0,1);if(S===0)return;const E=d.context,R=E.gl,L=d.transform,B=d.getOrCreateProgram("stars"),U=a.bL([]);a.bN(U,U,-L._pitch),a.bM(U,U,-L.angle),a.bN(U,U,a.ap(L._center.lat)),a.ek(U,U,-a.ap(L._center.lng));const W=a.bR(new Float32Array(16),U),Z=a.aD([],L.starsProjMatrix,W),ne=a.eg([],W),re=a.el([],ne),ie=[0,1,0];a.dG(ie,ie,re),a.bJ(ie,ie,this.params.sizeMultiplier);const ce=[1,0,0];a.dG(ce,ce,re),a.bJ(ce,ce,this.params.sizeMultiplier);const le=(be=ie,_e=ce,Re=S,{u_matrix:Float32Array.from(Z),u_up:be,u_right:_e,u_intensity_multiplier:Re});var be,_e,Re;d.uploadCommonUniforms(E,B),this.starsVx&&this.starsIdx&&B.draw(d,R.TRIANGLES,Mr.disabled,an.disabled,this.colorModeAlphaBlendedWriteRGB,Zr.disabled,le,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Hh{constructor(){this.visibleTiles=[]}updateBorders(d,g){const S=[],E=[],R=d._getRenderableCoordinates(!1,!0);for(const U of R){const W=d.getTile(U);if(!W.hasData())continue;const Z=W.getBucket(g);Z&&(Z.isEmpty()||(S.push(U.key),E.push({bucket:Z,tileID:U.canonical})))}let L=S.length!==this.visibleTiles.length;if(!L){S.sort();for(let U=0;UU.tileID.z-W.tileID.z||U.tileID.x-W.tileID.x||U.tileID.y-W.tileID.y);for(const U of E){const W=new Array,Z=new Array,ne=U.bucket;for(const re of ne.featuresOnBorder)B.has(re.featureId)?Z.push(re.footprintIndex):(B.add(re.featureId),W.push(re.footprintIndex));ne.updateFootprintHiddenFlags(W,a.en,!1),ne.updateFootprintHiddenFlags(Z,a.en,!0)}}}function yP(_,d){const g=[..._],S=d.cameraWorldSizeForFog/d.worldSize,E=a.b9([]);return a.cC(E,E,[S,S,1]),a.aD(g,E,g),a.aD(g,d.worldToFogMatrix,g),g}function fs(_,d,g,S,E){const R=g.material,L=S.context,{baseColorTexture:B,metallicRoughnessTexture:U}=R.pbrMetallicRoughness,{normalTexture:W,occlusionTexture:Z,emissionTexture:ne}=R;function re(ce,le,be){if(ce&&(_.push(le),L.activeTexture.set(L.gl.TEXTURE0+be),ce.gfxTexture)){const{minFilter:_e,magFilter:Re,wrapS:Me,wrapT:je}=ce.sampler;ce.gfxTexture.bindExtraParam(_e,Re,Me,je)}}re(B,"HAS_TEXTURE_u_baseColorTexture",5),re(U,"HAS_TEXTURE_u_metallicRoughnessTexture",6),re(W,"HAS_TEXTURE_u_normalTexture",7),re(Z,"HAS_TEXTURE_u_occlusionTexture",8),re(ne,"HAS_TEXTURE_u_emissionTexture",9),E&&(E.texture||(E.texture=new a.dR(S.context,E.image,[E.image.height,E.image.height,E.image.height],L.gl.RGBA8)),L.activeTexture.set(L.gl.TEXTURE0+10),E.texture&&E.texture.bind(L.gl.LINEAR,L.gl.CLAMP_TO_EDGE),_.push("APPLY_LUT_ON_GPU")),g.texcoordBuffer&&(_.push("HAS_ATTRIBUTE_a_uv_2f"),d.push(g.texcoordBuffer)),g.colorBuffer&&(_.push(g.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),d.push(g.colorBuffer)),g.normalBuffer&&(_.push("HAS_ATTRIBUTE_a_normal_3f"),d.push(g.normalBuffer)),g.pbrBuffer&&(_.push("HAS_ATTRIBUTE_a_pbr"),_.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),d.push(g.pbrBuffer)),R.alphaMode!=="OPAQUE"&&R.alphaMode!=="MASK"||_.push("UNPREMULT_TEXTURE_IN_SHADER"),R.defined||_.push("DIFFUSE_SHADED");const ie=S.shadowRenderer;ie&&(_.push("RENDER_SHADOWS"),ie.useNormalOffset&&_.push("NORMAL_OFFSET"))}function vy(_,d,g,S,E,R){const L=_.modelOpacity,B=d.context,U=new Mr(d.context.gl.LEQUAL,_.isLightMesh?Mr.ReadOnly:Mr.ReadWrite,d.depthRangeFor3D),W=d.transform,Z=_.mesh,ne=Z.material,re=ne.pbrMetallicRoughness,ie=d.style.fog;let ce;ce=d.transform.projection.zAxisUnit==="pixels"?[..._.nodeModelMatrix]:a.aD([],S.zScaleMatrix,_.nodeModelMatrix),a.aD(ce,S.negCameraPosMatrix,ce);const le=a.b7([],ce);a.e6(le,le);const be=g.paint.get("model-color-use-theme").constantOr("default")==="none",_e=g.paint.get("model-emissive-strength").constantOr(0),Re=Np(new Float32Array(_.worldViewProjection),new Float32Array(ce),new Float32Array(le),null,d,L,re.baseColorFactor,ne.emissiveFactor,re.metallicFactor,re.roughnessFactor,ne,_e,g,void 0,void 0,_.materialOverride,_.modelColor),Me={defines:[]},je=[],Xe=d.shadowRenderer;Xe&&(Xe.useNormalOffset=!1),fs(Me.defines,je,Z,d,be?null:g.lut);let $e=null;if(ie){const Be=yP(_.nodeModelMatrix,d.transform);if($e=new Float32Array(Be),W.projection.name!=="globe"){const Ge=Z.aabb.min,ot=Z.aabb.max,[Je,St]=ie.getOpacityForBounds(Be,Ge[0],Ge[1],ot[0],ot[1]);Me.overrideFog=Je>=vr||St>=vr}}const Ke=Ya(d,g.paint.get("model-cutoff-fade-range"));Ke.shouldRenderCutoff&&Me.defines.push("RENDER_CUTOFF");const De=d.getOrCreateProgram("model",Me);d.uploadCommonUniforms(B,De,null,$e,Ke),d.renderPass!=="shadow"&&Xe&&Xe.setupShadowsFromMatrix(_.nodeModelMatrix,De),De.draw(d,B.gl.TRIANGLES,U,E,R,Z.material.doubleSided?Zr.disabled:Zr.backCCW,Re,g.id,Z.vertexBuffer,Z.indexBuffer,Z.segments,g.paint,d.transform.zoom,void 0,je)}function fw(_,d){return _.style._importedAsBasemap?"basemap":d.scope}function mw(_,d,g,S,E,R,L,B,U,W){const Z=_.transform,ne=!!d.isGeometryBloom&&d.isGeometryBloom;if(ne&&_.renderPass==="shadow")return;const re=Z.projection.name==="globe"?a.ev(g,Z):[...g];a.aD(re,re,d.globalMatrix);const ie=a.aD([],S,re);if(d.meshes)for(const ce of d.meshes){const le=B.get(ce.material.name);if(le&&le.opacity<=0)continue;if(ce.material.alphaMode!=="BLEND"){L.push({mesh:ce,depth:0,modelIndex:E,worldViewProjection:ie,nodeModelMatrix:re,isLightMesh:ne,materialOverride:le,modelOpacity:U,modelColor:W,node:d,modelMatrix:g});continue}const be=a.ah([],ce.centroid,ie);!Z.isOrthographic&&be[2]<=0||R.push({mesh:ce,depth:be[2],modelIndex:E,worldViewProjection:ie,nodeModelMatrix:re,isLightMesh:ne,materialOverride:le,modelOpacity:U,modelColor:W,node:d,modelMatrix:g})}if(d.children)for(const ce of d.children)mw(_,ce,g,S,E,R,L,B,U,W)}function _y(_,d,g,S){const E=g.shadowRenderer;if(!E)return;const R=E.getShadowPassDepthMode(),L=E.calculateShadowPassMatrixFromMatrix(d),B=vE(L);g.getOrCreateProgram("modelDepth").draw(g,g.context.gl.TRIANGLES,R,an.disabled,tn.disabled,Zr.disabled,B,S.id,_.vertexBuffer,_.indexBuffer,_.segments,S.paint,g.transform.zoom,void 0,void 0)}function DE(_,d,g,S){const E=function(Z,ne){if(ne.footprintDebugMesh)return ne.footprintDebugMesh;if(!ne.footprint)return null;const re=Z.context,ie=ne.footprint.vertices,ce=ne.footprint.indices,le=new a.dB;le.reserve(ie.length);for(const Ge of ie)le.emplaceBack(Ge.x,Ge.y);const be=new a.dC;be.reserve(ce.length);for(let Ge=0;Ge0){const re=R.terrain,ie=re.findDEMTileFor(B);ie&&ie.dem?U=a.ex.create(re,B,ie):ne=0}if(ne===0&&(L.terrainElevationMin=0,L.terrainElevationMax=0),ne===L.validForExaggeration&&(ne===0||U&&U._demTile&&U._demTile.tileID===L.validForDEMTile.id&&U._dem._timestamp===L.validForDEMTile.timestamp))return!1;for(const re in L.instancesPerModel){const ie=L.instancesPerModel[re];for(let ce=0;ceW&&(W=ie.max)}const Z=a.aC(S.x,R,L)-S.x,ne=a.aC(S.y,B,U)-S.y,re=a.bU(W,d.center.lat)-S.z;return d._zoomFromMercatorZ(Math.sqrt(Z*Z+ne*ne+re*re))}function fi(_,d,g,S,E,R,L){const B=_.context,U=_.renderPass==="shadow",W=_.shadowRenderer,Z=U&&W?W.getShadowPassDepthMode():new Mr(B.gl.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D),ne=_.isTileAffectedByFog(R),re=_.transform.projection.name==="globe";if(g.meshes)for(const ie of g.meshes){const ce=re?[]:["MODEL_POSITION_ON_GPU"],le=[];let be,_e,Re;const Me=!re&&S.instancedDataArray.length>20;Me&&ce.push("INSTANCED_ARRAYS");const je=Ya(_,d.paint.get("model-cutoff-fade-range"));if(je.shouldRenderCutoff&&ce.push("RENDER_CUTOFF"),U&&W)be=_.getOrCreateProgram("modelDepth",{defines:ce}),_e=vE(L.shadowTileMatrix,L.shadowTileMatrix,Float32Array.from(g.globalMatrix)),Re=tn.disabled;else{fs(ce,le,ie,_,d.paint.get("model-color-use-theme").constantOr("default")==="none"?null:d.lut),be=_.getOrCreateProgram("model",{defines:ce,overrideFog:ne});const $e=ie.material,Ke=$e.pbrMetallicRoughness,De=d.paint.get("model-opacity").constantOr(1),Be=d.paint.get("model-emissive-strength").constantOr(0);_e=Np(R.expandedProjMatrix,Float32Array.from(g.globalMatrix),new Float32Array(16),null,_,De,Ke.baseColorFactor,$e.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,$e,Be,d,E),W&&(L.shadowUniformsInitialized?be.setShadowUniformValues(B,W.getShadowUniformValues()):(W.setupShadows(R.toUnwrapped(),be,"model-tile"),L.shadowUniformsInitialized=!0)),Re=je.shouldRenderCutoff||De<1||$e.alphaMode!=="OPAQUE"?tn.alphaBlended:tn.unblended}_.uploadCommonUniforms(B,be,R.toUnwrapped(),null,je);const Xe=ie.material.doubleSided?Zr.disabled:Zr.backCCW;if(Me)le.push(S.instancedDataBuffer),be.draw(_,B.gl.TRIANGLES,Z,an.disabled,Re,Xe,_e,d.id,ie.vertexBuffer,ie.indexBuffer,ie.segments,d.paint,_.transform.zoom,void 0,le,S.instancedDataArray.length);else{const $e=U?"u_instance":"u_normal_matrix";for(let Ke=0;KeU[1]?L:U,R[0]=g.max[0],L=a.aE(a.bE(),R,E),B=L[1]U[1]?L:U,R[1]=g.min[1],L=a.aE(a.bE(),R,E),B=L[1]U[1]?L:U;const W=a.aC(S[0],0,1),Z=100*d.pixelsPerMeter*a.aC(S[1],0,1),ne=a.aC(S[2],0,1),re=a.ey(a.bE(),B,U,W),ie=Math.tan(.5*d.fovX),ce=-re[2]*ie;if(Z===0)return re[1]<-Math.abs(ce)?ne:1;const le=(-Math.abs(ce)-re[1])/Z,be=(Re,Me,je)=>(1-je)*Re+je*Me,_e=a.aC(be(1,ne,le),ne,1);return be(1,_e,a.aC((d.pitch-20)/20,0,1))}class gw{}class vP{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(d,g,S){{const ne=this._storage.get(g.id);if(ne)return ne.lastUsedFrameIdx=d,ne.buf}const E=S.gl,R=E.getBufferParameter(E.ELEMENT_ARRAY_BUFFER,E.BUFFER_SIZE),L=new ArrayBuffer(R),B=new Int16Array(L);E.getBufferSubData(E.ELEMENT_ARRAY_BUFFER,0,new Int16Array(L));const U=new a.eA;for(let ne=0;ne30&&(S.buf.destroy(),this._storage.delete(g))}destroy(){for(const[d,g]of this._storage)g.buf.destroy(),this._storage.delete(d)}}class _P{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const wy=a.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class bP{constructor(d){this.revealStart=11,this.revealRange=2}}const AB=a.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class wP{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(d,g){const S=d.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const L=new a.eB,B=new a.dC;L.emplaceBack(-1,-1),L.emplaceBack(1,-1),L.emplaceBack(1,1),L.emplaceBack(-1,1),B.emplaceBack(0,1,2),B.emplaceBack(0,2,3),this.vignetteVx=d.context.createVertexBuffer(L,AB.members),this.vignetteIdx=d.context.createIndexBuffer(B)}const E=a.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){d.uploadCommonUniforms(d.context,S);const L={u_vignetteShape:(R={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:R.vignetteColor};S.draw(d,d.context.gl.TRIANGLES,Mr.disabled,an.disabled,tn.alphaBlended,Zr.disabled,L,"vignette",this.vignetteVx,this.vignetteIdx,E)}var R}}class yw{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(d,g){const S=d.getFreeCameraOptions().position,E=S.toAltitude(),R=S.toLngLat(),L=a.ap(R.lng),B=a.ap(R.lat),U=d.pixelsPerMeter/g,W=L*a.eD,Z=a.eD*Math.log(Math.tan(Math.PI/4+B/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 ne=-this._offsetYPrev+Z,re=-this._elevationPrev+E;this._accumulatedOffsetX+=(-this._offsetXPrev+W)*U,this._accumulatedOffsetY+=ne*U,this._accumulatedElevation+=re*U,this._offsetXPrev=W,this._offsetYPrev=Z,this._elevationPrev=E}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function xw(_,d){return[-(_[0]-Math.floor(_[0]/d)*d),-(_[1]-Math.floor(_[1]/d)*d),-(_[2]-Math.floor(_[2]/d)*d)]}function BE(_){const d=a.em(1323123451230),g=[];for(let S=0;S<_;++S){const E=2*d()-1,R=2*d()-1,L=2*d()-1;g.push(a.cQ(E,R,L))}return g}function Kh(_,d,g,S,E){const R=a.aC((E-g)/(S-g),0,1);return(1-R)*_+R*d}class pv{constructor(d){this._movement=new yw,this._accumulatedTimeFromStart=0,this._prevTime=Date.now()/1e3,this._vignette=new wP,this._ppmScaleFactor=d}destroy(){this.particlesVx&&this.particlesVx.destroy(),this.particlesIdx&&this.particlesIdx.destroy(),this._vignette&&this._vignette.destroy()}updateOnRender(d,g){const S=d.transform;this._movement.update(S,this._ppmScaleFactor);const E=S.starsProjMatrix,R=a.bL([]);a.bN(R,R,a.ap(90)-S._pitch),a.bM(R,R,-S.angle);const L=a.bR(new Float32Array(16),R),B=a.eC(1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1),U=a.e6([],B),W=a.aD([],U,L),Z=Date.now()/1e3;return this._accumulatedTimeFromStart+=(Z-this._prevTime)*g,this._prevTime=Z,{projectionMatrix:E,modelviewMatrix:W}}}class gv extends pv{constructor(d){super(4.25),this._params={overrideStyleParameters:!1,intensity:.5,timeFactor:1,velocityConeAperture:0,velocity:300,boxSize:2500,dropletSizeX:1,dropletSizeYScale:10,distortionStrength:70,screenThinning:{intensity:.57,start:.46,range:1.17,fadePower:.17,affectedRatio:1,particleOffset:-.2},color:{r:.66,g:.68,b:.74,a:.7},direction:{x:-50,y:-35},shapeDirPower:2,shapeNormalPower:1},this._revealParams=new bP("Precipitation > 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 S=BE(this.particlesCount),E=new a.eE,R=new a.dC;let L=0;const B=a.em(1323123451230);for(let U=0;US)return;const E=Kh(0,1,g.revealStart,g.revealStart+g.revealRange,S);if(!this.particlesVx||!this.particlesIdx)return;const R=structuredClone(this._params);let L=[-R.direction.x,R.direction.y,-100];a.ay(L,L);const B=structuredClone(this._vignetteParams);B.strength*=E,R.overrideStyleParameters||(R.intensity=d.style.rain.state.density,R.timeFactor=d.style.rain.state.intensity,R.color=structuredClone(d.style.rain.state.color),L=structuredClone(d.style.rain.state.direction),R.screenThinning.intensity=d.style.rain.state.centerThinning,R.dropletSizeX=d.style.rain.state.dropletSize[0],R.dropletSizeYScale=d.style.rain.state.dropletSize[1]/d.style.rain.state.dropletSize[0],R.distortionStrength=100*d.style.rain.state.distortionStrength,B.strength=1,B.color=structuredClone(d.style.rain.state.vignetteColor));const U=this.updateOnRender(d,R.timeFactor),W=d.context,Z=W.gl,ne=d.transform;this.screenTexture&&this.screenTexture.size[0]===d.width&&this.screenTexture.size[1]===d.height||(this.screenTexture=new a.T(W,{width:d.width,height:d.height,data:null},Z.RGBA8)),R.distortionStrength>0&&(W.activeTexture.set(Z.TEXTURE0),this.screenTexture.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),Z.copyTexSubImage2D(Z.TEXTURE_2D,0,0,0,0,0,d.width,d.height));const re=d.getOrCreateProgram("rainParticle");d.uploadCommonUniforms(W,re),W.activeTexture.set(Z.TEXTURE0),this.screenTexture.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const ie=[R.color.r,R.color.g,R.color.b,R.color.a],ce=(le,be)=>{const _e=xw(this._movement.getPosition(),le),Re=R.dropletSizeX,Me=R.dropletSizeX*R.dropletSizeYScale,je=d.width/2,Xe=d.height/2,$e=Kh(0,R.screenThinning.start,0,1,R.screenThinning.intensity),Ke=Kh(.001,R.screenThinning.range,0,1,R.screenThinning.intensity),De=Kh(0,R.screenThinning.particleOffset,0,1,R.screenThinning.intensity),Be=(Ge={modelview:U.modelviewMatrix,projection:U.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:_e,velocityConeAperture:R.velocityConeAperture,velocity:R.velocity,boxSize:le,rainDropletSize:[Re,Me],distortionStrength:R.distortionStrength,rainDirection:L,color:ie,screenSize:[ne.width,ne.height],thinningCenterPos:[je,Xe],thinningShape:[$e,Ke,Math.pow(10,R.screenThinning.fadePower)],thinningAffectedRatio:R.screenThinning.affectedRatio,thinningParticleOffset:De,shapeDirectionalPower:R.shapeDirPower,shapeNormalPower:R.shapeNormalPower,mode:be?0:1},{u_modelview:Float32Array.from(Ge.modelview),u_projection:Float32Array.from(Ge.projection),u_time:Ge.time,u_cam_pos:Ge.camPos,u_texScreen:0,u_velocityConeAperture:Ge.velocityConeAperture,u_velocity:Ge.velocity,u_boxSize:Ge.boxSize,u_rainDropletSize:Ge.rainDropletSize,u_distortionStrength:Ge.distortionStrength,u_rainDirection:Ge.rainDirection,u_color:Ge.color,u_screenSize:Ge.screenSize,u_thinningCenterPos:Ge.thinningCenterPos,u_thinningShape:Ge.thinningShape,u_thinningAffectedRatio:Ge.thinningAffectedRatio,u_thinningParticleOffset:Ge.thinningParticleOffset,u_shapeDirectionalPower:Ge.shapeDirectionalPower,u_shapeNormalPower:Ge.shapeNormalPower,u_mode:Ge.mode});var Ge;const ot=Math.round(R.intensity*this.particlesCount),Je=a.dy.simpleSegment(0,0,4*ot,2*ot);re.draw(d,Z.TRIANGLES,Mr.disabled,an.disabled,tn.alphaBlended,Zr.disabled,Be,"rain_particles",this.particlesVx,this.particlesIdx,Je)};R.distortionStrength>0&&ce(R.boxSize,!0),ce(R.boxSize,!1),this._vignette.draw(d,B)}}const Lp=a.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 SP extends pv{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 bP("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 S=BE(this.particlesCount),E=new a.eF,R=new a.dC;let L=0;const B=a.em(1323123451230);for(let U=0;UL)return;const B=Kh(0,1,R.revealStart,R.revealStart+R.revealRange,L);E.strength*=B,g.overrideStyleParameters||(g.intensity=d.style.snow.state.density,g.timeFactor=d.style.snow.state.intensity,g.color=structuredClone(d.style.snow.state.color),S=structuredClone(d.style.snow.state.direction),g.screenThinning.intensity=d.style.snow.state.centerThinning,g.billboardSize=2.79*d.style.snow.state.flakeSize,E.strength=1,E.color=structuredClone(d.style.snow.state.vignetteColor));const U=this.updateOnRender(d,g.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const W=d.context,Z=W.gl,ne=d.transform,re=d.getOrCreateProgram("snowParticle");d.uploadCommonUniforms(W,re),((ie,ce,le)=>{const be=xw(this._movement.getPosition(),ie),_e=ne.width/2,Re=ne.height/2,Me=Kh(0,le.screenThinning.start,0,1,le.screenThinning.intensity),je=Kh(.001,le.screenThinning.range,0,1,le.screenThinning.intensity),Xe=Kh(0,le.screenThinning.particleOffset,0,1,le.screenThinning.intensity),$e=(Ke={modelview:U.modelviewMatrix,projection:U.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:be,velocityConeAperture:le.velocityConeAperture,velocity:le.velocity,horizontalOscillationRadius:le.horizontalOscillationRadius,horizontalOscillationRate:le.horizontalOscillationRate,boxSize:ie,billboardSize:1*le.billboardSize,simpleShapeParameters:[le.shapeFadeStart,le.shapeFadePower],screenSize:[ne.width,ne.height],thinningCenterPos:[_e,Re],thinningShape:[Me,je,Math.pow(10,le.screenThinning.fadePower)],thinningAffectedRatio:le.screenThinning.affectedRatio,thinningParticleOffset:Xe,color:[le.color.r,le.color.g,le.color.b,le.color.a],direction:S},{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(le.intensity*this.particlesCount),Be=a.dy.simpleSegment(0,0,4*De,2*De);this.particlesVx&&this.particlesIdx&&re.draw(d,Z.TRIANGLES,Mr.disabled,an.disabled,tn.alphaBlended,Zr.disabled,$e,"snow_particles",this.particlesVx,this.particlesIdx,Be)})(g.boxSize,0,g),this._vignette.draw(d,E)}}const TP={symbol:function(_,d,g,S,E){if(_.renderPass!=="translucent")return;const R=an.disabled,L=_.colorModeForRenderPass(),B=g.layout.get("text-variable-anchor"),U=g.layout.get("text-size-scale-range"),W=a.aC(_.scaleFactor,U[0],U[1]);B&&function(re,ie,ce,le,be,_e,Re,Me){const je=ie.transform,Xe=be==="map",$e=_e==="map";for(const Ke of re){const De=le.getTile(Ke),Be=De.getBucket(ce);if(!Be||!Be.text||!Be.text.segments.get().length)continue;const Ge=a.bj(Be.textSizeData,je.zoom,Me),ot=vp(Ke,Be.getProjection(),je),Je=je.calculatePixelsToTileUnitsMatrix(De),St=Kf(ot,De.tileID.canonical,$e,Xe,je,Be.getProjection(),Je),pt=Be.hasIconTextFit()&&Be.hasIconData();Ge&&oP(Be,Xe,$e,Re,je,St,Ke,Math.pow(2,je.zoom-De.tileID.overscaledZ),Ge,pt)}}(S,_,g,d,g.layout.get("text-rotation-alignment"),g.layout.get("text-pitch-alignment"),E,W);const Z=g.paint.get("icon-opacity").constantOr(1)!==0,ne=g.paint.get("text-opacity").constantOr(1)!==0;g.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Z||ne)?aw(_,d,g,S,R,L):(Z&&aw(_,d,g,S,R,L,{onlyIcons:!0}),ne&&aw(_,d,g,S,R,L,{onlyText:!0})),d.map.showCollisionBoxes&&(jr(_,d,g,S,g.paint.get("text-translate"),g.paint.get("text-translate-anchor"),!0),jr(_,d,g,S,g.paint.get("icon-translate"),g.paint.get("icon-translate-anchor"),!1))},circle:function(_,d,g,S){if(_.renderPass!=="translucent")return;const E=g.paint.get("circle-opacity"),R=g.paint.get("circle-stroke-width"),L=g.paint.get("circle-stroke-opacity"),B=g.layout.get("circle-sort-key").constantOr(1)!==void 0,U=g.paint.get("circle-emissive-strength");if(E.constantOr(1)===0&&(R.constantOr(1)===0||L.constantOr(1)===0))return;const W=_.context,Z=W.gl,ne=_.transform,re=!(!_.terrain||!_.terrain.enabled),ie=g.layout.get("circle-elevation-reference"),ce=_.depthModeForSublayer(0,Mr.ReadOnly),le=new Mr(_.context.gl.LEQUAL,Mr.ReadOnly,_.depthRangeFor3D),be=ie==="none"||re?ce:le,_e=an.disabled,Re=_.colorModeForDrapableLayerRenderPass(U),Me=ne.projection.name==="globe",je=[a.aH(ne.center.lng),a.aL(ne.center.lat)],Xe=[];for(let Ke=0;KeKe.sortKey-De.sortKey);const $e={useDepthForOcclusion:ne.depthOcclusionForSymbolsAndCircles};for(const Ke of Xe){const{programConfiguration:De,program:Be,layoutVertexBuffer:Ge,dynamicBuffers:ot,indexBuffer:Je,uniformValues:St,tile:pt}=Ke.state,Ot=Ke.segments;_.terrain&&_.terrain.setupElevationDraw(pt,Be,$e),_.uploadCommonUniforms(W,Be,pt.tileID.toUnwrapped()),Be.draw(_,Z.TRIANGLES,be,_e,Re,Zr.disabled,St,g.id,Ge,Je,Ot,g.paint,ne.zoom,De,ot)}},heatmap:function(_,d,g,S){if(g.paint.get("heatmap-opacity")!==0)if(_.renderPass==="offscreen"){const E=_.context,R=E.gl,L=an.disabled,B=new tn([R.ONE,R.ONE,R.ONE,R.ONE],a.aq.transparent,[!0,!0,!0,!0]),U=_.transform.projection.name==="globe"?.5:.25;g.heatmapFbo=uv.createWithTexture(E,g.heatmapFbo,_.width*U,_.height*U),E.clear({color:a.aq.transparent});const W=_.transform,Z=W.projection.name==="globe",ne=Z?["PROJECTION_GLOBE_VIEW"]:[],re=Z?Zr.frontCCW:Zr.disabled,ie=[a.aH(W.center.lng),a.aL(W.center.lat)];for(let ce=0;ce({u_image:0,u_color_ramp:1,u_opacity:ne.paint.get("heatmap-opacity")}))(0,R),R.id,E.viewportBuffer,E.quadTriangleIndexBuffer,E.viewportSegments,R.paint,E.transform.zoom)}(_,g))},line:function(_,d,g,S){const E=g.paint.get("line-opacity"),R=g.paint.get("line-width");if(E.constantOr(1)===0||R.constantOr(1)===0)return;const L=g.paint.get("line-blend-mode");if(L!=="default"&&_.transform.projection.name!=="globe")return _.terrain&&_.terrain.renderingToTexture?void function(B,U,W,Z,ne){if(B.renderPass!=="translucent")return;const re=B.context,ie=re.gl,ce=B.terrain;if(!ce)return;const le=re.bindFramebuffer.current,be=B.emissiveMode==="mrt-fallback";W.lineBlendDrapeFbo=uv.createWithTexture(re,W.lineBlendDrapeFbo,ce.drapeBufferSize[0],ce.drapeBufferSize[1],!0),W.lineBlendDrapeStencil=W.lineBlendDrapeFbo._stencilRbo,be&&ie.drawBuffers([ie.COLOR_ATTACHMENT0]),re.clear({color:Gh[ne].clearColor,depth:1,stencil:0});const _e=B.currentStencilSource,Re=B._tileClippingMaskIDs,Me=B.nextStencilID;B.currentStencilSource=void 0,B._tileClippingMaskIDs={},B.nextStencilID=1;const je=B._terrain;B._terrain=null,B._renderTileClippingMasks(W,U,Z),lw(B,U,W,Z,Gh[ne].colorMode,!0),B._terrain=je,B.currentStencilSource=_e,B._tileClippingMaskIDs=Re,B.nextStencilID=Me,re.bindFramebuffer.set(le),be&&ie.drawBuffers([ie.COLOR_ATTACHMENT0,ie.COLOR_ATTACHMENT1]);const Xe=ce.drapeBufferSize;re.viewport.set([0,0,Xe[0],Xe[1]]);const $e=W.lineBlendDrapeFbo;if(!$e)return;re.activeTexture.set(ie.TEXTURE0),ie.bindTexture(ie.TEXTURE_2D,$e.colorAttachment0.get());const Ke=ne==="additive"?1:W.paint.get("line-opacity").constantOr(1),De=W.paint.get("line-emissive-strength").constantOr(0),Be=ne==="additive"?B.colorModeForDrapableLayerRenderPass(De):Gh[ne].colorMode;B.getOrCreateProgram("lineBlendComposite").draw(B,ie.TRIANGLES,Mr.disabled,an.disabled,Be,Zr.disabled,Jb(0,Ke,Gh[ne].compositeUniformValue),W.id,B.viewportBuffer,B.quadTriangleIndexBuffer,B.viewportSegments,W.paint,B.transform.zoom)}(_,d,g,S,L):_.renderPass==="offscreen"?void function(B,U,W,Z,ne){const re=B.context,ie=Math.ceil(B.width),ce=Math.ceil(B.height);W.lineBlendFbo=uv.createWithTexture(re,W.lineBlendFbo,ie,ce,!0),W.lineBlendStencil=W.lineBlendFbo._stencilRbo,re.clear({color:Gh[ne].clearColor,depth:1,stencil:0});const le=B.currentStencilSource,be=B._tileClippingMaskIDs,_e=B.nextStencilID;B.currentStencilSource=void 0,B._tileClippingMaskIDs={},B.nextStencilID=1,B._renderTileClippingMasks(W,U,Z);const Re=B.renderPass;B.renderPass="translucent",lw(B,U,W,Z,Gh[ne].colorMode),B.renderPass=Re,B.currentStencilSource=le,B._tileClippingMaskIDs=be,B.nextStencilID=_e,re.viewport.set([0,0,B.width,B.height])}(_,d,g,S,L):_.renderPass==="translucent"?void function(B,U,W){const Z=B.context,ne=Z.gl,re=U.lineBlendFbo;if(!re)return;Z.activeTexture.set(ne.TEXTURE0),ne.bindTexture(ne.TEXTURE_2D,re.colorAttachment0.get());const ie=W==="additive"?1:U.paint.get("line-opacity").constantOr(1),ce=W==="additive"?B.colorModeForDrapableLayerRenderPass(U.paint.get("line-emissive-strength").constantOr(0)):Gh[W].colorMode;B.getOrCreateProgram("lineBlendComposite").draw(B,ne.TRIANGLES,Mr.disabled,an.disabled,ce,Zr.disabled,Jb(0,ie,Gh[W].compositeUniformValue),U.id,B.viewportBuffer,B.quadTriangleIndexBuffer,B.viewportSegments,U.paint,B.transform.zoom)}(_,g,L):void 0;_.renderPass==="translucent"&&lw(_,d,g,S)},fill:function(_,d,g,S){const E=g.paint.get("fill-color"),R=g.paint.get("fill-opacity");if(R.constantOr(1)===0)return;const L=g.paint.get("fill-emissive-strength"),B=_.colorModeForDrapableLayerRenderPass(L),U=g.paint.get("fill-pattern"),W=_.opaquePassEnabledForLayer()&&!U.constantOr(1)&&E.constantOr(a.aq.transparent).a===1&&R.constantOr(0)===1?"opaque":"translucent";let Z="none";g.layout.get("fill-elevation-reference")!=="none"?Z="road":g.paint.get("fill-z-offset").constantOr(1)!==0&&(Z="offset");const ne=!(!_.terrain||!_.terrain.enabled),re={painter:_,sourceCache:d,layer:g,coords:S,colorMode:B,elevationType:Z,terrainEnabled:ne,pass:W};if(_.renderPass==="shadow")return void(_.shadowRenderer&&Z==="road"&&!ne&&function(ce){const{painter:le,sourceCache:be,layer:_e,coords:Re}=ce,Me=le.context.gl,je=ce.painter.shadowRenderer;for(const Xe of Re){const $e=be.getTile(Xe),Ke=$e.getBucket(_e);if(!Ke)continue;const De=Ke.elevatedStructures;if(!De||!De.shadowCasterSegments||De.shadowCasterSegments.segments[0].primitiveLength===0)continue;le.prepareDrawTile();const Be=Ke.bufferData.programConfigurations.get(_e.id),Ge=le.isTileAffectedByFog(Xe),ot=le.getOrCreateProgram("elevatedStructuresDepth",{config:Be,overrideFog:Ge}),Je=je.calculateShadowPassMatrixFromTile($e.tileID.toUnwrapped());le.uploadCommonUniforms(le.context,ot,Xe.toUnwrapped());const St=QI(Je,0);ot.draw(le,Me.TRIANGLES,je.getShadowPassDepthMode(),an.disabled,tn.disabled,Zr.disabled,St,_e.id,De.vertexBuffer,De.indexBuffer,De.shadowCasterSegments,_e.paint,le.transform.zoom,Be)}}(re));const ie=_.emissiveMode==="mrt-fallback";if(Z!=="offset"){if(fv(re,!1,ie),Z==="road"){const ce=!ne&&_.renderPass==="translucent";ce&&hv(_,d,g,S,"geometry"),fv(re,!0,ie,an.disabled),ce&&function(le){const{painter:be,sourceCache:_e,layer:Re,coords:Me,colorMode:je}=le,Xe=be.context.gl,$e=le.painter.shadowRenderer,Ke=!!$e&&$e.enabled,De=new Mr(be.context.gl.LEQUAL,Mr.ReadOnly,be.depthRangeFor3D);let Be=[0,0,0];if(Ke){const ot=be.style.directionalLight,Je=be.style.ambientLight;ot&&Je&&(Be=fd(be.style,ot,Je))}const Ge=ot=>{for(const Je of Me){const St=_e.getTile(Je),pt=St.getBucket(Re);if(!pt)continue;const Ot=pt.elevatedStructures;if(!Ot)continue;let Ut,ut;if(ot?(Ut=Ot.renderableBridgeSegments,ut=Ot.bridgeProgramConfigurations.get(Re.id)):(Ut=Ot.renderableTunnelSegments,ut=Ot.tunnelProgramConfigurations.get(Re.id)),!Ut||Ut.segments[0].primitiveLength===0)continue;ut.updatePaintBuffers(),be.prepareDrawTile();const st=be.isTileAffectedByFog(Je),_t=[];Ke&&_t.push("RENDER_SHADOWS","NORMAL_OFFSET");const jt=be.getOrCreateProgram("elevatedStructures",{config:ut,overrideFog:st,defines:_t}),Nt=be.translatePosMatrix(Je.projMatrix,St,Re.paint.get("fill-translate"),Re.paint.get("fill-translate-anchor"));Ke&&$e.setupShadows(St.tileID.toUnwrapped(),jt,"vector-tile");const lr=JI(Nt,Be);be.uploadCommonUniforms(be.context,jt,Je.toUnwrapped()),jt.draw(be,Xe.TRIANGLES,De,an.disabled,je,Zr.backCCW,lr,Re.id,Ot.vertexBuffer,Ot.indexBuffer,Ut,Re.paint,be.transform.zoom,ut,[Ot.vertexBufferNormal])}};Ge(!0),Ge(!1)}(re)}}else fv(re,!1,ie,_.stencilModeFor3D())},"fill-extrusion":function(_,d,g,S){const E=g.paint.get("fill-extrusion-opacity"),R=_.context,L=R.gl,B=_.terrain,U=B&&B.renderingToTexture;if(E===0)return;const W=_.emissiveMode==="mrt-fallback",Z=_.conflationActive&&_.style.isLayerClipped(g,d.getSource()),ne=_.style.order.indexOf(g.fqid);if(Z&&function(re,ie,ce,le,be){for(const _e of le){const Re=ie.getTile(_e).getBucket(ce);Re&&(Re.updateReplacement(_e,re.replacementSource,be),Re.uploadCentroid(re.context))}}(_,d,g,S,ne),B||Z)for(const re of S){const ie=d.getTile(re).getBucket(g);ie&&lP(_.context,d,re,ie,g,B,Z)}if(_.renderPass==="shadow"&&_.shadowRenderer){if(B&&E<.65&&g._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof a.af)return;const re=_.shadowRenderer.getShadowPassDepthMode();Ip(_,d,g,S,re,an.disabled,tn.disabled,Z)}else if(_.renderPass==="translucent"){const re=!g.paint.get("fill-extrusion-pattern").constantOr(1),ie=g.paint.get("fill-extrusion-color").constantOr(a.aq.white);if(!U&&ie.a!==0){const ce=new Mr(_.context.gl.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D);E===1&&re?Ip(_,d,g,S,ce,an.disabled,tn.unblended,Z):(Ip(_,d,g,S,ce,an.disabled,tn.disabled,Z),Ip(_,d,g,S,ce,_.stencilModeFor3D(),_.colorModeForRenderPass(),Z),_.resetStencilClippingMasks())}if(_.style.enable3dLights()&&re&&(!B&&_.transform.projection.name!=="globe"||U)){const ce=g.paint.get("fill-extrusion-opacity"),le=g.paint.get("fill-extrusion-ambient-occlusion-intensity"),be=g.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),_e=g.paint.get("fill-extrusion-flood-light-intensity"),Re=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Me=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Re?null:g.lut).toArray01().slice(0,3),je=le>0&&be>0,Xe=_e>0,$e=(Be,Ge,ot)=>(1-ot)*Be+ot*Ge,Ke=new wE;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 Ge=_.depthModeForSublayer(1,Mr.ReadOnly,L.LEQUAL,!0),ot=g.paint.get(Be?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Je=$e(.1,3,ot),St=_._showOverdrawInspector;if(!St){const pt=new an({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),Ot=new tn([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0],L.MIN);eh(Ke,_,d,g,S,Ge,pt,Ot,Zr.disabled,Be,"sdf",ce,le,be,_e,Me,Je,Z,!1)}{const pt=St?an.disabled:new an({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),Ot=St?_.colorModeForRenderPass():new tn([L.ONE_MINUS_DST_ALPHA,L.DST_ALPHA,L.ONE,L.ONE],a.aq.transparent,[!0,!0,!0,!0]);eh(Ke,_,d,g,S,Ge,pt,Ot,Zr.disabled,Be,"color",ce,le,be,_e,Me,Je,Z,!1)}};if(U){const Be=()=>{const ot=B.drapeBufferSize[0],Je=B.drapeBufferSize[1];let St=B.framebufferCopyTexture;return St&&(!St||St.size[0]===ot&&St.size[1]===Je)||(St&&St.destroy(),St=B.framebufferCopyTexture=new a.T(R,new a.q({width:ot,height:Je}),L.RGBA8)),St.bind(L.LINEAR,L.CLAMP_TO_EDGE),L.copyTexSubImage2D(L.TEXTURE_2D,0,0,0,0,0,ot,Je),St},Ge=(ot,Je,St)=>{const pt=_.depthModeForSublayer(1,Mr.ReadOnly,L.LEQUAL,!1),Ot=g.paint.get(ot?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ut=$e(.1,3,Ot);{const ut=new tn([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0]);eh(Ke,_,d,g,S,pt,an.disabled,ut,Zr.disabled,ot,"clear",ce,le,be,_e,Me,Ut,Z,Je)}{const ut=new an({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),st=new tn([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0],L.MIN);eh(Ke,_,d,g,S,pt,ut,st,Zr.disabled,ot,"sdf",ce,le,be,_e,Me,Ut,Z,Je)}W&&!ot&&(St=Be());{const ut=ot?L.ZERO:L.ONE_MINUS_DST_ALPHA,st=new an({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),_t=new tn([ut,L.DST_ALPHA,L.ONE_MINUS_DST_ALPHA,L.ZERO],a.aq.transparent,[!0,!0,!0,!0]);eh(Ke,_,d,g,S,pt,st,_t,Zr.disabled,ot,"color",ce,le,be,_e,Me,Ut,Z,Je)}if(!W||ot){const ut=new tn([L.ONE,L.ONE,L.ONE,ot?L.ZERO:L.ONE],a.aq.transparent,[!1,!1,!1,!0],ot?L.FUNC_ADD:L.MAX);eh(Ke,_,d,g,S,pt,an.disabled,ut,Zr.disabled,ot,"clear",ce,le,be,_e,Me,Ut,Z,Je,St)}else{L.drawBuffers([L.NONE,L.COLOR_ATTACHMENT1]);const ut=new an({func:L.EQUAL,mask:255},254,255,L.KEEP,L.DECR,L.DECR),st=new tn([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!0,!1,!1,!1],L.MAX);eh(Ke,_,d,g,S,pt,ut,st,Zr.disabled,ot,"emissive",ce,le,be,_e,Me,Ut,Z,Je,St),L.drawBuffers([L.COLOR_ATTACHMENT0])}};if(je||Xe){let ot;_.prepareDrawTile(),W&&!je||(ot=Be()),je&&Ge(!0,!1,ot),Xe&&Ge(!1,!0,ot)}}else je&&De(!0),Xe&&De(!1),(je||Xe)&&_.resetStencilClippingMasks()}}},building:function(_,d,g,S){_.currentLayer<_.firstLightBeamLayer&&(_.firstLightBeamLayer=_.currentLayer);const E=g.paint.get("building-ambient-occlusion-ground-intensity"),R=g.paint.get("building-ambient-occlusion-ground-radius"),L=g.paint.get("building-ambient-occlusion-ground-attenuation"),B=g.paint.get("building-opacity");if(B<=0)return;let U=E>0&&R>0,W=!0;const Z=g.paint.get("building-vertical-scale");if(Z<=0)return;_.shadowRenderer||(W=!1);const ne=_.conflationActive&&_.style.isLayerClipped(g,d.getSource()),re=_.style.order.indexOf(g.fqid);if(function(ie,ce,le,be,_e,Re){for(const Me of Re){const je=ce.getTile(Me).getBucket(le);je&&(_e&&je.updateReplacement(Me,ie.replacementSource,be),je.uploadUpdatedIndexBuffer(ie.context))}}(_,d,g,re,ne,S),function(ie,ce,le,be){for(const _e of be){const Re=ce.getTile(_e).getBucket(le);Re&&Re.needsEvaluation()&&Re.uploadUpdatedColorBuffer(ie.context)}}(_,d,g,S),g.resetLayerRenderingStats(_),_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0),_.renderPass==="shadow"&&_.shadowRenderer){const ie=[],ce=_.shadowRenderer.getShadowPassDepthMode();mv({painter:_,source:d,layer:g,coords:S,defines:ie,blendMode:tn.disabled,depthMode:ce,opacity:B,verticalScale:Z,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(_.renderPass==="translucent"){let ie=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];W&&(ie=ie.concat("RENDER_SHADOWS")),_.shadowRenderer&&_.shadowRenderer.useNormalOffset&&(ie=ie.concat("NORMAL_OFFSET"));const ce=g.paint.get("building-facade-emissive-chance"),le=g.paint.get("building-ambient-occlusion-intensity"),be=g.paint.get("building-flood-light-intensity"),_e=g.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Re=g.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(_e?null:g.lut).toArray01().slice(0,3),Me=g.paint.get("building-flood-light-ground-attenuation"),je=be>0,Xe=new Mr(_.context.gl.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D);B<1&&mv({painter:_,source:d,layer:g,coords:S,defines:ie,blendMode:tn.disabled,depthMode:Xe,opacity:B,verticalScale:Z,facadeEmissiveChance:ce,facadeAOIntensity:le,floodLightIntensity:be,floodLightColor:Re,depthOnly:!0});const $e=_.colorModeForRenderPass();mv({painter:_,source:d,layer:g,coords:S,defines:ie,blendMode:$e,depthMode:Xe,opacity:B,verticalScale:Z,facadeEmissiveChance:ce,facadeAOIntensity:le,floodLightIntensity:be,floodLightColor:Re});const Ke=g.paint.get("building-front-cutoff");cw(_.transform.pitch,Ke,!!_.terrain),U&&TE(_,d,g,S,!0,B,E,R,be,Re,L,ne),je&&TE(_,d,g,S,!1,B,E,R,be,Re,Me,ne)}else if(_.renderPass==="light-beam"){const ie=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ce=new Mr(_.context.gl.LEQUAL,Mr.ReadOnly,_.depthRangeFor3D);mv({painter:_,source:d,layer:g,coords:S,defines:ie,blendMode:tn.alphaBlended,depthMode:ce,opacity:B,verticalScale:Z,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1),_.resetStencilClippingMasks()},hillshade:function(_,d,g,S){if(_.renderPass!=="offscreen"&&_.renderPass!=="translucent"||_.style.disableElevatedTerrain)return;const E=_.context,R=_.terrain&&_.terrain.renderingToTexture,[L,B]=_.renderPass!=="translucent"||R?[{},S]:_.stencilConfigForOverlap(S);for(const U of B){const W=d.getTile(U);if(W.needsHillshadePrepare&&_.renderPass==="offscreen")hB(_,W,g);else if(_.renderPass==="translucent"){const Z=_.depthModeForSublayer(0,Mr.ReadOnly),ne=g.paint.get("hillshade-emissive-strength"),re=_.colorModeForDrapableLayerRenderPass(ne),ie=R&&_.terrain?_.terrain.stencilModeForRTTOverlap(U):L[U.overscaledZ];dB(_,U,W,g,Z,ie,re)}}E.viewport.set([0,0,_.width,_.height]),_.resetStencilClippingMasks()},raster:function(_,d,g,S,E,R){if(_.renderPass!=="translucent")return;const L=g.paint.get("raster-opacity");if(L===0)return;const B=_.transform.projection.name==="globe",U=g.paint.get("raster-elevation")!==0,W=U&&B,Z=_.terrain&&_.terrain.exaggeration()>0&&U&&g.paint.get("raster-elevation-reference")==="ground",ne=!B&&Z;if(_.renderElevatedRasterBackface&&!W)return;const re=_.context,ie=re.gl,ce=d.getSource(),le=function(Be,Ge,ot,Je,St){const pt=Ge.paint.get("raster-color"),Ot=Be.type==="raster-array",Ut=[],ut=Ge.paint.get("raster-resampling"),st=Ge.paint.get("raster-color-mix");let _t=Ge.paint.get("raster-color-range");const jt=[st[0],st[1],st[2],0],Nt=st[3];let lr=ut==="nearest"?Je.NEAREST:Je.LINEAR;if(Ot&&(Ut.push("RASTER_ARRAY"),pt||Ut.push("RASTER_COLOR"),ut==="linear"&&Ut.push("RASTER_ARRAY_LINEAR"),lr=Je.NEAREST,!_t&&Be.rasterLayers)){const Jt=Be.rasterLayers.find(({id:er})=>er===Ge.sourceLayer);Jt&&Jt.fields&&Jt.fields.range&&(_t=Jt.fields.range)}if(_t=_t||[0,1],pt){Ut.push("RASTER_COLOR"),ot.activeTexture.set(Je.TEXTURE2),Ge.updateColorRamp(_t);let Jt=Ge.colorRampTexture;Jt||(Jt=Ge.colorRampTexture=new a.T(ot,Ge.colorRamp,Je.RGBA8)),Jt.bind(lr,Je.CLAMP_TO_EDGE)}return St&&Ut.push("USE_MRT1"),{mix:jt,range:_t,offset:Nt,defines:Ut,resampling:lr}}(ce,g,re,ie,_.terrain&&_.terrain.renderingToTexture&&_.emissiveMode==="mrt-fallback");if(ce instanceof a.aV&&!S.length&&!B)return;const be=g.paint.get("raster-emissive-strength"),_e=_.colorModeForDrapableLayerRenderPass(be),Re=_.terrain&&_.terrain.renderingToTexture,Me=!_.options.moving,je=g.paint.get("raster-resampling")==="nearest"?ie.NEAREST:ie.LINEAR;if(ce instanceof a.aV&&!S.length&&(ce.onNorthPole||ce.onSouthPole)){const Be=U?_.stencilModeFor3D():an.disabled;return void dw(!!ce.onNorthPole,null,_,d,g,be,le,Zr.disabled,Be)}if(!S.length)return;const[Xe,$e]=ce instanceof a.aV||Re?[{},S]:_.stencilConfigForOverlap(S),Ke=$e[$e.length-1].overscaledZ;W&&le.defines.push("PROJECTION_GLOBE_VIEW"),U&&le.defines.push("RENDER_CUTOFF","ELEVATED"),Z&&le.defines.push("ELEVATION_REFERENCE_GROUND");const De=(Be,Ge,ot)=>{for(const Je of Be){const St=Je.toUnwrapped(),pt=d.getTile(Je);if(Re&&(!pt||!pt.hasData()))continue;re.activeTexture.set(ie.TEXTURE0);const Ot=dP(pt,ce,g,le);if(!Ot||!Ot.texture)continue;const{texture:Ut,mix:ut,offset:st,tileSize:_t,buffer:jt}=Ot;let Nt,lr;Re?(Nt=Mr.disabled,lr=Je.projMatrix):U?(Nt=new Mr(ie.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D),lr=B?Float32Array.from(_.transform.expandedFarZProjMatrix):_.transform.calculateProjMatrix(St,Me)):(Nt=_.depthModeForSublayer(Je.overscaledZ-Ke,L===1?Mr.ReadWrite:Mr.ReadOnly,ie.LESS),lr=_.transform.calculateProjMatrix(St,Me));const Jt=_.terrain&&Re?_.terrain.stencilModeForRTTOverlap(Je):Xe[Je.overscaledZ],er=R?0:g.paint.get("raster-fade-duration");pt.registerFadeDuration(er);const zt=d.findLoadedParent(Je,0),Pr=iv(pt,zt,d,_.transform,er);let Fr,br;!Pr.isFading&&pt.refreshedUponExpiration&&(pt.refreshedUponExpiration=!1),_.terrain&&_.terrain.prepareDrawTile(),re.activeTexture.set(ie.TEXTURE0),Ut.bind(je,ie.CLAMP_TO_EDGE),re.activeTexture.set(ie.TEXTURE1),zt?(zt.texture&&zt.texture.bind(je,ie.CLAMP_TO_EDGE),Fr=Math.pow(2,zt.tileID.overscaledZ-pt.tileID.overscaledZ),br=[pt.tileID.canonical.x*Fr%1,pt.tileID.canonical.y*Fr%1]):Ut.bind(je,ie.CLAMP_TO_EDGE),"useMipmap"in Ut&&re.extTextureFilterAnisotropic&&_.transform.pitch>20&&ie.texParameterf(ie.TEXTURE_2D,re.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,re.extTextureFilterAnisotropicMax);const Nr=_.transform;let Jr;const dn=U?EE(Nr):[0,0,0,0];let on,Tn,Kr,jn,ln,ts=0;if(W&&ce instanceof a.aV&&ce.coordinates.length>3)on=Float32Array.from(a.du(a.dv(new a.cn(0,0,0)))),Tn=Float32Array.from(Nr.globeMatrix),Kr=Float32Array.from(a.dq(Nr)),jn=[a.aH(Nr.center.lng),a.aL(Nr.center.lat)],Jr=ce.elevatedGlobePerspectiveTransform,ln=ce.elevatedGlobeGridMatrix||new Float32Array(9);else if(W){const ds=a.dr(Je.canonical);ts=a.ds(ds.getCenter().lat),on=Float32Array.from(a.du(a.dv(Je.canonical))),Tn=Float32Array.from(Nr.globeMatrix),Kr=Float32Array.from(a.dq(Nr)),jn=[a.aH(Nr.center.lng),a.aL(Nr.center.lat)],Jr=[0,0],ln=Float32Array.from(a.dt(Je.canonical,ds,ts,Nr.worldSize/Nr._pixelsPerMercatorPixel))}else Jr=ce instanceof a.aV?ce.perspectiveTransform:[0,0],on=new Float32Array(16),Tn=new Float32Array(9),Kr=new Float32Array(16),jn=[0,0],ln=new Float32Array(9);const Cs=rP(_,lr,on,Tn,Kr,ln,br||[0,0],a.al(_.transform.zoom),jn,dn,Fr||1,Pr,g,Jr,U?g.paint.get("raster-elevation"):0,2,ut,st,le.range,_t,jt,be),li=_.isTileAffectedByFog(Je),Fs=_.getOrCreateProgram("raster",{defines:le.defines,overrideFog:li});if(_.uploadCommonUniforms(re,Fs,St),ce instanceof a.aV){const ds=ce.elevatedGlobeVertexBuffer,_n=ce.elevatedGlobeIndexBuffer;if(Re||!B)ce.boundsBuffer&&ce.boundsSegments&&Fs.draw(_,ie.TRIANGLES,Nt,an.disabled,_e,Zr.disabled,Cs,g.id,ce.boundsBuffer,_.quadTriangleIndexBuffer,ce.boundsSegments);else if(ds&&_n){const bn=Nr.zoom<=a.cJ?ce.elevatedGlobeSegments:ce.getSegmentsForLongitude(Nr.center.lng);bn&&Fs.draw(_,ie.TRIANGLES,Nt,an.disabled,_e,Ge,Cs,g.id,ds,_n,bn)}}else if(W){Nt=new Mr(ie.LEQUAL,Mr.ReadOnly,_.depthRangeFor3D);const ds=_.globeSharedBuffers;if(ds){Z&&(_.terrain.setupElevationDraw(pt,Fs),_.uploadCommonUniforms(re,Fs,pt.tileID.toUnwrapped()));const[_n,bn,Bs]=ds.getGridBuffers(ts,!1),mi=Fs.getAttributeLocation(ie,"a_texture_pos");mi!==-1&&ie.vertexAttribI4ui(mi,0,0,0,0),Fs.draw(_,ie.TRIANGLES,Nt,ot||Jt,_.colorModeForRenderPass(),Ge,Cs,g.id,_n,bn,Bs)}}else if(ne)Nt=new Mr(ie.LEQUAL,Mr.ReadWrite,_.depthRangeFor3D),_.terrain.setupElevationDraw(pt,Fs),_.uploadCommonUniforms(re,Fs,pt.tileID.toUnwrapped()),Nr.pitch>20&&Fs.draw(_,ie.TRIANGLES,Nt,an.disabled,tn.disabled,Zr.frontCCW,Cs,g.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments),Fs.draw(_,ie.TRIANGLES,Nt,Jt,_e,Zr.backCCW,Cs,g.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments);else{const{tileBoundsBuffer:ds,tileBoundsIndexBuffer:_n,tileBoundsSegments:bn}=_.getTileBoundsBuffers(pt);Fs.draw(_,ie.TRIANGLES,Nt,Jt,_e,Zr.disabled,Cs,g.id,ds,_n,bn)}}if(!(ce instanceof a.aV)&&W)for(const Je of Be){const St=Je.canonical.y===(1<a.d$[jt](St));ut.push(St);const st=St.canonical.x,_t=St.canonical.y;for(const jt of ut){const Nt=je.getTile(Ge?jt.wrapped():jt);if(!Nt)continue;const lr=Nt.rasterParticleState;if(!lr)continue;const Jt=jt.canonical.x+(1<Ke.tileID)),ie&&(W.activeTexture.set(Z.TEXTURE0),_.imageManager.bind(_.context,g.scope));const $e=[];if(_.terrain&&_.terrain.renderingToTexture&&_.emissiveMode==="mrt-fallback"&&$e.push("USE_MRT1"),U){const Ke=_.getOrCreateProgram(Me,{overrideFog:!1,overrideRtt:!0,defines:$e}),De=new Float32Array(a.b9([])),Be=new a.aR(0,0,0,0,0),Ge=ie?rm(De,B,L,_,0,g.scope,ce,U,{tileID:Be,tileSize:re}):cv(De,B,L,E.toPremultipliedRenderColor(R?null:g.lut));return void Ke.draw(_,Z.TRIANGLES,_e,be,Re,Zr.disabled,Ge,g.id,_.viewportBuffer,_.quadTriangleIndexBuffer,_.viewportSegments)}for(const Ke of Xe){const De=_.isTileAffectedByFog(Ke),Be=_.getOrCreateProgram(Me,{overrideFog:De,defines:$e}),Ge=Ke.toUnwrapped(),ot=S?Ke.projMatrix:_.transform.calculateProjMatrix(Ge);_.prepareDrawTile();const Je=d?d.getTile(Ke):je?je[Ke.key]:new a.b0(Ke,re,ne.zoom,_),St=ie?rm(ot,B,L,_,0,g.scope,ce,U,{tileID:Ke,tileSize:re}):cv(ot,B,L,E.toPremultipliedRenderColor(R?null:g.lut));_.uploadCommonUniforms(W,Be,Ge);const{tileBoundsBuffer:pt,tileBoundsIndexBuffer:Ot,tileBoundsSegments:Ut}=_.getTileBoundsBuffers(Je);Be.draw(_,Z.TRIANGLES,_e,be,Re,Zr.disabled,St,g.id,pt,Ot,Ut)}},sky:function(_,d,g){const S=_._atmosphere?a.al(_.transform.zoom):1,E=g.paint.get("sky-opacity")*S;if(E===0)return;const R=_.context,L=g.paint.get("sky-type"),B=new Mr(R.gl.LEQUAL,Mr.ReadOnly,[0,1]),U=_.frameCounter/1e3%1;L==="atmosphere"?_.renderPass==="offscreen"?g.needsSkyboxCapture(_)&&(function(W,Z){const ne=W.context,re=ne.gl;let ie=Z.skyboxFbo;if(!ie){ie=Z.skyboxFbo=ne.createFramebuffer(32,32,1,null),Z.skyboxGeometry=new ml(ne),Z.skyboxTexture=ne.gl.createTexture(),re.bindTexture(re.TEXTURE_CUBE_MAP,Z.skyboxTexture),re.texParameteri(re.TEXTURE_CUBE_MAP,re.TEXTURE_WRAP_S,re.CLAMP_TO_EDGE),re.texParameteri(re.TEXTURE_CUBE_MAP,re.TEXTURE_WRAP_T,re.CLAMP_TO_EDGE),re.texParameteri(re.TEXTURE_CUBE_MAP,re.TEXTURE_MIN_FILTER,re.LINEAR),re.texParameteri(re.TEXTURE_CUBE_MAP,re.TEXTURE_MAG_FILTER,re.LINEAR);for(let _e=0;_e<6;++_e)re.texImage2D(re.TEXTURE_CUBE_MAP_POSITIVE_X+_e,0,re.RGBA,32,32,0,re.RGBA,re.UNSIGNED_BYTE,null)}ne.bindFramebuffer.set(ie.framebuffer),ne.viewport.set([0,0,32,32]);const ce=Z.getCenter(W,!0),le=W.getOrCreateProgram("skyboxCapture"),be=new Float64Array(16);a.b9(be),a.ef(be,be,.5*-Math.PI),Yc(W,Z,le,be,ce,0),a.b9(be),a.ef(be,be,.5*Math.PI),Yc(W,Z,le,be,ce,1),a.b9(be),a.cE(be,be,.5*-Math.PI),Yc(W,Z,le,be,ce,2),a.b9(be),a.cE(be,be,.5*Math.PI),Yc(W,Z,le,be,ce,3),a.b9(be),Yc(W,Z,le,be,ce,4),a.b9(be),a.ef(be,be,Math.PI),Yc(W,Z,le,be,ce,5),ne.viewport.set([0,0,W.width,W.height])}(_,g),g.markSkyboxValid(_)):_.renderPass==="sky"&&function(W,Z,ne,re,ie){const ce=W.context,le=ce.gl,be=W.transform,_e=W.getOrCreateProgram("skybox");ce.activeTexture.set(le.TEXTURE0),le.bindTexture(le.TEXTURE_CUBE_MAP,Z.skyboxTexture);const Re=((Me,je,Xe,$e,Ke)=>({u_matrix:Me,u_sun_direction:je,u_cubemap:0,u_opacity:$e,u_temporal_offset:Ke}))(be.skyboxMatrix,Z.getCenter(W,!1),0,re,ie);W.uploadCommonUniforms(ce,_e),_e.draw(W,le.TRIANGLES,ne,an.disabled,W.colorModeForRenderPass(),Zr.backCW,Re,"skybox",Z.skyboxGeometry.vertexBuffer,Z.skyboxGeometry.indexBuffer,Z.skyboxGeometry.segment)}(_,g,B,E,U):L==="gradient"&&_.renderPass==="sky"&&function(W,Z,ne,re,ie){const ce=W.context,le=ce.gl,be=W.transform,_e=W.getOrCreateProgram("skyboxGradient");Z.skyboxGeometry||(Z.skyboxGeometry=new ml(ce)),ce.activeTexture.set(le.TEXTURE0);let Re=Z.colorRampTexture;Re||(Re=Z.colorRampTexture=new a.T(ce,Z.colorRamp,le.RGBA8)),Re.bind(le.LINEAR,le.CLAMP_TO_EDGE);const Me=((je,Xe,$e,Ke,De)=>({u_matrix:je,u_color_ramp:0,u_center_direction:Xe,u_radius:a.ap($e),u_opacity:Ke,u_temporal_offset:De}))(be.skyboxMatrix,Z.getCenter(W,!1),Z.paint.get("sky-gradient-radius"),re,ie);W.uploadCommonUniforms(ce,_e),_e.draw(W,le.TRIANGLES,ne,an.disabled,W.colorModeForRenderPass(),Zr.backCW,Me,"skyboxGradient",Z.skyboxGeometry.vertexBuffer,Z.skyboxGeometry.indexBuffer,Z.skyboxGeometry.segment)}(_,g,B,E,U)},custom:function(_,d,g,S){const E=_.context,R=g.implementation;if(!_.transform.projection.unsupportedLayers||!_.transform.projection.unsupportedLayers.includes("custom")||_.terrain&&(_.terrain.renderingToTexture||_.renderPass==="offscreen")&&g.isDraped(d)){if(_.renderPass==="offscreen"){const L=R.prerender;if(L){if(_.setCustomLayerDefaults(),E.setColorMode(_.colorModeForRenderPass()),_.transform.projection.name==="globe"){const B=_.transform.pointMerc;L.call(R,E.gl,_.transform.customLayerMatrix(),_.transform.getProjection(),_.transform.globeToMercatorMatrix(),a.al(_.transform.zoom),[B.x,B.y],_.transform.pixelsPerMeterRatio)}else L.call(R,E.gl,_.transform.customLayerMatrix());E.setDirty(),_.setBaseState()}}else if(_.renderPass==="translucent"){if(_.terrain&&_.terrain.renderingToTexture){const B=R.renderToTile;if(B){const U=S[0].canonical,W={x:U.x+S[0].wrap*(R.wrapTileId?0:1<{W&&(W.useNormalOffset=!0,Z||(W.enabled=!0))},re=d.getSource();if(_.renderPass==="light-beam"&&re.type!=="batched-model")return;if(re.type==="vector"||re.type==="geojson")return function(je,Xe,$e,Ke,De){const Be=je.transform,Ge=Be.projection.name==="globe",ot=Be.getFreeCameraOptions().position;if(!je.modelManager)return;const Je=je.modelManager;$e.modelManager=Je;const St=je.shadowRenderer;if(!$e._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const pt=$e._unevaluatedLayout._values["model-id"],Ot=Object.assign({},$e.layout.get("model-id").parameters),Ut=je.style.order.indexOf($e.fqid),ut=$e.paint.get("model-opacity").constantOr(1);for(const st of Ke){const _t=Xe.getTile(st).getBucket($e);if(!_t||_t.projection.name!==Be.projection.name)continue;const jt=_t.getModelUris();if(jt&&!_t.modelsRequested&&(Je.addModelsFromBucket(jt,De),_t.modelsRequested=!0),Ge)Ot.zoom=st.overscaledZ;else{const br=by(st,Be);Ot.zoom=br}const Nt=pt.possiblyEvaluate(Ot);if(sr(je,_t,st),Qt.shadowUniformsInitialized=!1,Qt.useSingleShadowCascade=!!St&&St.getMaxCascadeForTile(st.toUnwrapped())===0,je.renderPass==="shadow"&&St){if(je.currentShadowCascade===1&&_t.isInsideFirstShadowMapFrustum)continue;const br=Be.calculatePosMatrix(st.toUnwrapped(),Be.worldSize);if(Qt.tileMatrix.set(br),Qt.shadowTileMatrix=Float32Array.from(St.calculateShadowPassMatrixFromMatrix(br)),Qt.aabb.min=[0,0,0],Qt.aabb.max[0]=Qt.aabb.max[1]=a.an,Qt.aabb.max[2]=0,xP(_t,Qt,je,$e.scope))continue}const lr=1<0&&je.style.isLayerClipped($e,Xe.getSource())&&_t.updateReplacement(st,je.replacementSource,Ut,$e.scope)&&(_t.uploaded=!1,_t.upload(je.context));let er=0;const zt=new Array,Pr=new Array,Fr=new Array;for(let br in _t.instancesPerModel){const Nr=_t.instancesPerModel[br];Nr.features.length>0&&!Ge&&(br=Nt.evaluate(Nr.features[0].feature,{}));const Jr=Je.getModel(br,De);if(Jr||Je.hasURLBeenRequested(br)||_t.modelUris.includes(br)||(_t.modelUris.push(br),_t.modelsRequested=!1),Jr&&Jr.uploaded)if(Ge){const dn=a.bJ([],[ot.x,ot.y,ot.z],je.transform.worldSize);a.eo(dn,dn);for(let on=0;on0&&jn.elevationUpdate(br.terrain,on,Kr,Jr.source),jn.needsReEvaluation(br,Tn,Jr)&&jn.evaluate(Jr))}})(je,Xe,$e,Ke),function(){const br=new Map;let Nr,Jr,dn;zt?(Nr=Ke.length-1,Jr=-1,dn=-1):(Nr=0,Jr=Ke.length,dn=1);const on=new Float64Array(16),Tn=a.ce(),Kr=new a.P(0,0);for(let jn=Nr;jn!==Jr;jn+=dn){const ln=Ke[jn],ts=Xe.getTile(ln).getBucket($e);if(!ts||!ts.uploaded)continue;let Cs=!1;ot&&(Cs=ot.getMaxCascadeForTile(ln.toUnwrapped())===0);const li=Be.calculatePosMatrix(ln.toUnwrapped(),Be.worldSize),Fs=ts.modelTraits;!lr&&zt&&(a.b7(on,li),a.ah(Tn,St,on),Kr.x=Tn[0],Kr.y=Tn[1]);const ds=[];ts.setFilter($e.filter);for(const _n of ts.getNodesInfo()){if(_n.hiddenByReplacement||!_n.node.meshes)continue;const bn=_n.node;let Bs=0;je.terrain&&bn.elevation&&(Bs=bn.elevation*je.terrain.exaggeration());const mi=(()=>{const io=_n.aabb;return Nt.min=[...io.min],Nt.max=[...io.max],Nt.min[2]+=Bs,Nt.max[2]+=Bs,a.ah(Nt.min,Nt.min,li),a.ah(Nt.max,Nt.max,li),Nt})(),hs=_n.evaluatedScale;if(hs[0]<=1&&hs[1]<=1&&hs[2]<=1&&mi.intersects(Jt)===0)continue;if(!lr&&zt){const io=.16666666666666666;_n.cameraCollisionOpacity=St[0]>mi.min[0]&&St[0]mi.min[1]&&St[1]!zt||_n.opacity===1&&bn.opacity===1?_n.depthbn.depth?-1:1);for(const _n of ds){const bn=_n.nodeInfo,Bs=bn.node;if(je._debugParams.show3DModelFootprints&&Bs.footprint){const Mn=Bs.id||Bs.name||"footprint";br.has(Mn)||br.set(Mn,{node:Bs,mvp:_n.wvpForTile})}let mi=a.aD([],ut,_n.tileModelMatrix);a.aD(mi,Ot,mi);const hs=a.b7([],mi);a.e6(hs,hs),a.cC(hs,hs,at),mi=a.aD(mi,mi,Bs.globalMatrix);const hn=je.renderPass==="light-beam",si=$e.paint.get("model-color-use-theme").constantOr("default")==="none",Is=Fs&a.ez.HasMapboxMeshFeatures,Yi=Is?0:bn.evaluatedRMEA[0][2];for(let Mn=0;Mn=vr||Ac>=vr}}const ys=Ms.material;let Qc;ys.occlusionTexture&&ys.occlusionTexture.offsetScale&&(Qc=ys.occlusionTexture.offsetScale,Sa.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Jc=je.getOrCreateProgram("model",Sa);!lr&&ot&&ot.setupShadowsFromMatrix(_n.tileModelMatrix,Jc,ot.useNormalOffset),je.uploadCommonUniforms(De,Jc,null,kc);const Vs=ys.pbrMetallicRoughness;Vs.metallicFactor=.9,Vs.roughnessFactor=.5;const Ys=Np(new Float32Array(Do),new Float32Array(mi),new Float32Array(hs),new Float32Array(Bs.globalMatrix),je,_n.opacity,Vs.baseColorFactor,ys.emissiveFactor,Vs.metallicFactor,Vs.roughnessFactor,ys,Yi,$e,[0,0,0],Qc);!ha&&(bn.hasTranslucentParts||_n.opacity<1)&&Jc.draw(je,De.gl.TRIANGLES,_t,an.disabled,tn.disabled,Zr.backCCW,Ys,$e.id,Ms.vertexBuffer,Ms.indexBuffer,Ms.segments,$e.paint,je.transform.zoom,void 0,io),Jc.draw(je,De.gl.TRIANGLES,ha?jt:_t,an.disabled,ha||_n.opacity<1||bn.hasTranslucentParts?tn.alphaBlended:tn.unblended,Zr.backCCW,Ys,$e.id,Ms.vertexBuffer,Ms.indexBuffer,Ms.segments,$e.paint,je.transform.zoom,void 0,io)}}}if(je._debugParams.show3DModelFootprints&&br.size>0){const jn=Array.from(br.keys()).sort();for(const ln of jn){const{node:ts,mvp:Cs}=br.get(ln);DE(je,0,ts,Cs)}}}()}(_,d,g,S),void ne();if(re.type!=="model")return;const ie=re.getModels(),ce=[],le=_.transform.getFreeCameraOptions().position,be=a.bJ([],[le.x,le.y,le.z],_.transform.worldSize);a.eo(be,be);const _e=[],Re=[];let Me=0;for(const je of ie){const Xe=d.getFeatureState("",je.id),$e={type:"Unknown",id:je.id,properties:je.featureProperties},Ke=g.paint.get("model-rotation").evaluate($e,Xe),De=g.paint.get("model-scale").evaluate($e,Xe),Be=g.paint.get("model-translation").evaluate($e,Xe),Ge=g.paint.get("model-opacity").evaluate($e,Xe);OE(g,je.id,Xe,je.featureProperties,je.nodeOverrideNames,je.nodeOverrides),Rp(g,je.id,Xe,je.featureProperties,je.materialOverrideNames,je.materialOverrides),je.nodeOverrides.size>0&&je.computeBoundsAndApplyParent(),je.computeModelMatrix(_,Ke,De,Be,B,L,!1);const ot=a.b9([]),Je=a.e2(je.position.lat,_.transform.zoom),St=a.bP([],[1,1,1/Je]);a.bx(ot,ot,be),ce.push({zScaleMatrix:St,negCameraPosMatrix:ot});for(const pt of je.nodes)mw(_,pt,je.matrix,_.transform.expandedFarZProjMatrix,Me,_e,Re,je.materialOverrides,Ge);Me++}if(_e.sort((je,Xe)=>Xe.depth-je.depth),_.renderPass!=="shadow"){if(_._debugParams.show3DModelFootprints){const je=_.transform.projMatrix,Xe=new Map,$e=(De,Be)=>{if(De.footprint){const Ge=De.id||De.name||"footprint";if(!Xe.has(Ge)){const ot=a.aD([],je,Be);Xe.set(Ge,{node:De,mvp:ot})}}};for(const De of Re)$e(De.node,De.modelMatrix);for(const De of _e)$e(De.node,De.modelMatrix);const Ke=Array.from(Xe.keys()).sort();for(const De of Ke){const{node:Be,mvp:Ge}=Xe.get(De);DE(_,0,Be,Ge)}}Wh(_,g,_e,Re,ce),ne()}else{for(const je of Re)_y(je.mesh,je.nodeModelMatrix,_,g);for(const je of _e)_y(je.mesh,je.nodeModelMatrix,_,g);ne()}}},$E={line:function(_,d,g){if(_.hasElevatedBuckets=!1,_.hasNonElevatedBuckets=!1,_._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||_._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(d){const S=d.getVisibleCoordinates();for(const E of S){const R=d.getTile(E).getBucket(_);if(R&&(R.elevationType!=="none"?_.hasElevatedBuckets=!0:_.hasNonElevatedBuckets=!0,_.hasElevatedBuckets&&_.hasNonElevatedBuckets))break}}}else _.hasNonElevatedBuckets=!0},model:function(_,d,g){const S=d.getSource();if(!S.loaded())return;if(S.type==="vector"||S.type==="geojson")return void(g.modelManager&&g.modelManager.upload(g,fw(g,_)));if(S.type==="batched-model"||S.type!=="model")return;const E=S.getModels();for(const R of E)R.upload(g.context)},raster:function(_,d,g){const S=d.getSource();if(!(S instanceof yp&&S.loaded()))return;const E=_.sourceLayer||S.rasterLayerIds&&S.rasterLayerIds[0];if(!E)return;const R=_.paint.get("raster-array-band")||S.getInitialBand(E);if(R==null)return;const L=d.getIds().map(B=>d.getTileByID(B));for(const B of L)B.updateNeeded(_.id,R)&&S.prepareTile(B,E,_.id,R)},"raster-particle":function(_,d,g){const S=d.getSource();if(!(S instanceof yp&&S.loaded()))return;const E=_.sourceLayer||S.rasterLayerIds&&S.rasterLayerIds[0];if(!E)return;const R=_.paint.get("raster-particle-array-band")||S.getInitialBand(E);if(R==null)return;const L=d.getIds().map(B=>d.getTileByID(B));for(const B of L)B.updateNeeded(_.id,R)&&S.prepareTile(B,E,_.id,R)}},zE={fill:hv},UE={fill:function(_,d,g,S){if(!g.layout||g.layout.get("fill-elevation-reference")==="none"||g.paint.get("fill-opacity").constantOr(1)===0)return;const E=_.context.gl,R=new Mr(E.LEQUAL,Mr.ReadOnly,_.depthRangeFor3D),L=new an({func:E.ALWAYS,mask:255},255,255,E.KEEP,E.KEEP,E.REPLACE),B=_.transform.getFreeCameraOptions().position,U=_.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const W of S){const Z=d.getTile(W),ne=Z.getBucket(g);if(!ne)continue;const re=ne.elevatedStructures;if(!re||re.depthSegments.segments[0].primitiveLength===0)continue;const ie=bE(W.toUnwrapped(),B),ce=_.translatePosMatrix(W.projMatrix,Z,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor")),le=ov(ce,ie,0,1,0);U.draw(_,E.TRIANGLES,R,L,tn.disabled,Zr.disabled,le,g.id,re.vertexBuffer,re.indexBuffer,re.depthSegments,g.paint,_.transform.zoom)}}};class NB{constructor(d,g,S,E,R){this.context=new xy(d,g),this.transform=S,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=a.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 U of L)this._debugParams.enabledLayers[U]=!0;for(const U of L);this.occlusionParams=new _P,this.setup(),this.numSublayers=Pu.maxUnderzooming+Pu.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new a.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new W0(this),this._wireframeDebugCache=new vP,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const B=new a.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new a.T(this.context,B,d.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=E,this.maxFrontCutoffRawStart=0,this.worldview=R,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(d,g){const S=!!d&&!!d.terrain&&this.transform.projection.supportsTerrain;if(!(S||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new av(this,d));const E=this._terrain;this.transform.elevation=S?E:null,E.update(d,this.transform,g),this.transform.elevation&&!E.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[S,E]=g.getFovAdjustedRange(this.transform._fov);if(S>E)return void(this.transform.fogCullDistSq=null);const R=S+.78*(E-S);this.transform.fogCullDistSq=R*R}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(d){d&&!this._terrain&&(this._terrain=new av(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*a.o.devicePixelRatio,this.height=g*a.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const S of this.style.order)this.style._mergedLayers[S].resize()}setup(){const d=this.context,g=new a.dB;g.emplaceBack(0,0),g.emplaceBack(a.an,0),g.emplaceBack(0,a.an),g.emplaceBack(a.an,a.an),this.tileExtentBuffer=d.createVertexBuffer(g,a.dx.members),this.tileExtentSegments=a.dy.simpleSegment(0,0,4,2);const S=new a.dB;S.emplaceBack(0,0),S.emplaceBack(a.an,0),S.emplaceBack(0,a.an),S.emplaceBack(a.an,a.an),this.debugBuffer=d.createVertexBuffer(S,a.dx.members),this.debugSegments=a.dy.simpleSegment(0,0,4,5);const E=new a.dB;E.emplaceBack(-1,-1),E.emplaceBack(1,-1),E.emplaceBack(-1,1),E.emplaceBack(1,1),this.viewportBuffer=d.createVertexBuffer(E,a.dx.members),this.viewportSegments=a.dy.simpleSegment(0,0,4,2);const R=new a.eH;R.emplaceBack(0,0,0,0),R.emplaceBack(a.an,0,a.an,0),R.emplaceBack(0,a.an,0,a.an),R.emplaceBack(a.an,a.an,a.an,a.an),this.mercatorBoundsBuffer=d.createVertexBuffer(R,a.eI.members),this.mercatorBoundsSegments=a.dy.simpleSegment(0,0,4,2);const L=new a.dC;L.emplaceBack(0,1,2),L.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=d.createIndexBuffer(L);const B=new a.eJ;for(const W of[0,1,3,2,0])B.emplaceBack(W);this.debugIndexBuffer=d.createIndexBuffer(B),this.emptyTexture=new a.T(d,new a.q({width:1,height:1},Uint8Array.of(0,0,0,0)),d.gl.RGBA8),this.identityMat=a.bb();const U=this.context.gl;this.stencilClearMode=new an({func:U.ALWAYS,mask:0},0,255,U.ZERO,U.ZERO,U.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,Mr.disabled,this.stencilClearMode,tn.disabled,Zr.disabled,sv(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(d,g,S){if(!g||this.currentStencilSource===g.id||!d.isTileClipped()||!S||S.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let B=!1;for(const U of S)if(this._tileClippingMaskIDs[U.key]===void 0){B=!0;break}if(!B)return}this.currentStencilSource=g.id;const E=this.context,R=E.gl;this.nextStencilID+S.length>256&&this.clearStencil(),E.setColorMode(tn.disabled),E.setDepthMode(Mr.disabled);const L=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const B of S){const U=g.getTile(B),W=this._tileClippingMaskIDs[B.key]=this.nextStencilID++,{tileBoundsBuffer:Z,tileBoundsIndexBuffer:ne,tileBoundsSegments:re}=this.getTileBoundsBuffers(U);L.draw(this,R.TRIANGLES,Mr.disabled,new an({func:R.ALWAYS,mask:0},W,255,R.KEEP,R.KEEP,R.REPLACE),tn.disabled,Zr.disabled,sv(B.projMatrix),"$clipping",Z,ne,re)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const d=this.nextStencilID++,g=this.context.gl;return new an({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 an({func:g.EQUAL,mask:255},this._tileClippingMaskIDs[d.key],0,g.KEEP,g.KEEP,g.REPLACE)}stencilConfigForOverlap(d){const g=this.context.gl,S=d.sort((L,B)=>B.overscaledZ-L.overscaledZ),E=S[S.length-1].overscaledZ,R=S[0].overscaledZ-E+1;if(R>1){this.currentStencilSource=void 0,this.nextStencilID+R>256&&this.clearStencil();const L={};for(let B=0;Bthis._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 S=a.o.now();this._dt=S-this._timeStamp,this._timeStamp=S,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=d.map.repaint,this.style=d,this.options=g;const E=this.style._mergedLayers,R=!(!this.terrain||!this.terrain.enabled),L=()=>this.style._getOrder(R).filter(ut=>{const st=E[ut];return!(st.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[st.type]});let B=L(),U=!1,W=!1,Z=null,ne=0,re=!1;for(const ut of B){const st=E[ut];st.visibility!=="none"&&(st.type==="circle"?U=!0:st.type==="building"?(Z=st,++ne):st.type==="symbol"&&(st.hasOcclusionOpacityProperties?W=!0:U=!0))}this.updateEmissiveMode();let ie=B.map(ut=>E[ut]);const ce=this.style._mergedSourceCaches;this.imageManager=d.imageManager,this.modelManager=d.modelManager,this.symbolFadeChange=d.placement.symbolFadeChange(a.o.now()),this.imageManager.beginFrame();for(const ut in ce){const st=ce[ut];st.used&&(st.prepare(this.context),st.getSource().usedInConflation&&++ne)}let le=!1;for(const ut of ie)ut.isHidden(this.transform.zoom)||(ut.type==="clip"&&(le=!0),this.prepareLayer(ut));const be={},_e={},Re={},Me={},je={};for(const ut in ce){const st=ce[ut];be[ut]=st.getVisibleCoordinates(),_e[ut]=be[ut].slice().reverse(),Re[ut]=st.getVisibleCoordinates(!0).reverse(),Me[ut]=st.getShadowCasterCoordinates(),je[ut]=st.sortCoordinatesByDistance(be[ut])}const Xe=ut=>{const st=this.style.getLayerSourceCache(ut);return st&&st.used?st.getSource():null};if(ne||le||this._clippingActiveLastFrame){const ut=[],st=[];let _t=0;for(const jt of ie)this.isSourceForClippingOrConflation(jt,Xe(jt))&&(ut.push(jt),st.push(_t)),_t++;if(ut&&(le||ut.length>1)||this._clippingActiveLastFrame){le=!1;const jt=[];for(let Nt=0;Nt0){const jt=Xe(st);jt&&(this.minCutoffZoom=Math.max(jt.minzoom,this.minCutoffZoom)),st.minzoom&&(this.minCutoffZoom=Math.max(st.minzoom,this.minCutoffZoom))}st.is3D(R)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=ut),this._lastOcclusionLayer=ut)}const $e=this.style&&this.style.fog;$e?(this._fogVisible=$e.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=$e.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Re),this.opaquePassCutoff=0,B=L(),ie=B.map(ut=>E[ut]));const Ke=this._shadowRenderer;if(Ke){Ke.updateShadowParameters(this.transform,this.style.directionalLight);for(const ut in ce)for(const st of be[ut]){let _t={min:0,max:0};this.terrain&&(_t=this.terrain.getMinMaxForTile(st)||_t),Ke.addShadowReceiver(st.toUnwrapped(),_t.min,_t.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new a.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new gP(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 SP(this)),!De&&this._snow&&(this._snow.destroy(),delete this._snow),Be&&!this._rain&&(this._rain=new gv(this)),!Be&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Z){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Hh);const ut=this.style.getLayerSourceCache(Z);this.buildingTileBorderManager.updateBorders(ut,Z)}if(!$r.has(this.context.gl))return;this.renderPass="offscreen";for(const ut of ie){const st=d.getLayerSourceCache(ut);if(!ut.hasOffscreenPass()||ut.isHidden(this.transform.zoom))continue;const _t=st?_e[st.id]:void 0;(ut.type==="custom"||ut.type==="raster"||ut.type==="raster-particle"||ut.isSky()||_t&&_t.length)&&this.renderLayer(this,st,ut,_t)}this.depthRangeFor3D=[0,1-(ie.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Me)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ge=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),ot=(()=>{if(g.showOverdrawInspector)return a.aq.black;const ut=this.style.fog;if(ut&&this.transform.projection.supportsFog){const st=this.style.getLut(ut.scope);if(!Ge){const _t=ut.properties.get("color-use-theme")==="none",jt=ut.properties.get("color").toNonPremultipliedRenderColor(_t?null:st).toArray01();return new a.aq(...jt)}if(Ge){const _t=ut.properties.get("space-color-use-theme")==="none",jt=ut.properties.get("space-color").toNonPremultipliedRenderColor(_t?null:st).toArray01();return new a.aq(...jt)}}return a.aq.transparent})();if(this.context.clear({color:ot,depth:1}),this.clearStencil(),this._showOverdrawInspector=g.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ge&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=B.length-1;this.currentLayer>=0;this.currentLayer--){const ut=ie[this.currentLayer],st=d.getLayerSourceCache(ut);if(ut.isSky())continue;const _t=st?(ut.is3D(R)?je:_e)[st.id]:void 0;this._renderTileClippingMasks(ut,st,_t),this.renderLayer(this,st,ut,_t)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ge&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||a.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 _t=this.currentLayer;this.depthOcclusion=!0;for(const jt of this.layersWithOcclusionOpacity){this.currentLayer=jt;const Nt=ie[this.currentLayer],lr=d.getLayerSourceCache(Nt),Jt=lr?_e[lr.id]:void 0;this.terrain||this._renderTileClippingMasks(Nt,lr,lr?be[lr.id]:void 0),this.renderLayer(this,lr,Nt,Jt)}this.depthOcclusion=!1,this.currentLayer=_t,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 ut=null;ie.forEach(st=>{const _t=d.getLayerSourceCache(st);_t&&!st.isHidden(this.transform.zoom)&&_t.getVisibleCoordinates().length&&(!ut||ut.getSource().maxzoom<_t.getSource().maxzoom)&&(ut=_t)}),ut&&this.options.showTileBoundaries&&fP(this,ut,ut.getVisibleCoordinates(),a.aq.red,!1,this.options.showParseStatus)}this.terrain&&this._debugParams.showTerrainProxyTiles&&fP(this,this.terrain.proxySourceCache,this.terrain.proxyCoords,new a.aq(1,.8,.1,1),!0,this.options.showParseStatus),this.options.showPadding&&function(ut){const st=ut.transform.padding;mP(ut,ut.transform.height-(st.top||0),3,CE),mP(ut,st.bottom||0,3,TB),PE(ut,st.left||0,3,jB),PE(ut,ut.transform.width-(st.right||0),3,EB);const _t=ut.transform.centerPoint;(function(jt,Nt,lr,Jt){hw(jt,Nt-1,lr-10,2,20,Jt),hw(jt,Nt-10,lr-1,20,2,Jt)})(ut,_t.x,ut.transform.height-_t.y,IE)}(this),this.context.setDefault(),this.frameCounter=(this.frameCounter+1)%Number.MAX_SAFE_INTEGER,this.tileLoaded&&this.options.speedIndexTiming&&(this.loadTimeStamps.push(performance.now()),this.saveCanvasCopy()),re||(this.conflationActive=!1)}prepareLayer(d){this.gpuTimingStart(d);const{unsupportedLayers:g}=this.transform.projection,S=!g||!g.includes(d.type);if($E[d.type]&&(S||this.terrain&&d.type==="custom")){const E=this.style.getLayerSourceCache(d);$E[d.type](d,E,this)}this.gpuTimingEnd()}renderLayer(d,g,S,E){S.isHidden(this.transform.zoom)||(S.type==="background"||S.type==="sky"||S.type==="custom"||S.type==="model"||S.type==="raster"||S.type==="raster-particle"||E&&E.length)&&(this.id=S.id,this.gpuTimingStart(S),d.transform.projection.unsupportedLayers&&d.transform.projection.unsupportedLayers.includes(S.type)&&(!d.terrain||S.type!=="custom")||S.type==="clip"||TP[S.type](d,g,S,E,this.style.placement.variableOffsets,this.options.isInitialLoad),this.gpuTimingEnd())}gpuTimingStart(d){if(!this.options.gpuTiming)return;const g=this.context.extTimerQuery,S=this.context.gl;let E=this.gpuTimers[d.id];E||(E=this.gpuTimers[d.id]={calls:0,cpuTime:0,query:S.createQuery()}),E.calls++,S.beginQuery(g.TIME_ELAPSED_EXT,E.query)}gpuTimingDeferredRenderStart(){if(this.options.gpuTimingDeferredRender){const d=this.context.extTimerQuery,g=this.context.gl,S=g.createQuery();this.deferredRenderGpuTimeQueries.push(S),g.beginQuery(d.TIME_ELAPSED_EXT,S)}}gpuTimingDeferredRenderEnd(){this.options.gpuTimingDeferredRender&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}gpuTimingEnd(){this.options.gpuTiming&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}collectGpuTimers(){const d=this.gpuTimers;return this.gpuTimers={},d}collectDeferredRenderGpuQueries(){const d=this.deferredRenderGpuTimeQueries;return this.deferredRenderGpuTimeQueries=[],d}queryGpuTimers(d){const g={};for(const S in d){const E=d[S],R=this.context.extTimerQuery,L=R.getQueryParameter(E.query,this.context.gl.QUERY_RESULT)/1e6;R.deleteQueryEXT(E.query),g[S]=L}return g}queryGpuTimeDeferredRender(d){if(!this.options.gpuTimingDeferredRender)return 0;const g=this.context.gl;let S=0;for(const E of d)S+=g.getQueryParameter(E,g.QUERY_RESULT)/1e6,g.deleteQuery(E);return S}translatePosMatrix(d,g,S,E,R){if(!S[0]&&!S[1])return d;const L=R?E==="map"?this.transform.angle:0:E==="viewport"?-this.transform.angle:0;if(L){const W=Math.sin(L),Z=Math.cos(L);S=[S[0]*Z-S[1]*W,S[0]*W+S[1]*Z]}const B=[R?S[0]:a.aA(g,S[0],this.transform.zoom),R?S[1]:a.aA(g,S[1],this.transform.zoom),0],U=new Float32Array(16);return a.bx(U,d,B),U}saveTileTexture(d){if(d.context!==this.context)return;const g=d.size[0],S=this._tileTextures[g];S?S.push(d):this._tileTextures[g]=[d]}getTileTexture(d){const g=this._tileTextures[d];return g&&g.length>0?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,S){const E=S===void 0?this.terrain&&this.terrain.renderingToTexture:S,R=[];return this.style&&this.style.enable3dLights()&&(d==="globeRaster"||d==="terrainRaster"?(R.push("LIGHTING_3D_MODE"),R.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):E||R.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(R.push("TERRAIN"),this.linearFloatFilteringSupported()&&R.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&R.push("GLOBE"),!this._fogVisible||E||g!==void 0&&!g||R.push("FOG"),E&&R.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&R.push("OVERDRAW_INSPECTOR"),R}getOrCreateProgram(d,g){this.cache=this.cache||{};const S=g&&g.defines||[],E=g&&g.config,R=this.currentGlobalDefines(d,g&&g.overrideFog,g&&g.overrideRtt).concat(S),L=Ap.cacheKey(LI[d],d,R,E);return this.cache[L]||(this.cache[L]=new Ap(this.context,d,LI[d],E,iw[d],R)),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 a.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 S=this.style.directionalLight,E=this.style.ambientLight;if(S&&E){const R=((L,B,U)=>{const W=L.properties.get("direction"),Z=L.properties.get("color-use-theme")==="none",ne=L.properties.get("color").toNonPremultipliedRenderColor(Z?null:U.getLut(L.scope)).toArray01(),re=L.properties.get("intensity"),ie=B.properties.get("color-use-theme")==="none",ce=B.properties.get("color").toNonPremultipliedRenderColor(ie?null:U.getLut(B.scope)).toArray01(),le=B.properties.get("intensity"),be=[W.x,W.y,W.z],_e=a.dD(ce,le),Re=a.dD(ne,re);return{u_lighting_ambient_color:_e,u_lighting_directional_dir:be,u_lighting_directional_color:Re,u_ground_radiance:gE(be,Re,_e)}})(S,E,this.style);g.setLightsUniformValues(d,R)}}}uploadCommonUniforms(d,g,S,E,R){if(this.uploadCommonLightUniforms(d,g),this.terrain&&this.terrain.renderingToTexture)return;const L=this.style.fog;if(L){const B=L.getOpacity(this.transform.pitch),U=((W,Z,ne,re,ie,ce,le,be,_e,Re,Me,je)=>{const Xe=W.transform,$e=Z.properties.get("color-use-theme")==="none",Ke=Z.properties.get("color").toNonPremultipliedRenderColor($e?null:W.style.getLut(Z.scope)).toArray01();Ke[3]=re;const De=W.frameCounter/1e3%1,[Be,Ge]=Z.properties.get("vertical-range");return{u_fog_matrix:ne?Xe.calculateFogTileMatrix(ne):je||W.identityMat,u_fog_range:Z.getFovAdjustedRange(Xe._fov),u_fog_color:Ke,u_fog_horizon_blend:Z.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Be,Ge),Ge],u_fog_temporal_offset:De,u_frustum_tl:ie,u_frustum_tr:ce,u_frustum_br:le,u_frustum_bl:be,u_globe_pos:_e,u_globe_radius:Re,u_viewport:Me,u_globe_transition:a.al(Xe.zoom),u_is_globe:+(Xe.projection.name==="globe")}})(this,L,S,B,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*a.o.devicePixelRatio,this.transform.height*a.o.devicePixelRatio],E);g.setFogUniformValues(d,U)}R&&g.setCutoffUniformValues(d,R.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={},S=this.transform.coveringTiles({tileSize:512});for(const E of S)g[E.key]=d[E.key]||new a.b0(E,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]>=vr||g[1]>=vr}setupDepthForOcclusion(d,g,S){const E=this.context,R=E.gl,L=!!S;var B;S||(S={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}),E.activeTexture.set(R.TEXTURE3),d&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(R.NEAREST,R.CLAMP_TO_EDGE),S.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],S.u_depth_range_unpack=[2/((B=this.depthRangeFor3D)[1]-B[0]),-1-2*B[0]/(B[1]-B[0])],S.u_occluder_half_size=.5*this.occlusionParams.occluderSize,S.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(R.NEAREST,R.CLAMP_TO_EDGE),E.activeTexture.set(R.TEXTURE0),L||g.setTerrainUniformValues(E,S)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const d=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=d?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function VE(_,d){let g=!1,S=null;const E=()=>{S=null,g&&(_(),S=setTimeout(E,d),g=!1)};return()=>(g=!0,S||E(),S)}class CB{constructor(d){this._hashName=d&&encodeURIComponent(d),a.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=pl(d);if(this._hashName){const S=this._hashName;let E=!1;const R=location.hash.slice(1).split("&").map(L=>{const B=L.split("=")[0];return B===S?(E=!0,`${B}=${g}`):L}).filter(L=>L);return E||R.push(`${S}=${g}`),`#${R.join("&")}`}return`#${g}`}_getCurrentHash(){const d=location.hash.replace("#","");if(this._hashName){let g;return d.split("&").map(S=>S.split("=")).forEach(S=>{S[0]===this._hashName&&(g=S)}),(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(S=>isNaN(Number(S)))){const S=d.dragRotate.isEnabled()&&d.touchZoomRotate.isEnabled()?+(g[3]||0):d.getBearing();return d.jumpTo({center:[+g[2],+g[1]],zoom:+g[0],bearing:S,pitch:+(g[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function pl(_,d){const g=_.getCenter(),S=Math.round(100*_.getZoom())/100,E=Math.ceil((S*Math.LN2+Math.log(512/360/.5))/Math.LN10),R=Math.pow(10,E),L=Math.round(g.lng*R)/R,B=Math.round(g.lat*R)/R,U=_.getBearing(),W=_.getPitch();let Z=d?`/${L}/${B}/${S}`:`${S}/${B}/${L}`;return(U||W)&&(Z+="/"+Math.round(10*U)/10),W&&(Z+=`/${Math.round(W)}`),Z}const vw={linearity:.3,easing:a.eN(0,0,.3,1)},yv=Object.assign({deceleration:2500,maxSpeed:1400},vw),IB=Object.assign({deceleration:20,maxSpeed:1400},vw),Xs=Object.assign({deceleration:1e3,maxSpeed:360},vw),On=Object.assign({deceleration:1e3,maxSpeed:90},vw);class jP{constructor(d){this._map=d,this.clear()}clear(){this._inertiaBuffer=[]}record(d){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:a.o.now(),settings:d})}_drainInertiaBuffer(){const d=this._inertiaBuffer,g=a.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 a.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:R}of this._inertiaBuffer)g.zoom+=R.zoomDelta||0,g.bearing+=R.bearingDelta||0,g.pitch+=R.pitchDelta||0,R.panDelta&&g.pan._add(R.panDelta),R.around&&(g.around=R.around),R.pinchAround&&(g.pinchAround=R.pinchAround);const S=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,E={};if(g.pan.mag()){const R=rh(g.pan.mag(),S,Object.assign({},yv,d||{}));E.offset=g.pan.mult(R.amount/g.pan.mag()),E.center=this._map.transform.center,Ec(E,R)}if(g.zoom){const R=rh(g.zoom,S,IB);E.zoom=this._map.transform.zoom+R.amount,Ec(E,R)}if(g.bearing){const R=rh(g.bearing,S,Xs);E.bearing=this._map.transform.bearing+a.aC(R.amount,-179,179),Ec(E,R)}if(g.pitch){const R=rh(g.pitch,S,On);E.pitch=this._map.transform.pitch+R.amount,Ec(E,R)}if(E.zoom||E.bearing){const R=g.pinchAround===void 0?g.around:g.pinchAround;E.around=R?this._map.unproject(R):this._map.getCenter()}return this.clear(),E.noMoveStart=!0,E}}function Ec(_,d){(!_.duration||_.durationg.unproject(U)),B=R.reduce((U,W,Z,ne)=>U.add(W.div(ne.length)),new a.P(0,0));super(d,{points:R,point:B,lngLats:L,lngLat:g.unproject(B),originalEvent:S}),this._defaultPrevented=!1}}class qE extends a.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(d,g){super("wheel",{originalEvent:g}),this._defaultPrevented=!1}}class GE{constructor(d,g){this._map=d,this._clickTolerance=g.clickTolerance}reset(){this._mousedownPos=void 0}wheel(d){return this._firePreventable(new qE(this._map,d))}mousedown(d,g){return this._mousedownPos=g,this._firePreventable(new Mo(d.type,this._map,d))}mouseup(d){this._map.fire(new Mo(d.type,this._map,d))}preclick(d){const g=new MouseEvent("preclick",d);this._map.fire(new Mo(g.type,this._map,g))}click(d,g){this._mousedownPos&&this._mousedownPos.dist(g)>=this._clickTolerance||(this.preclick(d),this._map.fire(new Mo(d.type,this._map,d)))}dblclick(d){return this._firePreventable(new Mo(d.type,this._map,d))}mouseover(d){this._map.fire(new Mo(d.type,this._map,d))}mouseout(d){this._map.fire(new Mo(d.type,this._map,d))}touchstart(d){return this._firePreventable(new Zc(d.type,this._map,d))}touchmove(d){this._map.fire(new Zc(d.type,this._map,d))}touchend(d){this._map.fire(new Zc(d.type,this._map,d))}touchcancel(d){this._map.fire(new Zc(d.type,this._map,d))}_firePreventable(d){if(this._map.fire(d),d.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class HE{constructor(d){this._map=d}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(d){this._map.fire(new Mo(d.type,this._map,d))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Mo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(d){this._delayContextMenu?this._contextMenuEvent=d:this._map.fire(new Mo(d.type,this._map,d)),this._map.listens("contextmenu")&&d.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class WE{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&&(z(),this._startPos=this._lastPos=g,this._active=!0)}mousemoveWindow(d,g){if(!this._active)return;const S=g,E=this._startPos,R=this._lastPos;if(!E||!R||R.equals(S)||!this._box&&S.dist(E){this._box&&(this._box.style.transform=`translate(${L}px,${U}px)`,this._box.style.width=B-L+"px",this._box.style.height=W-U+"px")})}mouseupWindow(d,g){if(!this._active)return;const S=this._startPos,E=g;if(S&&d.button===0){if(this.reset(),K(),S.x!==E.x||S.y!==E.y)return this._map.fire(new a.C("boxzoomend",{originalEvent:d})),{cameraAnimation:R=>R.fitScreenCoordinates(S,E,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),q(),delete this._startPos,delete this._lastPos}_fireEvent(d,g){return this._map.fire(new a.C(d,{originalEvent:g}))}}function xv(_,d){const g={};for(let S=0;S<_.length;S++)g[_[S].identifier]=d[S];return g}class Ou{constructor(d){this.reset(),this.numTouches=d.numTouches}reset(){this.centroid=void 0,this.startTime=0,this.touches={},this.aborted=!1}touchstart(d,g,S){(this.centroid||S.length>this.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=d.timeStamp),S.length===this.numTouches&&(this.centroid=function(E){const R=new a.P(0,0);for(const L of E)R._add(L);return R.div(E.length)}(g),this.touches=xv(S,g)))}touchmove(d,g,S){if(this.aborted||!this.centroid)return;const E=xv(S,g);for(const R in this.touches){const L=E[R];(!L||L.dist(this.touches[R])>30)&&(this.aborted=!0)}}touchend(d,g,S){if((!this.centroid||d.timeStamp-this.startTime>500)&&(this.aborted=!0),S.length===0){const E=!this.aborted&&this.centroid;if(this.reset(),E)return E}}}class nh{constructor(d){this.singleTap=new Ou(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,S){this.singleTap.touchstart(d,g,S)}touchmove(d,g,S){this.singleTap.touchmove(d,g,S)}touchend(d,g,S){const E=this.singleTap.touchend(d,g,S);if(E){const R=d.timeStamp-this.lastTime<500,L=!this.lastTap||this.lastTap.dist(E)<30;if(R&&L||this.reset(),this.count++,this.lastTime=d.timeStamp,this.lastTap=E,this.count===this.numTaps)return this.reset(),E}}}class Sy{constructor(){this._zoomIn=new nh({numTouches:1,numTaps:2}),this._zoomOut=new nh({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(d,g,S){this._zoomIn.touchstart(d,g,S),this._zoomOut.touchstart(d,g,S)}touchmove(d,g,S){this._zoomIn.touchmove(d,g,S),this._zoomOut.touchmove(d,g,S)}touchend(d,g,S){const E=this._zoomIn.touchend(d,g,S),R=this._zoomOut.touchend(d,g,S);return E?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()+1,around:L.unproject(E)},{originalEvent:d})}):R?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()-1,around:L.unproject(R)},{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 _w=0,KE=2,YE={[_w]:1,[KE]:2},Yh={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class vv{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 S=ee(d);this._correctButton(d,S)&&(this._lastPoint=g,this._eventButton=S)}mousemoveWindow(d,g){const S=this._lastPoint;if(S){if(d.preventDefault(),this._eventButton!=null&&function(E,R){const L=YE[R];return E.buttons===void 0||(E.buttons&L)!==L}(d,this._eventButton))this.reset();else if(this._moved||!(g.dist(S)0&&(this._active=!0);const E=xv(S,g),R=new a.P(0,0),L=new a.P(0,0);let B=0;for(const W in E){const Z=E[W],ne=this._touches[W];ne&&(R._add(Z),L._add(Z.sub(ne)),B++,E[W]=Z)}if(this._touches=E,B{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class bv{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(d){}_move(d,g,S){return{}}touchstart(d,g,S){this._firstTwoTouches||S.length<2||(this._firstTwoTouches=[S[0].identifier,S[1].identifier],this._start([g[0],g[1]]))}touchmove(d,g,S){const E=this._firstTwoTouches;if(!E)return;d.preventDefault();const[R,L]=E,B=Pi(S,g,R),U=Pi(S,g,L);if(!B||!U)return;const W=this._aroundCenter?null:B.add(U).div(2);return this._move([B,U],W,d)}touchend(d,g,S){if(!this._firstTwoTouches)return;const[E,R]=this._firstTwoTouches,L=Pi(S,g,E),B=Pi(S,g,R);L&&B||(this._active&&K(),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 Pi(_,d,g){for(let S=0;S<_.length;S++)if(_[S].identifier===g)return d[S]}function ww(_,d){return Math.log2(_/d)}class XE extends bv{reset(){super.reset(),this._distance=0,this._startDistance=0}_start(d){this._startDistance=this._distance=d[0].dist(d[1])}_move(d,g){const S=this._distance;if(this._distance=d[0].dist(d[1]),this._active||!(Math.abs(ww(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:ww(this._distance,S),pinchAround:g}}}function Sw(_,d){return 180*_.angleWith(d)/Math.PI}class Mp extends bv{reset(){super.reset(),this._minDiameter=0,this._startVector=void 0,this._vector=void 0}_start(d){this._startVector=this._vector=d[0].sub(d[1]),this._minDiameter=d[0].dist(d[1])}_move(d,g){const S=this._vector;if(this._vector=d[0].sub(d[1]),S&&(this._active||!this._isBelowThreshold(this._vector)))return this._active=!0,{bearingDelta:Sw(this._vector,S),pinchAround:g}}_isBelowThreshold(d){this._minDiameter=Math.min(this._minDiameter,d.mag());const g=25/(Math.PI*this._minDiameter)*360,S=this._startVector;if(!S)return!1;const E=Sw(d,S);return Math.abs(E)Math.abs(_.x)}class QE extends bv{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,wv(d[0].sub(d[1]))&&(this._valid=!1)}_move(d,g,S){const E=this._lastPoints;if(!E)return;const R=d[0].sub(E[0]),L=d[1].sub(E[1]);return this._map._cooperativeGestures&&!a.eO()&&S.touches.length<3||(this._valid=this.gestureBeginsVertically(R,L,S.timeStamp),!this._valid)?void 0:(this._lastPoints=d,this._active=!0,{pitchDelta:(R.y+L.y)/2*-.5})}gestureBeginsVertically(d,g,S){if(this._valid!==void 0)return this._valid;const E=d.mag()>=2,R=g.mag()>=2;if(!E&&!R)return;if(!E||!R)return this._firstMove==null&&(this._firstMove=S),S-this._firstMove<100&&void 0;const L=d.y>0==g.y>0;return wv(d)&&wv(g)&&L}}const JE={panStep:100,bearingStep:15,pitchStep:10};class Dp{constructor(){const d=JE;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,S=0,E=0,R=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?S=-1:(d.preventDefault(),R=-1);break;case 39:d.shiftKey?S=1:(d.preventDefault(),R=1);break;case 38:d.shiftKey?E=1:(d.preventDefault(),L=-1);break;case 40:d.shiftKey?E=-1:(d.preventDefault(),L=1);break;default:return}return this._rotationDisabled&&(S=0,E=0),{cameraAnimation:B=>{const U=B.getZoom();B.easeTo({duration:300,easeId:"keyboardHandler",easing:e2,zoom:g?Math.round(U)+g*(d.shiftKey?2:1):U,bearing:B.getBearing()+S*this._bearingStep,pitch:B.getPitch()+E*this._pitchStep,offset:[-R*this._panStep,-L*this._panStep],center:B.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 e2(_){return _*(2-_)}const Op=4.000244140625,t2=1/450;class Tw{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._handler=g,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=t2,a.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()||a.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 S=a.o.now(),E=S-(this._lastWheelEventTime||0);this._lastWheelEventTime=S,g!==0&&g%Op===0?this._type="wheel":g!==0&&Math.abs(g)<4?this._type="trackpad":E>400?(this._type=null,this._lastValue=g,this._timeout=window.setTimeout(this._onTimeout,40,d)):this._type||(this._type=Math.abs(E*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=J(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 W=this._type==="wheel"&&Math.abs(this._delta)>Op?this._wheelZoomRate:this._defaultZoomRate;let Z=2/(1+Math.exp(-Math.abs(this._delta*W)));this._delta<0&&Z!==0&&(Z=1/Z);const ne=g(),re=Math.pow(2,ne),ie=typeof this._targetZoom=="number"?d.zoomScale(this._targetZoom):re;this._targetZoom=Math.min(d.maxZoom,Math.max(d.minZoom,d.scaleZoom(ie*Z))),this._type==="wheel"&&(this._startZoom=ne,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const S=typeof this._targetZoom=="number"?this._targetZoom:g(),E=this._startZoom,R=this._easing;let L,B=!1;if(this._type==="wheel"&&E&&R){const W=Math.min((a.o.now()-this._lastWheelEventTime)/200,1),Z=R(W);L=a.am(E,S,Z),W<1?this._frameId||(this._frameId=!0):B=!0}else L=S,B=!0;this._active=!0,B&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let U=L-g();return U*this._lastDelta<0&&(U=0),{noInertia:!0,needsRenderFrame:!B,zoomDelta:U,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(d){let g=a.eP;if(this._prevEase){const S=this._prevEase,E=(a.o.now()-S.start)/S.duration,R=S.easing(E+.01)-S.easing(E),L=.27/Math.sqrt(R*R+1e-4)*.01,B=Math.sqrt(.0729-L*L);g=a.eN(L,B,.25,1)}return this._prevEase={start:a.o.now(),duration:d,easing:g},g}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=C("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(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 jw{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 Ew{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(d,g){return d.preventDefault(),{cameraAnimation:S=>{S.easeTo({duration:300,zoom:S.getZoom()+(d.shiftKey?-1:1),around:S.unproject(g)},{originalEvent:d})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class EP{constructor(){this._tap=new nh({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,S){this._swipePoint||(this._tapTime&&d.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?S.length>0&&(this._swipePoint=g[0],this._swipeTouch=S[0].identifier):this._tap.touchstart(d,g,S))}touchmove(d,g,S){if(this._tapTime){if(this._swipePoint){if(S[0].identifier!==this._swipeTouch)return;const E=g[0],R=E.y-this._swipePoint.y;return this._swipePoint=E,d.preventDefault(),this._active=!0,{zoomDelta:R/128}}}else this._tap.touchmove(d,g,S)}touchend(d,g,S){this._tapTime?this._swipePoint&&S.length===0&&this.reset():this._tap.touchend(d,g,S)&&(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 r2{constructor(d,g,S){this._el=d,this._mousePan=g,this._touchPan=S}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 kP{constructor(d,g,S){this._pitchWithRotate=d.pitchWithRotate,this._mouseRotate=g,this._mousePitch=S}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 AP{constructor(d,g,S,E){this._el=d,this._touchZoom=g,this._touchRotate=S,this._tapDragZoom=E,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 Sv=_=>_.zoom||_.drag||_.pitch||_.rotate;class NP extends a.C{}class CP{constructor(){this.constants=[1,1,.01],this.radius=0}setup(d,g){const S=a.ax([],g,d);this.radius=a.ai(S[2]<0?a.eR([],S,this.constants):[S[0],S[1],0])}projectRay(d){a.eR(d,d,this.constants),a.ay(d,d),a.eS(d,d,this.constants);const g=a.bJ([],d,this.radius);if(g[2]>0){const S=a.bJ([],[0,0,1],a.bi(g,[0,0,1])),E=a.bJ([],a.ay([],[g[0],g[1],0]),this.radius),R=a.cT([],g,a.bJ([],a.ax([],a.cT([],E,S),g),2));g[0]=R[0],g[1]=R[1]}return g}}function Tv(_){return _.panDelta&&_.panDelta.mag()||_.zoomDelta||_.bearingDelta||_.pitchDelta}class IP{constructor(d,g){this._map=d,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new jP(d),this._bearingSnap=g.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new CP,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(g),a.aZ(["handleEvent","handleWindowEvent"],this);const S=this._el;this._listeners=[[S,"touchstart",{passive:!0}],[S,"touchmove",{passive:!1}],[S,"touchend",void 0],[S,"touchcancel",void 0],[S,"mousedown",void 0],[S,"mousemove",void 0],[S,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[S,"mouseover",void 0],[S,"mouseout",void 0],[S,"dblclick",void 0],[S,"click",void 0],[S,"keydown",{capture:!1}],[S,"keyup",void 0],[S,"wheel",{passive:!1}],[S,"contextmenu",void 0],[window,"blur",void 0]];for(const[E,R,L]of this._listeners){const B=E===document?this.handleWindowEvent:this.handleEvent;E.addEventListener(R,B,L)}}destroy(){for(const[d,g,S]of this._listeners){const E=d===document?this.handleWindowEvent:this.handleEvent;d.removeEventListener(g,E,S)}}_addDefaultHandlers(d){const g=this._map,S=g.getCanvasContainer();this._add("mapEvent",new GE(g,d));const E=g.boxZoom=new WE(g,d);this._add("boxZoom",E);const R=new Sy,L=new Ew;g.doubleClickZoom=new jw(L,R),this._add("tapZoom",R),this._add("clickZoom",L);const B=new EP;this._add("tapDragZoom",B);const U=g.touchPitch=new QE(g);this._add("touchPitch",U);const W=new bw(d),Z=new _v(d);g.dragRotate=new kP(d,W,Z),this._add("mouseRotate",W,["mousePitch"]),this._add("mousePitch",Z,["mouseRotate"]);const ne=new Fu(d),re=new ZE(g,d);g.dragPan=new r2(S,ne,re),this._add("mousePan",ne),this._add("touchPan",re,["touchZoom","touchRotate"]);const ie=new Mp,ce=new XE;g.touchZoomRotate=new AP(S,ce,ie,B),this._add("touchRotate",ie,["touchPan","touchZoom"]),this._add("touchZoom",ce,["touchPan","touchRotate"]),this._add("blockableMapEvent",new HE(g));const le=g.scrollZoom=new Tw(g,this);this._add("scrollZoom",le,["mousePan"]);const be=g.keyboard=new Dp;this._add("keyboard",be);for(const _e of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])d.interactive&&d[_e]&&g[_e].enable(d[_e])}_add(d,g,S){this._handlers.push({handlerName:d,handler:g,allowed:S}),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!!Sv(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(d,g,S){for(const E in d)if(E!==S&&(!g||g.indexOf(E)<0))return!0;return!1}handleWindowEvent(d){this.handleEvent(d,`${d.type}Window`)}_getMapTouches(d){const g=[];for(const S of d)this._el.contains(S.target)&&g.push(S);return g}handleEvent(d,g){this._updatingCamera=!0;const S=d.type==="renderFrame",E=S?void 0:d,R={needsRenderFrame:!1},L={},B={},U=d.touches?this._getMapTouches(d.touches):void 0,W=U?Q(this._el,U):S?void 0:J(this._el,d);for(const{handlerName:re,handler:ie,allowed:ce}of this._handlers){if(!ie.isEnabled())continue;let le;this._blockedByActive(B,ce,re)?ie.reset():ie[g||d.type]&&(le=ie[g||d.type](d,W,U),this.mergeHandlerResult(R,L,le,re,E),le&&le.needsRenderFrame&&this._triggerRenderFrame()),(le||ie.isActive())&&(B[re]=ie)}const Z={};for(const re in this._previousActiveHandlers)B[re]||(Z[re]=E);this._previousActiveHandlers=B,(Object.keys(Z).length||Tv(R))&&(this._changes.push([R,L,Z]),this._triggerRenderFrame()),(Object.keys(B).length||Tv(R))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:ne}=R;ne&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],ne(this._map))}mergeHandlerResult(d,g,S,E,R){if(!S)return;Object.assign(d,S);const L={handlerName:E,originalEvent:S.originalEvent||R};S.zoomDelta!==void 0&&(g.zoom=L),S.panDelta!==void 0&&(g.drag=L),S.pitchDelta!==void 0&&(g.pitch=L),S.bearingDelta!==void 0&&(g.rotate=L)}_applyChanges(){const d={},g={},S={};for(const[E,R,L]of this._changes)E.panDelta&&(d.panDelta=(d.panDelta||new a.P(0,0))._add(E.panDelta)),E.zoomDelta&&(d.zoomDelta=(d.zoomDelta||0)+E.zoomDelta),E.bearingDelta&&(d.bearingDelta=(d.bearingDelta||0)+E.bearingDelta),E.pitchDelta&&(d.pitchDelta=(d.pitchDelta||0)+E.pitchDelta),E.around!==void 0&&(d.around=E.around),E.aroundCoord!==void 0&&(d.aroundCoord=E.aroundCoord),E.pinchAround!==void 0&&(d.pinchAround=E.pinchAround),E.noInertia&&(d.noInertia=E.noInertia),Object.assign(g,R),Object.assign(S,L);this._updateMapTransform(d,g,S),this._changes=[]}_updateMapTransform(d,g,S){const E=this._map,R=E.transform,L=Re=>[Re.x,Re.y,Re.z];if((()=>{const Re=this._eventsInProgress.drag;return Re&&!this._handlersById[Re.handlerName].isActive()})()&&!Tv(d)){const Re=R.zoom;R.cameraElevationReference="sea",this._originalZoom!=null&&R._orthographicProjectionAtLowPitch&&R.projection.name!=="globe"&&R.pitch===0?(R.cameraElevationReference="ground",R.zoom=this._originalZoom):(R.recenterOnTerrain(),R.cameraElevationReference="ground"),Re!==R.zoom&&this._map._update(!0)}if(R._isCameraConstrained&&E._stop(!0),!Tv(d))return void this._fireEvents(g,S,!0);let{panDelta:B,zoomDelta:U,bearingDelta:W,pitchDelta:Z,around:ne,aroundCoord:re,pinchAround:ie}=d;R._isCameraConstrained&&(U>0&&(U=0),R._isCameraConstrained=!1),ie!==void 0&&(ne=ie),(U||(Re=>g[Re]&&!this._eventsInProgress[Re])("drag"))&&ne&&(this._dragOrigin=L(R.pointCoordinate3D(ne)),this._originalZoom=R.zoom,this._trackingEllipsoid.setup(R._camera.position,this._dragOrigin)),R.cameraElevationReference="sea",E._stop(!0),ne=ne||E.transform.centerPoint,W&&(R.bearing+=W),Z&&(R.pitch+=Z),R._updateCameraState();const ce=[0,0,0];if(B)if(R.projection.name==="mercator"){const Re=this._trackingEllipsoid.projectRay(R.screenPointToMercatorRay(ne).dir),Me=this._trackingEllipsoid.projectRay(R.screenPointToMercatorRay(ne.sub(B)).dir);ce[0]=Me[0]-Re[0],ce[1]=Me[1]-Re[1]}else{const Re=R.pointCoordinate(ne);if(R.projection.name==="globe"){B=B.rotate(-R.angle);const Me=R._pixelsPerMercatorPixel/R.worldSize;ce[0]=-B.x*a.eQ(a.bV(Re.y))*Me,ce[1]=-B.y*a.eQ(R.center.lat)*Me}else{const Me=R.pointCoordinate(ne.sub(B));Re&&Me&&(ce[0]=Me.x-Re.x,ce[1]=Me.y-Re.y)}}const le=R.zoom,be=[0,0,0];if(U){const Re=L(re||R.pointCoordinate3D(ne)),Me={dir:a.ay([],a.ax([],Re,R._camera.position))};if(Me.dir[2]<0){const je=R.zoomDeltaToMovement(Re,U);a.bJ(be,Me.dir,je)}}const _e=a.cT(ce,ce,be);R._translateCameraConstrained(_e),U&&Math.abs(R.zoom-le)>1e-4&&R.recenterOnTerrain(),R.cameraElevationReference="ground",this._map._update(),d.noInertia||this._inertia.record(d),this._fireEvents(g,S,!0)}_fireEvents(d,g,S){const E=Sv(this._eventsInProgress),R=Sv(d),L={};for(const Z in d){const{originalEvent:ne}=d[Z];this._eventsInProgress[Z]||(L[`${Z}start`]=ne),this._eventsInProgress[Z]=d[Z]}!E&&R&&this._fireEvent("movestart",R.originalEvent);for(const Z in L)this._fireEvent(Z,L[Z]);R&&this._fireEvent("move",R.originalEvent);for(const Z in d){const{originalEvent:ne}=d[Z];this._fireEvent(Z,ne)}const B={};let U;for(const Z in this._eventsInProgress){const{handlerName:ne,originalEvent:re}=this._eventsInProgress[Z];this._handlersById[ne].isActive()||(delete this._eventsInProgress[Z],U=g[ne]||re,B[`${Z}end`]=U)}for(const Z in B)this._fireEvent(Z,B[Z]);const W=Sv(this._eventsInProgress);if(S&&(E||R)&&!W){this._updatingCamera=!0;const Z=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),ne=re=>re!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new NP("renderFrame",{timeStamp:d})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const n2="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class PP extends a.E{constructor(d,g){super(),this._moving=!1,this._zooming=!1,this.transform=d,this._bearingSnap=g.bearingSnap,this._respectPrefersReducedMotion=g.respectPrefersReducedMotion!==!1,a.aZ(["_renderFrameCallback"],this)}getCenter(){return new a.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(d,g){return this.jumpTo({center:d},g)}panBy(d,g,S){return d=a.P.convert(d).mult(-1),this.panTo(this.transform.center,Object.assign({offset:d},g),S)}panTo(d,g,S){return this.easeTo(Object.assign({center:d},g),S)}getZoom(){return this.transform.zoom}setZoom(d,g){return this.jumpTo({zoom:d},g),this}zoomTo(d,g,S){return this.easeTo(Object.assign({zoom:d},g),S)}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,S){return this.easeTo(Object.assign({bearing:d},g),S)}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?S/(2*Math.tan(.5*d.fovX)*d.aspect):E/(2*Math.tan(.5*d.fovY)*d.aspect)}_cameraForBoundsOnGlobe(d,g,S,E,R,L){const B=d.clone(),U=this._extendCameraOptions(L);B.bearing=E,B.pitch=R;const W=a.aU.convert(g),Z=a.aU.convert(S),ne=.5*(W.lat+Z.lat),re=.5*(W.lng+Z.lng),ie=a.eT(ne,re),ce=a.ay([],ie),le=a.ay([],a.bh([],ce,[0,1,0])),be=a.bh([],le,ce),_e=[le[0],le[1],le[2],0,be[0],be[1],be[2],0,ce[0],ce[1],ce[2],0,0,0,0,1],Re=[ie,a.eT(W.lat,W.lng),a.eT(Z.lat,W.lng),a.eT(Z.lat,Z.lng),a.eT(W.lat,Z.lng),a.eT(ne,W.lng),a.eT(ne,Z.lng),a.eT(W.lat,re),a.eT(Z.lat,re)];let Me=a.cU.fromPoints(Re.map(jt=>[a.bi(le,jt),a.bi(be,jt),a.bi(ce,jt)]));const je=a.ah([],Me.center,_e);a.eU(je)===0&&a.eV(je,0,0,1),a.ay(je,je),a.bJ(je,je,a.aF),B.center=a.eW(je);const Xe=B.getWorldToCameraMatrix(),$e=a.b7(new Float64Array(16),Xe);Me=a.cU.applyTransform(Me,a.aD([],Xe,_e));const Ke=this._extendAABB(Me,B,U,E);if(!Ke)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Me=Ke,a.ah(je,je,Xe);const De=.5*(Me.max[2]-Me.min[2]),Be=this._minimumAABBFrustumDistance(B,Me),Ge=a.bJ([],[0,0,1],De),ot=a.cT(Ge,je,Ge),Je=Be+(B.pitch===0?0:a.bf(je,ot)),St=B.globeCenterInViewSpace,pt=a.ax([],je,[St[0],St[1],St[2]]);a.ay(pt,pt),a.bJ(pt,pt,Je);const Ot=a.cT([],je,pt);a.ah(Ot,Ot,$e);const Ut=a.eD/a.aF,ut=a.ai(Ot),st=a.bU(Math.max(ut*Ut-a.eD,Number.EPSILON),0),_t=Math.min(B.zoomFromMercatorZAdjusted(st),U.maxZoom);return _t>.5*(a.cJ+a.cv)?(B.setProjection({name:"mercator"}),B.zoom=_t,this._cameraForBounds(B,g,S,E,R,L)):{center:B.center,zoom:_t,bearing:E,pitch:R}}_extendAABB(d,g,S,E){const R=.5*((S.padding.left||0)+(S.padding.right||0)),L=.5*((S.padding.top||0)+(S.padding.bottom||0)),B=L,U=R,W=R,Z=L,ne=g.width-(U+W),re=g.height-(B+Z),ie=a.ax([],d.max,d.min),ce=Math.min(ne/ie[0],re/ie[1]),le=Math.min(g.scaleZoom(g.scale*ce),S.maxZoom);if(isNaN(le))return null;const be=g.scale/g.zoomScale(le),_e=new a.cU([d.min[0]-U*be,d.min[1]-Z*be,d.min[2]],[d.max[0]+W*be,d.max[1]+B*be,d.max[2]]),Re=(typeof S.offset.x=="number"&&typeof S.offset.y=="number"?new a.P(S.offset.x,S.offset.y):a.P.convert(S.offset)).rotate(-a.ap(E));return _e.center[0]-=Re.x*be,_e.center[1]+=Re.y*be,_e}queryTerrainElevation(d,g){const S=this.transform.elevation;return S?(g=Object.assign({},{exaggerated:!0},g),S.getAtPoint(a.ag.fromLngLat(d),null,g.exaggerated)):null}_cameraForBounds(d,g,S,E,R,L){if(d.projection.name==="globe")return this._cameraForBoundsOnGlobe(d,g,S,E,R,L);const B=d.clone(),U=this._extendCameraOptions(L);B.bearing=E,B.pitch=R;const W=a.aU.convert(g),Z=a.aU.convert(S),ne=new a.aU(W.lng,Z.lat),re=new a.aU(Z.lng,W.lat),ie=B.project(W),ce=B.project(Z),le=this.queryTerrainElevation(W),be=this.queryTerrainElevation(Z),_e=this.queryTerrainElevation(ne),Re=this.queryTerrainElevation(re),Me=[[ie.x,ie.y,Math.min(le||0,be||0,_e||0,Re||0)],[ce.x,ce.y,Math.max(le||0,be||0,_e||0,Re||0)]];let je=a.cU.fromPoints(Me);const Xe=B.getWorldToCameraMatrix(),$e=a.b7(new Float64Array(16),Xe);je=a.cU.applyTransform(je,Xe);const Ke=this._extendAABB(je,B,U,E);if(!Ke)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");je=Ke;const De=.5*a.ax([],je.max,je.min)[2],Be=this._minimumAABBFrustumDistance(B,je),Ge=[0,0,1,0];a.aE(Ge,Ge,Xe),a.eX(Ge,Ge);const ot=a.bJ([],Ge,Be+De),Je=a.cT([],je.center,ot);a.ah(je.center,je.center,$e),a.ah(Je,Je,$e);const St=B.unproject(new a.P(je.center[0],je.center[1])),pt=a.eY(B.projection,St),Ot=Math.pow(2,pt),Ut=Math.min(B._zoomFromMercatorZ(Je[2]*B.pixelsPerMeter*Ot/B.worldSize),U.maxZoom);return B.mercatorFromTransition&&Ut<.5*(a.cJ+a.cv)?(B.setProjection({name:"globe"}),B.zoom=Ut,this._cameraForBounds(B,g,S,E,R,L)):{center:St,zoom:Ut,bearing:E,pitch:R}}fitBounds(d,g,S){const E=this.cameraForBounds(d,g);return this._fitInternal(E,g,S)}fitScreenCoordinates(d,g,S,E,R){const L=a.P.convert(d),B=a.P.convert(g),U=new a.P(Math.min(L.x,B.x),Math.min(L.y,B.y)),W=new a.P(Math.max(L.x,B.x),Math.max(L.y,B.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(L,B))return this;const Z=this.transform.pointLocation3D(U),ne=this.transform.pointLocation3D(W),re=this.transform.pointLocation3D(new a.P(U.x,W.y)),ie=this.transform.pointLocation3D(new a.P(W.x,U.y)),ce=[Math.min(Z.lng,ne.lng,re.lng,ie.lng),Math.min(Z.lat,ne.lat,re.lat,ie.lat)],le=[Math.max(Z.lng,ne.lng,re.lng,ie.lng),Math.max(Z.lat,ne.lat,re.lat,ie.lat)],be=E&&E.pitch?E.pitch:this.getPitch(),_e=this._cameraForBounds(this.transform,ce,le,S,be,E);return this._fitInternal(_e,E,R)}_fitInternal(d,g,S){return d?(g=Object.assign(d,g)).linear?this.easeTo(g,S):this.flyTo(g,S):this}jumpTo(d,g){this.stop();const S=d.preloadOnly?this.transform.clone():this.transform;let E=!1,R=!1,L=!1;"zoom"in d&&S.zoom!==+d.zoom&&(E=!0,S.zoom=+d.zoom),d.center!==void 0&&(S.center=a.aU.convert(d.center)),"bearing"in d&&S.bearing!==+d.bearing&&(R=!0,S.bearing=+d.bearing),"pitch"in d&&S.pitch!==+d.pitch&&(L=!0,S.pitch=+d.pitch);const B=typeof d.padding=="number"?this._extendPadding(d.padding):d.padding;if(d.padding!=null&&!S.isPaddingEqual(B))if(d.retainPadding===!1){const U=S.clone();U.padding=B,S.setLocationAtPoint(S.center,U.centerPoint)}else S.padding=B;return d.preloadOnly?(this._preloadTiles(S),this):(this.fire(new a.C("movestart",g)).fire(new a.C("move",g)),E&&this.fire(new a.C("zoomstart",g)).fire(new a.C("zoom",g)).fire(new a.C("zoomend",g)),R&&this.fire(new a.C("rotatestart",g)).fire(new a.C("rotate",g)).fire(new a.C("rotateend",g)),L&&this.fire(new a.C("pitchstart",g)).fire(new a.C("pitch",g)).fire(new a.C("pitchend",g)),this.fire(new a.C("moveend",g)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||a.w(n2),this.transform.getFreeCameraOptions()}setFreeCameraOptions(d,g){const S=this.transform;if(!S.projection.supportsFreeCamera)return a.w(n2),this;this.stop();const E=S.zoom,R=S.pitch,L=S.bearing;S.setFreeCameraOptions(d);const B=E!==S.zoom,U=R!==S.pitch,W=L!==S.bearing;return this.fire(new a.C("movestart",g)).fire(new a.C("move",g)),B&&this.fire(new a.C("zoomstart",g)).fire(new a.C("zoom",g)).fire(new a.C("zoomend",g)),W&&this.fire(new a.C("rotatestart",g)).fire(new a.C("rotate",g)).fire(new a.C("rotateend",g)),U&&this.fire(new a.C("pitchstart",g)).fire(new a.C("pitch",g)).fire(new a.C("pitchend",g)),this.fire(new a.C("moveend",g)),this}easeTo(d,g){this._stop(!1,d.easeId),((d=Object.assign({offset:[0,0],duration:500,easing:a.eP},d)).animate===!1||this._prefersReducedMotion(d))&&(d.duration=0);const S=this.transform,E=this.getZoom(),R=this.getBearing(),L=this.getPitch(),B=this.getPadding(),U="zoom"in d?+d.zoom:E,W="bearing"in d?this._normalizeBearing(d.bearing,R):R,Z="pitch"in d?+d.pitch:L,ne=this._extendPadding(d.padding),re=a.P.convert(d.offset);let ie,ce,le;if(S.projection.name==="globe"){const Ge=a.ag.fromLngLat(S.center),ot=re.rotate(-S.angle);Ge.x+=ot.x/S.worldSize,Ge.y+=ot.y/S.worldSize;const Je=Ge.toLngLat(),St=a.aU.convert(d.center||Je);this._normalizeCenter(St),ie=S.centerPoint.add(ot),ce=new a.P(Ge.x,Ge.y).mult(S.worldSize),le=new a.P(a.aH(St.lng),a.aL(St.lat)).mult(S.worldSize).sub(ce)}else{ie=S.centerPoint.add(re);const Ge=S.pointLocation(ie),ot=a.aU.convert(d.center||Ge);this._normalizeCenter(ot),ce=S.project(Ge),le=S.project(ot).sub(ce)}const be=S.zoomScale(U-E);let _e,Re;d.around&&(_e=a.aU.convert(d.around),Re=S.locationPoint(_e));const Me=this._zooming||U!==E,je=this._rotating||R!==W,Xe=this._pitching||Z!==L,$e=!S.isPaddingEqual(ne),Ke=d.retainPadding===!1?S.clone():S,De=Ge=>ot=>{if(Me&&(Ge.zoom=a.am(E,U,ot)),je&&(Ge.bearing=a.am(R,W,ot)),Xe&&(Ge.pitch=a.am(L,Z,ot)),$e&&(Ke.interpolatePadding(B,ne,ot),ie=Ke.centerPoint.add(re)),_e)Ge.setLocationAtPoint(_e,Re);else{const Je=Ge.zoomScale(Ge.zoom-E),St=U>E?Math.min(2,be):Math.max(.5,be),pt=Math.pow(St,1-ot),Ot=Ge.unproject(ce.add(le.mult(ot*pt)).mult(Je));Ge.setLocationAtPoint(Ge.renderWorldCopies?Ot.wrap():Ot,ie)}return d.preloadOnly||this._fireMoveEvents(g),Ge};if(d.preloadOnly){const Ge=this._emulate(De,d.duration,S);return this._preloadTiles(Ge),this}const Be={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Me,this._rotating=je,this._pitching=Xe,this._padding=$e,this._easeId=d.easeId,this._prepareEase(g,d.noMoveStart,Be),this._ease(De(S),Ge=>{S.cameraElevationReference==="sea"&&S.recenterOnTerrain(),this._afterEase(g,Ge)},d),this}_prepareEase(d,g,S={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),g||S.moving||this.fire(new a.C("movestart",d)),this._zooming&&!S.zooming&&this.fire(new a.C("zoomstart",d)),this._rotating&&!S.rotating&&this.fire(new a.C("rotatestart",d)),this._pitching&&!S.pitching&&this.fire(new a.C("pitchstart",d))}_fireMoveEvents(d){this.fire(new a.C("move",d)),this._zooming&&this.fire(new a.C("zoom",d)),this._rotating&&this.fire(new a.C("rotate",d)),this._pitching&&this.fire(new a.C("pitch",d))}_afterEase(d,g){if(this._easeId&&g&&this._easeId===g)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const S=this._zooming,E=this._rotating,R=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,S&&this.fire(new a.C("zoomend",d)),E&&this.fire(new a.C("rotateend",d)),R&&this.fire(new a.C("pitchend",d)),this.fire(new a.C("moveend",d))}flyTo(d,g){if(this._prefersReducedMotion(d)){const jt=a.aJ(d,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(jt,g)}this.stop(),d=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:a.eP},d);const S=this.transform,E=this.getZoom(),R=this.getBearing(),L=this.getPitch(),B=this.getPadding(),U="zoom"in d?a.aC(+d.zoom,S.minZoom,S.maxZoom):E,W="bearing"in d?this._normalizeBearing(d.bearing,R):R,Z="pitch"in d?+d.pitch:L,ne=this._extendPadding(d.padding),re=S.zoomScale(U-E),ie=a.P.convert(d.offset);let ce=S.centerPoint.add(ie);const le=S.pointLocation(ce),be=a.aU.convert(d.center||le);this._normalizeCenter(be);const _e=S.project(le),Re=S.project(be).sub(_e);let Me=d.curve;const je=Math.max(S.width,S.height),Xe=je/re,$e=Re.mag();if("minZoom"in d){const jt=a.aC(Math.min(d.minZoom,E,U),S.minZoom,S.maxZoom),Nt=je/S.zoomScale(jt-E);Me=Math.sqrt(Nt/$e*2)}const Ke=Me*Me;function De(jt){const Nt=(Xe*Xe-je*je+(jt?-1:1)*Ke*Ke*$e*$e)/(2*(jt?Xe:je)*Ke*$e);return Math.log(Math.sqrt(Nt*Nt+1)-Nt)}function Be(jt){return(Math.exp(jt)-Math.exp(-jt))/2}function Ge(jt){return(Math.exp(jt)+Math.exp(-jt))/2}const ot=De(0);let Je=function(jt){return Ge(ot)/Ge(ot+Me*jt)},St=function(jt){return je*((Ge(ot)*(Be(Nt=ot+Me*jt)/Ge(Nt))-Be(ot))/Ke)/$e;var Nt},pt=(De(1)-ot)/Me;if(Math.abs($e)<1e-6||!isFinite(pt)){if(Math.abs(je-Xe)<1e-6)return this.easeTo(d,g);const jt=Xed.maxDuration&&(d.duration=0);const Ot=R!==W,Ut=Z!==L,ut=!S.isPaddingEqual(ne),st=d.retainPadding===!1?S.clone():S,_t=jt=>Nt=>{const lr=Nt*pt,Jt=1/Je(lr);jt.zoom=Nt===1?U:E+jt.scaleZoom(Jt),Ot&&(jt.bearing=a.am(R,W,Nt)),Ut&&(jt.pitch=a.am(L,Z,Nt)),ut&&(st.interpolatePadding(B,ne,Nt),ce=st.centerPoint.add(ie));const er=Nt===1?be:jt.unproject(_e.add(Re.mult(St(lr))).mult(Jt));return jt.setLocationAtPoint(jt.renderWorldCopies?er.wrap():er,ce),jt._updateCameraOnTerrain(),d.preloadOnly||this._fireMoveEvents(g),jt};if(d.preloadOnly){const jt=this._emulate(_t,d.duration,S);return this._preloadTiles(jt),this}return this._zooming=!0,this._rotating=Ot,this._pitching=Ut,this._padding=ut,this._prepareEase(g,!1),this._ease(_t(S),()=>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 S=this._onEaseEnd;this._onEaseEnd=void 0,S.call(this,g)}if(!d){const S=this.handlers;S&&S.stop(!1)}return this}_ease(d,g,S){S.animate===!1||S.duration===0?(d(1),g()):(this._easeStart=a.o.now(),this._easeOptions=S,this._onEaseFrame=d,this._onEaseEnd=g,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const d=Math.min((a.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=a.bs(d,-180,180);const S=Math.abs(d-g);return Math.abs(d-360-g)180?-360:S<-180?360:0}_prefersReducedMotion(d){return this._respectPrefersReducedMotion&&a.o.prefersReducedMotion&&!(d&&d.essential)}_emulate(d,g,S){const E=Math.ceil(15*g/1e3),R=[],L=d(S.clone());for(let B=0;B<=E;B++){const U=L(B/E);R.push(U.clone())}return R}_preloadTiles(d,g){}}class s2{constructor(d={}){this.options=d,a.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(d){const g=this.options&&this.options.compact,S=d._getUIString("AttributionControl.ToggleAttribution");this._map=d,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=C("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",S);const E=C("span","mapboxgl-ctrl-icon",this._compactButton);return E.setAttribute("aria-hidden","true"),E.setAttribute("title",S),this._innerContainer=C("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||a.g.ACCESS_TOKEN}];if(d){const S=g.reduce((E,R,L)=>(R.value&&(E+=`${R.key}=${R.value}${LE.length-R.length),d=d.filter((E,R)=>{for(let L=R+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 S=d.map(E=>function(R){const L=new DOMParser().parseFromString(R,"text/html");return Array.from(L.body.querySelectorAll("*")).reverse().forEach(B=>{const U=B.textContent||"";if(B.tagName!=="A")return void B.replaceWith(...B.childNodes);const W=B.getAttribute("href");if(!W||!/^(https?:|mailto:)/i.test(W))return void B.replaceWith(L.createTextNode(U));const Z=L.createElement("a");Z.href=W,Z.textContent=U,Z.rel="noopener nofollow";const ne=B.getAttribute("class");ne&&(Z.className=ne),B.replaceWith(Z)}),L.body.innerHTML}(E)).join(" | ");S!==this._attribHTML&&(this._attribHTML=S,d.length?(this._innerContainer.innerHTML=S,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 i2{constructor(){a.aZ(["_updateLogo","_updateCompact"],this)}onAdd(d){this._map=d,this._container=C("div","mapboxgl-ctrl");const g=C("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 S=d[g].getSource();if(S.hasOwnProperty("mapbox_logo")&&!S.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 RP{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,S=g?this._queue.concat(g):this._queue;for(const E of S)if(E.id===d)return void(E.cancelled=!0)}run(d=0){const g=this._currentlyRunning=this._queue;this._queue=[];for(const S of g)if(!S.cancelled&&(S.callback(d),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class PB{constructor(d){this.jumpTo(d)}getValue(d){if(d<=this._startTime)return this._start;if(d>=this._endTime)return this._end;const g=a.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,S){this._start=this.getValue(g),this._end=d,this._startTime=g,this._endTime=g+S}}const RB={"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 Os extends a.C{constructor(d,g,S,E){const{point:R,lngLat:L,originalEvent:B,target:U}=d;super(d.type,{point:R,lngLat:L,originalEvent:B,target:U}),this.preventDefault=()=>{d.preventDefault()},this.id=g,this.interaction=S,this.feature=E}}class kw{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 S=g.filter;let E=g.type;S&&this.filters.set(d,a.dg(S)),E==="mouseover"&&(E="mouseenter"),E==="mouseout"&&(E="mouseleave");const R=this.interactionsByType.get(E)||new Map;E==="mouseenter"||E==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(d,g)):R.size===0&&this.map.on(E,this.handleType),R.size===0&&this.interactionsByType.set(E,R),R.set(d,g),this.typeById.set(d,E)}get(d){const g=this.typeById.get(d);if(!g)return;const S=this.interactionsByType.get(g);return S?S.get(d):void 0}remove(d){const g=this.typeById.get(d);if(!g)return;this.typeById.delete(d),this.filters.delete(d);const S=this.interactionsByType.get(g);S&&(S.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))):S.size===0&&this.map.off(g,this.handleType))}queryTargets(d,g){const S=[];for(const[E,R]of g)R.target&&S.push({targetId:E,target:R.target,filter:this.filters.get(E)});return this.map.style.queryRenderedTargets(d,S,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 S=new Map;for(const[E,{feature:R}]of this.prevHoveredFeatures)this.hoveredFeatures.has(E)||S.set(R.id,R);S.size&&(d.type="mouseleave",this.handleType(d,Array.from(S.values())))}handleOut(d){const g=Array.from(this.hoveredFeatures.values()).map(({feature:S})=>S);g.length&&(d.type="mouseleave",this.handleType(d,g)),this.hoveredFeatures.clear()}handleType(d,g){const S=d.type==="mouseenter";if(S&&!this.interactionsByType.has(d.type))return void a.w("mouseenter interaction required for mouseleave to work.");const E=Array.from(this.interactionsByType.get(d.type)).reverse(),R=!!g;g=g||this.queryTargets(d.point,E);let L=!1;const B=new Set;for(const U of g){for(const[W,Z]of E){if(!Z.target)continue;const ne=U.variants?U.variants[W]:null;if(ne){for(const re of ne){if(Xd(re,U,B,W))continue;const ie=new a.di(U,re),ce=Bj(re,U,W);R&&ie.id!==void 0&&(ie.state=this.map.getFeatureState(ie));const le=S?this.prevHoveredFeatures.get(ce):null,be=new Os(d,W,Z,ie),_e=le?le.stop:Z.handler(be);if(S&&this.hoveredFeatures.set(ce,{feature:U,stop:_e}),_e!==!1){L=!0;break}}if(L)break}}if(L)break}if(!L)for(const[U,W]of E){const{handler:Z,target:ne}=W;if(!ne&&Z(new Os(d,U,W,null))!==!1)break}}}function LB(_,d){if(Array.isArray(_)&&Array.isArray(d)){const g=new Set(_),S=new Set(d);return g.size===S.size&&_.every(E=>S.has(E))}return a.b6(_,d)}const MB={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},DB={showCompass:!0,showZoom:!0,visualizePitch:!1};class jv{constructor(d,g,S=!1){this._clickTolerance=10,this.element=g,this.mouseRotate=new bw({clickTolerance:d.dragRotate._mouseRotate._clickTolerance}),this.map=d,S&&(this.mousePitch=new _v({clickTolerance:d.dragRotate._mousePitch._clickTolerance})),a.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),z()}move(d,g){const S=this.map,E=this.mouseRotate.mousemoveWindow(d,g),R=E&&E.bearingDelta;if(R&&S.setBearing(S.getBearing()+R),this.mousePitch){const L=this.mousePitch.mousemoveWindow(d,g),B=L&&L.pitchDelta;B&&S.setPitch(S.getPitch()+B)}}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(){q(),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()}),J(this.element,d)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(d){this.move(d,J(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=Q(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=Q(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(S).distSqr(d)180;){const S=g.locationPoint3D(_);if(S.x>=0&&S.y>=0&&S.x<=g.width&&S.y<=g.height)break;_.lng>g.center.lng?_.lng-=360:_.lng+=360}return _}const Ev={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%)"},Xc={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Bu extends a.E{constructor(d,g){super(),(d instanceof HTMLElement||g)&&(d=Object.assign({element:d},g)),a.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:S="center",color:E="#3FB1CE",scale:R=1,draggable:L=!1,clickTolerance:B=0,rotation:U=Xc.rotation,rotationAlignment:W=Xc.rotationAlignment,pitchAlignment:Z=Xc.pitchAlignment,occludedOpacity:ne=Xc.occludedOpacity,altitude:re=Xc.altitude}=d||{};this._anchor=S,this._color=E,this._scale=R,this._draggable=L,this._clickTolerance=B,this._rotation=U,this._rotationAlignment=W,this._pitchAlignment=Z,this._occludedOpacity=ne,this._altitude=re,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),d&&d.element?(this._element=d.element,this._offset=a.P.convert(d&&d.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=a.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",le=>{le.preventDefault()}),this._element.addEventListener("mousedown",le=>{le.preventDefault()});const ie=this._element.classList;for(const le in Ev)ie.remove(`mapboxgl-marker-anchor-${le}`);ie.add(`mapboxgl-marker-anchor-${this._anchor}`);const ce=d&&d.className?d.className.trim().split(/\s+/):[];ie.add(...ce),this._popup=null}_createDefaultMarker(){const d=C("div"),g=I("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},d);if(this._altitude===0){const S=I("radialGradient",{id:"shadowGradient"},I("defs",{},g));I("stop",{offset:"10%","stop-opacity":.4},S),I("stop",{offset:"100%","stop-opacity":.05},S),I("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},g)}return I("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),I("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),I("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=a.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||Xc.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 E=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":[E,-1*(38.1-13.5+E)],"bottom-right":[-E,-1*(38.1-13.5+E)],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,S=d.charCode||d.keyCode;g!=="Space"&&g!=="Enter"&&S!==32&&S!==13||this.togglePopup()}_onMapClick(d){const g=d.originalEvent.target,S=this._element;this._popup&&(g===S||S.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 S=d.unproject(g,this._altitude),E=d.getFreeCameraOptions();if(!E.position)return!1;const R=E.position.toLngLat();return R.distanceTo(S)<.9*R.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 S=d.unproject(g,this._altitude);let E;d._showingGlobe()&&a.e$(d.transform,this._lngLat)?E=0:(E=1-d._queryFogOpacity(S),d.transform._terrainEnabled()&&d.getTerrain()&&this._behindTerrain()&&(E*=this._occludedOpacity)),this._element.style.opacity=`${E}`,this._element.style.pointerEvents=E>0?"auto":"none",this._popup&&this._popup._setOpacity(E),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) ${Ev[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${g.x}px,${g.y}px) `}_calculateXYTransform(){const d=this._pos,g=this._map,S=this.getPitchAlignment();if(!g||!d||S!=="map")return"";if(!g._showingGlobe()){const U=g.getPitch();return U?`rotateX(${U}deg)`:""}const E=a.cH(a.f0(g.transform,this._lngLat)),R=d.sub(a.f1(g.transform)),L=Math.abs(R.x)+Math.abs(R.y);if(L===0)return"";const B=E/L;return`rotateX(${-R.y*B}deg) rotateY(${R.x*B}deg)`}_calculateZTransform(){const d=this._pos,g=this._map;if(!g||!d)return"";let S=0;const E=this.getRotationAlignment();if(E==="map")if(g._showingGlobe()){const R=g.project(new a.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),L=g.project(new a.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(R);S=a.cH(Math.atan2(L.y,L.x))-90}else S=-g.getBearing();else if(E==="horizon"){const R=a.aj(4,6,g.getZoom()),L=a.f1(g.transform);L.y+=R*g.transform.height;const B=d.sub(L),U=a.cH(Math.atan2(B.y,B.x));S=(U>90?U-270:U+90)*(1-R)}return S+=this._rotation,S?`rotateZ(${S}deg)`:""}_update(d){cancelAnimationFrame(this._updateFrameId);const g=this._map;g&&(g.transform.renderWorldCopies&&(this._lngLat=a2(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=a.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 S=this._pointerdownPos,E=this._positionDelta;if(S&&E){if(!this._isDragging){const R=this._clickTolerance||g._clickTolerance;if(d.point.dist(S)_.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(_.minPitch!=null&&_.maxPitch!=null&&_.minPitch>_.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(_.minPitch!=null&&_.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(_.maxPitch!=null&&_.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");_.antialias&&a.eZ(window)&&(_.antialias=!1,a.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new H0(_.minZoom,_.maxZoom,_.minPitch,_.maxPitch,_.renderWorldCopies,null,null),_),this._repaint=!!_.repaint,this._interactive=_.interactive,this._minTileCacheSize=_.minTileCacheSize,this._maxTileCacheSize=_.maxTileCacheSize,this._failIfMajorPerformanceCaveat=_.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=_.preserveDrawingBuffer,this._antialias=_.antialias,this._trackResize=_.trackResize,this._bearingSnap=_.bearingSnap,this._refreshExpiredTiles=_.refreshExpiredTiles,this._fadeDuration=_.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=_.crossSourceCollisions,this._collectResourceTiming=_.collectResourceTiming,this._language=this._parseLanguage(_.language),this._worldview=_.worldview,this._renderTaskQueue=new RP,this._domRenderTaskQueue=new RP,this._controls=[],this._markers=[],this._popups=[],this._mapId=a.r(),this._locale=Object.assign({},RB,_.locale),this._clickTolerance=_.clickTolerance,this._cooperativeGestures=_.cooperativeGestures,this._performanceMetricsCollection=_.performanceMetricsCollection,this._tessellationStep=_.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=_.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new PB(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=_.scaleFactor,this._requestManager=new we(_.transformRequest,_.accessToken,_.testMode);const g=ke(_.accessToken||a.g.ACCESS_TOKEN);if(g&&"atlas"in g&&typeof g.atlas=="number"&&(this._tokenExpiration=g.atlas),this._silenceAuthErrors=!!_.testMode,this._contextCreateOptions=_.contextCreateOptions?Object.assign({},_.contextCreateOptions):{},typeof _.container=="string"){const S=document.getElementById(_.container);if(!S)throw new Error(`Container '${_.container.toString()}' not found.`);this._container=S}else{if(!(_.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=_.container}if(this._container.childNodes.length>0&&a.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),_.maxBounds&&this.setMaxBounds(_.maxBounds),this._spriteFormat="auto",a.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 IP(this,_),this._localFontFamily=_.localFontFamily,this._localIdeographFontFamily=_.localIdeographFontFamily,this._useServerFontComposition=_.useServerFontComposition,(_.style||!_.testMode)&&this.setStyle(_.style||a.g.DEFAULT_STYLE,{config:_.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),_.projection&&this.setProjection(_.projection),_.hash&&(this._hash=new CB(typeof _.hash=="string"&&_.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){d.center==null&&d.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:_.center,zoom:_.zoom,bearing:_.bearing,pitch:_.pitch});const S=_.bounds;S&&(this.resize(),this.fitBounds(S,Object.assign({},_.fitBoundsOptions,{duration:0})))}this.resize(),_.attributionControl&&this.addControl(new s2({customAttribution:_.customAttribution})),this._logoControl=new i2,this.addControl(this._logoControl,_.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",S=>{this._update(S.dataType==="style"),this.fire(new a.C(`${S.dataType}data`,S))}),this.on("dataloading",S=>{this.fire(new a.C(`${S.dataType}dataloading`,S))}),this._interactions=new kw(this)}_getMapId(){return this._mapId}addControl(_,d){if(d===void 0&&(d=_.getDefaultPosition?_.getDefaultPosition():"top-right"),!_||!_.onAdd)return this.fire(new a.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const g=_.onAdd(this);this._controls.push(_);const S=this._controlPositions[d];return d.indexOf("bottom")!==-1?S.insertBefore(g,S.firstChild):S.appendChild(g),this}removeControl(_){if(!_||!_.onRemove)return this.fire(new a.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const d=this._controls.indexOf(_);return d>-1&&this._controls.splice(d,1),_.onRemove(this),this}hasControl(_){return this._controls.indexOf(_)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(_){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const d=!this._moving;return d&&this.fire(new a.C("movestart",_)).fire(new a.C("move",_)),this.fire(new a.C("resize",_)),d&&this.fire(new a.C("moveend",_)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(_){return this.transform.setMaxBounds(a.aK.convert(_)),this._update()}setMinZoom(_){if((_=_??-2)>=-2&&_<=this.transform.maxZoom)return this.transform.minZoom=_,this._update(),this.getZoom()<_?this.setZoom(_):this.fire(new a.C("zoomstart")).fire(new a.C("zoom")).fire(new a.C("zoomend")),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(_){if((_=_??22)>=this.transform.minZoom)return this.transform.maxZoom=_,this._update(),this.getZoom()>_?this.setZoom(_):this.fire(new a.C("zoomstart")).fire(new a.C("zoom")).fire(new a.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(_){if((_=_??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(_>=0&&_<=this.transform.maxPitch)return this.transform.minPitch=_,this._update(),this.getPitch()<_?this.setPitch(_):this.fire(new a.C("pitchstart")).fire(new a.C("pitch")).fire(new a.C("pitchend")),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(_){if((_=_??85)>85)throw new Error("maxPitch must be less than or equal to 85");if(_>=this.transform.minPitch)return this.transform.maxPitch=_,this._update(),this.getPitch()>_?this.setPitch(_):this.fire(new a.C("pitchstart")).fire(new a.C("pitch")).fire(new a.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(_){return this._scaleFactor=_,this.painter.scaleFactor=_,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(d=>d.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(_){return this.transform.renderWorldCopies=_,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(_){return _==="auto"?navigator.language:Array.isArray(_)?_.length===0?void 0:_.map(d=>d==="auto"?navigator.language:d):_}setLanguage(_){const d=this._parseLanguage(_);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(_){return this.style&&_!==this._worldview?(this._worldview=_,this._styleDirty=!0,this.style.setWorldview(_),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(_){return this._lazyInitEmptyStyle(),_?typeof _=="string"&&(_={name:_}):_=null,this._useExplicitProjection=!!_,this._prioritizeAndUpdateProjection(_,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const _=this.transform,d=_.projection.name;let g;d==="globe"&&_.zoom>=a.cv?(_.setMercatorFromTransition(),g=!0):d==="mercator"&&_.zoom=a.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(_),this.style.applyProjectionUpdate();const S=this.transform.getProjection().name==="mercator"&&g!==this.transform.mercatorFromTransition;return(d||S)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(_,d){return this.transform.locationPoint3D(a.aU.convert(_),d)}unproject(_,d){return this.transform.pointLocation3D(a.P.convert(_),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(_,d,g){const S=E=>{let R=[];if(Array.isArray(d)){const L=d.filter(B=>this.getLayer(B));R=L.length?this.queryRenderedFeatures(E,{layers:L}):[]}else R=this.queryRenderedFeatures(E,{target:d});return R};if(_==="mouseenter"||_==="mouseover"){let E=!1;return{listener:g,targets:d,delegates:{mousemove:L=>{const B=S(L.point);B.length?E||(E=!0,g.call(this,new Mo(_,this,L.originalEvent,{features:B}))):E=!1},mouseout:()=>{E=!1}}}}if(_==="mouseleave"||_==="mouseout"){let E=!1;return{listener:g,targets:d,delegates:{mousemove:B=>{S(B.point).length?E=!0:E&&(E=!1,g.call(this,new Mo(_,this,B.originalEvent)))},mouseout:B=>{E&&(E=!1,g.call(this,new Mo(_,this,B.originalEvent)))}}}}{const E=R=>{const L=S(R.point);L.length&&(R.features=L,g.call(this,R),delete R.features)};return{listener:g,targets:d,delegates:{[_]:E}}}}on(_,d,g){if(typeof d=="function"||g===void 0)return super.on(_,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const S=this._createDelegatedListener(_,d,g);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[_]=this._delegatedListeners[_]||[],this._delegatedListeners[_].push(S);for(const E in S.delegates)this.on(E,S.delegates[E]);return this}once(_,d,g){if(typeof d=="function"||g===void 0)return super.once(_,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const S=this._createDelegatedListener(_,d,g);for(const E in S.delegates)this.once(E,S.delegates[E]);return this}off(_,d,g){if(typeof d=="function"||g===void 0)return super.off(_,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const S=this._delegatedListeners?this._delegatedListeners[_]:void 0;return S&&(E=>{for(let R=0;R{if(g){const E=typeof g=="string"?g:g instanceof Error?g.message:g.error;a.w(`Unable to perform style diff: ${E}. Rebuilding the style from scratch.`),this._updateStyle(_,d)}else S&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=d.localIdeographFontFamily,this._localFontFamily=d.localFontFamily,this._updateStyle(_,d))}_getUIString(_){const d=this._locale[_];if(d==null)throw new Error(`Missing UI string '${_}'`);return d}_updateStyle(_,d){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),_){const g=Object.assign({},d);d&&d.config&&(g.initialConfig=d.config,delete g.config),this.style=new Du(this,g).load(_),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Du(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():(a.w("There is no style added to the map."),!1)}_isValidId(_){return _==null?(this.fire(new a.B(new Error("IDs can't be empty."))),!1):!a.db(_)||(this.fire(new a.B(new Error(`IDs can't contain special symbols: "${_}".`))),!1)}_isTargetValid(_){return"featuresetId"in _?this._isValidId("importId"in _?_.importId:_.featuresetId):"layerId"in _&&this._isValidId(_.layerId)}_areTargetsValid(_){if(Array.isArray(_)){for(const d of _)if(!this._isValidId(d))return!1;return!0}return this._isTargetValid(_)}addSource(_,d){return this._isValidId(_)?(this._lazyInitEmptyStyle(),this.style.addSource(_,d),this._update(!0)):this}isSourceLoaded(_){return!!this._isValidId(_)&&!!this.style&&this.style._isSourceCacheLoaded(_)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(_,d,g){this._lazyInitEmptyStyle(),this.style.addSourceType(_,d,g)}removeSource(_){return this._isValidId(_)?(this.style.removeSource(_),this._updateTerrain(),this._update(!0)):this}getSource(_){return this._isValidId(_)?this.style.getOwnSource(_):null}addImage(_,d,{pixelRatio:g=1,sdf:S=!1,stretchX:E,stretchY:R,content:L}={}){this._lazyInitEmptyStyle();const B=a.I.from(_);if(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap){const{width:U,height:W,data:Z}=a.o.getImageData(d);this.style.addImage(B,{data:new a.q({width:U,height:W},Z),pixelRatio:g,stretchX:E,stretchY:R,content:L,sdf:S,version:0,usvg:!1})}else if(d.width===void 0||d.height===void 0)this.fire(new a.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:U,height:W}=d,Z=d;this.style.addImage(B,{data:new a.q({width:U,height:W},new Uint8Array(Z.data)),pixelRatio:g,stretchX:E,stretchY:R,content:L,sdf:S,usvg:!1,version:0,userImage:Z}),Z.onAdd&&Z.onAdd(this,_)}}updateImage(_,d){this._lazyInitEmptyStyle();const g=a.I.from(_),S=this.style.getImage(g);if(!S)return void this.fire(new a.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const E=d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap?a.o.getImageData(d):d,{width:R,height:L,data:B}=E;if(R===void 0||L===void 0)return void this.fire(new a.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(R!==(S.usvg?S.icon.usvg_tree.width:S.data.width)||L!==(S.usvg?S.icon.usvg_tree.height:S.data.height))return void this.fire(new a.B(new Error(`The width and height of the updated image (${R}, ${L}) must be that same as the previous version of the image (${S.data.width}, ${S.data.height})`)));const U=!(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap);let W=!1;S.usvg?(S.data=new a.q({width:R,height:L},new Uint8Array(B)),S.usvg=!1,S.icon=void 0,W=!0):S.data.replace(B,U),this.style.updateImage(g,S,W)}hasImage(_){return _?!!this.style&&!!this.style.getImage(a.I.from(_)):(this.fire(new a.B(new Error("Missing required image id"))),!1)}removeImage(_){this.style.removeImage(a.I.from(_))}loadImage(_,d){a.n(this._requestManager.transformRequest(_,a.R.Image),(g,S)=>{d(g,S)})}listImages(){return this.style.listImages().map(_=>_.name)}addModel(_,d){this._lazyInitEmptyStyle(),this.style.addModel(_,d)}hasModel(_){return _?this.style.hasModel(_):(this.fire(new a.B(new Error("Missing required model id"))),!1)}removeModel(_){this.style.removeModel(_)}listModels(){return this.style.listModels()}addLayer(_,d){return this._isValidId(_.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(_,d),this._update(!0)):this}getSlot(_){const d=this.getLayer(_);return d&&d.slot||null}setSlot(_,d){return this.style.setSlot(_,d),this.style.mergeLayers(),this._update(!0)}addImport(_,d){return this.style.addImport(_,d).catch(g=>this.fire(new a.B(new Error("Failed to add import",g)))),this}updateImport(_,d){return typeof d!="string"&&d.id!==_?(this.removeImport(_),this.addImport(d)):(this.style.updateImport(_,d),this._update(!0))}removeImport(_){return this.style.removeImport(_),this}moveImport(_,d){return this.style.moveImport(_,d),this._update(!0)}moveLayer(_,d){return this._isValidId(_)?(this.style.moveLayer(_,d),this._update(!0)):this}removeLayer(_){return this._isValidId(_)?(this.style.removeLayer(_),this._update(!0)):this}getLayer(_){if(!this._isValidId(_))return null;const d=this.style.getOwnLayer(_);return d?d.type==="custom"?d.implementation:d.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(_,d,g){return this._isValidId(_)?(this.style.setLayerZoomRange(_,d,g),this._update(!0)):this}setFilter(_,d,g={}){return this._isValidId(_)?(this.style.setFilter(_,d,g),this._update(!0)):this}getFilter(_){return this._isValidId(_)?this.style.getFilter(_):null}setPaintProperty(_,d,g,S={}){return this._isValidId(_)?(this.style.setPaintProperty(_,d,g,S),this._update(!0)):this}getPaintProperty(_,d){return this._isValidId(_)?this.style.getPaintProperty(_,d):null}setLayoutProperty(_,d,g,S={}){return this._isValidId(_)?(this.style.setLayoutProperty(_,d,g,S),this._update(!0)):this}getLayoutProperty(_,d){return this._isValidId(_)?this.style.getLayoutProperty(_,d):null}setLayerProperty(_,d,g,S={}){return this._isValidId(_)?(d==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(_,d,g,S),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(_){return this.style.setGlyphsUrl(_),this._update(!0)}getSchema(_){return this.style.getSchema(_)}setSchema(_,d){return this.style.setSchema(_,d),this._update(!0)}getConfig(_){return this.style.getConfig(_)}setConfig(_,d){return this.style.setConfig(_,d),this._update(!0)}getConfigProperty(_,d){return this.style.getConfigProperty(_,d)}setConfigProperty(_,d,g){return this.style.setConfigProperty(_,d,g),this._update(!0)}getFeaturesetDescriptors(_){return this.style.getFeaturesetDescriptors(_)}setLights(_){if(this._lazyInitEmptyStyle(),_&&_.length===1&&_[0].type==="flat"){const d=_[0];d.properties?this.style.setFlatLight(d.properties,d.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(_),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const _=this.style.getLights()||[];return _.length===0&&_.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),_}setLight(_,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:_}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(_){return this._lazyInitEmptyStyle(),!_&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(_),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(_){return this._lazyInitEmptyStyle(),this.style.setFog(_),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(_){return this._lazyInitEmptyStyle(),this.style.setSnow(_),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(_){return this._lazyInitEmptyStyle(),this.style.setRain(_),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(_){return this._lazyInitEmptyStyle(),this.style.setColorTheme(_),this._update(!0)}setImportColorTheme(_,d){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(_,d),this._update(!0)}setCamera(_){return this.style.setCamera(_),this._triggerCameraUpdate(_)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(_){const d=this.transform.nearClipOffset!==_;return this.transform.nearClipOffset=_,this._update(d)}_triggerCameraUpdate(_){return this._update(this.transform.setOrthographicProjectionAtLowPitch(_["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(_){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(a.aU.convert(_),this.transform):0}setFeatureState(_,d){return _.source&&!this._isValidId(_.source)?this:(this.style.setFeatureState(_,d),this._update())}removeFeatureState(_,d){return _.source&&!this._isValidId(_.source)?this:(this.style.removeFeatureState(_,d),this._update())}getFeatureState(_){return _.source&&!this._isValidId(_.source)?null:this.style.getFeatureState(_)}_selectIndoorFloor(_){this.style.indoorManager.selectFloor(_)}_setIndoorActiveFloorsVisibility(_){this.style.indoorManager.setActiveFloorsVisibility(_)}getIndoorTileOptions(_,d){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(_,d):null}_updateContainerDimensions(){if(!this._container)return;const _=this._container.getBoundingClientRect().width||400,d=this._container.getBoundingClientRect().height||300;let g,S,E,R=this._container;for(;R&&(!S||!E);){const L=window.getComputedStyle(R).transform;L&&L!=="none"&&(g=L.match(/matrix.*\((.+)\)/)[1].split(", "),g[0]&&g[0]!=="0"&&g[0]!=="1"&&(S=g[0]),g[3]&&g[3]!=="0"&&g[3]!=="1"&&(E=g[3])),R=R.parentElement}this._containerWidth=S?Math.abs(_/S):_,this._containerHeight=E?Math.abs(d/E):d}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&a.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const _=this._container;_.classList.add("mapboxgl-map"),(this._missingCSSCanary=C("div","mapboxgl-canary",_)).style.visibility="hidden",this._detectMissingCSS();const d=this._canvasContainer=C("div","mapboxgl-canvas-container",_);this._canvas=C("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=C("div","mapboxgl-control-container",_),S=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(E=>{S[E]=C("div",`mapboxgl-ctrl-${E}`,g)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(_,d){const g=a.o.devicePixelRatio||1;this._canvas.width=g*Math.ceil(_),this._canvas.height=g*Math.ceil(d),this._canvas.style.width=`${_}px`,this._canvas.style.height=`${d}px`}_addMarker(_){this._markers.push(_)}_removeMarker(_){const d=this._markers.indexOf(_);d!==-1&&this._markers.splice(d,1)}_addPopup(_){this._popups.push(_)}_removePopup(_){const d=this._popups.indexOf(_);d!==-1&&this._popups.splice(d,1)}_setupPainter(){const _=Object.assign({},A.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),d=this._canvas.getContext("webgl2",_);d?(qr(d,!0),this.painter=new NB(d,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",g=>{if(g.dataType==="source"){const S=this.transform.elevation?this.transform.elevation._source():null;S&&g.sourceCacheId===S.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),a.k.testSupport(d)):this.fire(new a.B(new Error("Failed to initialize WebGL")))}_contextLost(_){_.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new a.C("webglcontextlost",{originalEvent:_}))}_contextRestored(_){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new a.C("webglcontextrestored",{originalEvent:_}))}_onMapScroll(_){if(_.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(_){return this.style?(this._styleDirty=this._styleDirty||_,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(_){return this._update(),this._renderTaskQueue.add(_)}_cancelRenderFrame(_){this._renderTaskQueue.remove(_)}_requestDomTask(_){!this.loaded()||this.loaded()&&!this.isMoving()?_():this._domRenderTaskQueue.add(_)}_render(_){let d;this.fire(new a.C("renderstart")),++this._frameId;const g=this.painter.context.extTimerQuery,S=a.o.now(),E=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(d=E.createQuery(),E.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(_),this._domRenderTaskQueue.run(_),this._removed)return;this._updateProjectionTransition();const R=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const U=this.transform.zoom,W=this.transform.pitch,Z=a.o.now(),ne=new a.ae(U,{now:Z,fadeDuration:R,pitch:W,transition:this.style.transition,worldview:this._worldview});this.style.update(ne)}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(S),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):L=this._updateAverageElevation(S),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,R,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:R,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 a.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,y.mark(m.load),this.fire(new a.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 U=a.o.now()-S;E.endQuery(g.TIME_ELAPSED_EXT),setTimeout(()=>{const W=E.getQueryParameter(d,E.QUERY_RESULT)/1e6;E.deleteQuery(d),this.fire(new a.C("gpu-timing-frame",{cpuTime:U,gpuTime:W}))},50)}if(this.listens("gpu-timing-layer")){const U=this.painter.collectGpuTimers();setTimeout(()=>{const W=this.painter.queryGpuTimers(U);this.fire(new a.C("gpu-timing-layer",{layerTimes:W}))},50)}if(this.listens("gpu-timing-deferred-render")){const U=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const W=this.painter.queryGpuTimeDeferredRender(U);this.fire(new a.C("gpu-timing-deferred-render",{gpuTime:W}))},50)}const B=this._sourcesDirty||this._styleDirty||this._placementDirty||L;if(B||this._repaint)this.triggerRepaint();else{const U=this.idle();if(U&&(L=this._updateAverageElevation(S,!0)),L)this.triggerRepaint();else if(this._triggerFrame(!1),U&&(this.fire(new a.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const W=this._calculateSpeedIndex();this.fire(new a.C("speedindexcompleted",{speedIndex:W})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||B||(this._fullyLoaded=!0,y.mark(m.fullLoad),this._performanceMetricsCollection&&Tr(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(_){for(const d of this._markers)_&&!this.getRenderWorldCopies()&&(d._lngLat=d._lngLat.wrap()),d._update();for(const d of this._popups)!_||this.getRenderWorldCopies()||d._trackPointer||(d._lngLat=d._lngLat.wrap()),d._update()}_updateAverageElevation(_,d=!1){const g=E=>(this.transform.averageElevation=E,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&g(0);const S=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(S||(d||_-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(_)){const E=this.transform.averageElevation;let R=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(R)?R=0:this._averageElevationLastSampledAt=_;const L=Math.abs(E-R);if(L>1){if(this._isInitialLoad||S)return this._averageElevation.jumpTo(R),g(R);this._averageElevation.easeTo(R,_,300)}else if(L>1e-4)return this._averageElevation.jumpTo(R),g(R)}return!!this._averageElevation.isEasing(_)&&g(this._averageElevation.getValue(_))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const _=this.painter.context.gl;qr(_,!1),this._logoControl instanceof i2&&this._logoControl._updateLogo(),_&&_.clear(_.DEPTH_BUFFER_BIT|_.COLOR_BUFFER_BIT|_.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new a.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Lr(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,_=>{_&&(_.message!==ye&&_.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),wt(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&>(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&kt(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){xt(this._requestManager._customAccessToken)}_updateTerrain(){const _=this._isDragging();this.painter.updateTerrain(this.style,_)}_calculateSpeedIndex(){const _=this.painter.canvasCopy(),d=this.painter.getCanvasCopiesAndTimestamps();d.timeStamps.push(performance.now());const g=this.painter.context.gl,S=g.createFramebuffer();function E(R){g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,R,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,S),this._canvasPixelComparison(E(_),d.canvasCopies.map(E),d.timeStamps)}_canvasPixelComparison(_,d,g){let S=g[1]-g[0];const E=_.length/4;for(let R=0;R{const g=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,g&&this._render(d)}))}_preloadTiles(_){const d=this.style?this.style.getSourceCaches():[];return a.t(d,(g,S)=>g._preloadTiles(_,S),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(_){this._trackResize&&this.resize({originalEvent:_})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(_){this._showTileBoundaries!==_&&(this._showTileBoundaries=_,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(_){this._showParseStatus!==_&&(this._showParseStatus=_,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(_){this._showTerrainWireframe!==_&&(this._showTerrainWireframe=_,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(_){this._showLayers2DWireframe!==_&&(this._showLayers2DWireframe=_,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(_){this._showLayers3DWireframe!==_&&(this._showLayers3DWireframe=_,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(_){this._speedIndexTiming!==_&&(this._speedIndexTiming=_,this._update())}get showPadding(){return!!this._showPadding}set showPadding(_){this._showPadding!==_&&(this._showPadding=_,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(_){this._showCollisionBoxes!==_&&(this._showCollisionBoxes=_,this.style&&_?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(_){this._showOverdrawInspector!==_&&(this._showOverdrawInspector=_,this._update())}get repaint(){return!!this._repaint}set repaint(_){this._repaint!==_&&(this._repaint=_,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(_){this._vertices=_,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(_){this._showTileAABBs!==_&&(this._showTileAABBs=_,_&&this._update())}_setCacheLimits(_,d){a.e_(_,d)}get version(){return f}},NavigationControl:class{constructor(_={}){this.options=Object.assign({},DB,_),this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",d=>d.preventDefault()),this.options.showZoom&&(a.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",d=>{this._map&&this._map.zoomIn({},{originalEvent:d})}),C("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})}),C("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(a.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=C("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const _=this._map;if(!_)return;const d=_.getZoom(),g=d===_.getMaxZoom(),S=d===_.getMinZoom();this._zoomInButton.disabled=g,this._zoomOutButton.disabled=S,this._zoomInButton.setAttribute("aria-disabled",g.toString()),this._zoomOutButton.setAttribute("aria-disabled",S.toString())}_rotateCompassArrow(){const _=this._map;if(!_)return;const d=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(_.transform.pitch*(Math.PI/180)),.5)}) rotateX(${_.transform.pitch}deg) rotateZ(${_.transform.angle*(180/Math.PI)}deg)`:`rotate(${_.transform.angle*(180/Math.PI)}deg)`;_._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=d)})}onAdd(_){return this._map=_,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),_.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&_.on("pitch",this._rotateCompassArrow),_.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new jv(_,this._compass,this.options.visualizePitch)),this._container}onRemove(){const _=this._map;_&&(this._container.remove(),this.options.showZoom&&_.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&_.off("pitch",this._rotateCompassArrow),_.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(_,d){const g=C("button",_,this._container);return g.type="button",g.addEventListener("click",d),g}_setButtonTitle(_,d){if(!this._map)return;const g=this._map._getUIString(`NavigationControl.${d}`);_.setAttribute("aria-label",g),_.firstElementChild&&_.firstElementChild.setAttribute("title",g)}},GeolocateControl:class extends a.E{constructor(_={}){super();const d=navigator.geolocation;this.options=Object.assign({geolocation:d},kv,_),a.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=VE(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(_){return this._map=_,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(_){const d=(g=!!this.options.geolocation)=>{this._supportsGeolocation=g,_(g)};this._supportsGeolocation!==void 0?_(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(g=>d(g.state!=="denied")).catch(()=>d()):d()}_isOutOfMapMaxBounds(_){const d=this._map.getMaxBounds(),g=_.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(_){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(_))return this._setErrorState(),this.fire(new a.C("outofmaxbounds",_)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=_,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(_),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(_),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new a.C("geolocate",Object.assign({coords:_.coords,timestamp:_.timestamp},_.toJSON?{toJSON:_.toJSON.bind(_)}:{}))),this._finish()}}_updateCamera(_){const d=new a.aU(_.coords.longitude,_.coords.latitude),g=_.coords.accuracy,S=this._map.getBearing(),E=Object.assign({bearing:S},this.options.fitBoundsOptions);this._map.fitBounds(d.toBounds(g),E,{geolocateSource:!0})}_updateMarker(_){if(_){const d=new a.aU(_.coords.longitude,_.coords.latitude);this._accuracyCircleMarker.setLngLat(d).addTo(this._map),this._userLocationDotMarker.setLngLat(d).addTo(this._map),this._accuracy=_.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const _=this._map.transform,d=a.bU(1,_._center.lat)*_.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(_){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(_.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(_.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new a.C("error",{code:_.code,message:_.message,PERMISSION_DENIED:_.PERMISSION_DENIED,POSITION_UNAVAILABLE:_.POSITION_UNAVAILABLE,TIMEOUT:_.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const _=this.options.positionOptions.timeout;_&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},_))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(_){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",d=>d.preventDefault()),this._geolocateButton=C("button","mapboxgl-ctrl-geolocate",this._container),C("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",_===!1){a.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=C("div","mapboxgl-user-location"),this._dotElement.appendChild(C("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(C("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Bu({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=C("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Bu({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 a.C("trackuserlocationend")))})}}_onDeviceOrientation(_){this._userLocationDotMarker&&(_.webkitCompassHeading?this._heading=_.webkitCompassHeading:_.absolute===!0&&(this._heading=-1*_.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return a.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 a.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 a.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 a.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 _;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(_={maximumAge:6e5,timeout:0},this._noTimeout=!0):(_=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,_),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(_){return this.options.followUserLocation=_??kv.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 a.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 a.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const _=()=>{const d="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(d,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(d=>{d==="granted"&&_()}).catch(console.error):_()}_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:s2,ScaleControl:class{constructor(_={}){this.options=Object.assign({},wa,_),a.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const _=this.options.maxWidth||100,d=this._map,g=d._containerHeight/2,S=d._containerWidth/2-_/2,E=d.unproject([S,g]),R=d.unproject([S+_,g]),L=E.distanceTo(R);if(this.options.unit==="imperial"){const B=3.2808*L;B>5280?this._setScale(_,B/5280,"mile"):this._setScale(_,B,"foot")}else this.options.unit==="nautical"?this._setScale(_,L/1852,"nautical-mile"):L>=1e3?this._setScale(_,L/1e3,"kilometer"):this._setScale(_,L,"meter")}_setScale(_,d,g){this._map._requestDomTask(()=>{const S=function(R){const L=Math.pow(10,`${Math.floor(R)}`.length-1);let B=R/L;return B=B>=10?10:B>=5?5:B>=3?3:B>=2?2:B>=1?1:function(U){const W=Math.pow(10,Math.ceil(-Math.log(U)/Math.LN10));return Math.round(U*W)/W}(B),L*B}(d),E=S/d;this._container.innerHTML=g!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:g}).format(S):`${S} ${$u[g]}`,this._container.style.width=_*E+"px"})}onAdd(_){return this._map=_,this._language=_.getLanguage(),this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-scale",_.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(_){this._language=_,this._update()}setUnit(_){this.options.unit=_,this._update()}},FullscreenControl:class{constructor(_={}){this._fullscreen=!1,_&&_.container&&(_.container instanceof HTMLElement?this._container=_.container:a.w("Full screen control 'container' must be a DOM element.")),a.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(_){return this._map=_,this._container||(this._container=this._map.getContainer()),this._controlContainer=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",a.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const _=this._fullscreenButton=C("button","mapboxgl-ctrl-fullscreen",this._controlContainer);C("span","mapboxgl-ctrl-icon",_).setAttribute("aria-hidden","true"),_.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const _=this._getTitle();this._fullscreenButton.setAttribute("aria-label",_),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",_)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){a.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(_){return this._map=_,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const _=this._map.style.indoorManager;_.off("selector-update",this._onIndoorUpdate),_.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(_.getControlState())}}_createButton(_,d){const g=C("button",_,this._container);return g.type="button",g.addEventListener("click",d),g}_setButtonTitle(_,d){_.setAttribute("aria-label",d),_.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(_){if(!_||!_.floors||_.floors.length===0)return this._model=_,void(this._container.style.display="none");const d=this._model;this._model=_,this._container.style.display="inline-block";const g=!d||d.floors.length!==_.floors.length||d.floors.some((S,E)=>S.id!==_.floors[E].id);if(g&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),_.selectedFloorId){if(_.selectedFloorId!==this._lastSelectedFloorId||g){const S=_.floors.findIndex(E=>E.id===_.selectedFloorId);if(S!==-1){const E=_.floors.length;let R,L;E<=5?(R=0,L=E-1):this._visibleFloorStart===0?(R=0,L=3):this._visibleFloorStart>=E-3?(R=E-3-1,L=E-1):(R=this._visibleFloorStart,L=this._visibleFloorStart+3-1),SL&&(this._visibleFloorStart=S-2)}}this._lastSelectedFloorId=_.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const _=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);C("span","mapboxgl-ctrl-icon",_).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||_.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(_);const d=this._model.floors,g=d.length;if(g<=5)return void d.forEach(L=>this._createFloorButton(L));const S=this._visibleFloorStart===0,E=this._visibleFloorStart>=g-3;if(S)this._createFloorButton(d[0]);else{const L=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);C("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}let R=[];if(R=S?d.slice(1,4):E?d.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):d.slice(this._visibleFloorStart,this._visibleFloorStart+3),R.forEach(L=>this._createFloorButton(L)),E)this._createFloorButton(d[g-1]);else{const L=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);C("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}}_createFloorButton(_){const d=this._createButton("mapboxgl-ctrl-level-button",()=>{const R=_.id;this._model&&this._model.selectedFloorId===R&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(R))}),g=(_.name||"").trim(),S=_.zIndex.toString(),E=g?Array.from(g).slice(0,3).join(""):S;this._setButtonTitle(d,E),this._model&&this._model.activeFloorsVisible&&_.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 _=this._model&&this._model.floors||[];if(_.length>3){const d=_.length-3;this._visibleFloorStart===d-1&&(this._visibleFloorStart=d-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const _=this._model.floors.length-3;this._visibleFloorStart<_&&(this._visibleFloorStart++,this._visibleFloorStart===1&&(this._visibleFloorStart=2),this._visibleFloorStart===_-1&&(this._visibleFloorStart=_),this._visibleFloorStart>_&&(this._visibleFloorStart=_),this._render())}}},Popup:class extends a.E{constructor(_){super(),this.options=Object.assign(Object.create(Av),_),this._altitude=this.options.altitude,a.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(_&&_.className?_.className.trim().split(/\s+/):[])}addTo(_){return this._map&&this.remove(),this._map=_,this.options.closeOnClick&&_.on("preclick",this._onClose),this.options.closeOnMove&&_.on("move",this._onClose),_.on("remove",this.remove),this._update(),_._addPopup(this),this._focusFirstElement(),this._trackPointer?(_.on("mousemove",this._onMouseEvent),_.on("mouseup",this._onMouseEvent),_._canvasContainer.classList.add("mapboxgl-track-pointer")):_.on("move",this._update),this.fire(new a.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const _=this._map;return _&&(_.off("move",this._update),_.off("move",this._onClose),_.off("preclick",this._onClose),_.off("click",this._onClose),_.off("remove",this.remove),_.off("mousemove",this._onMouseEvent),_.off("mouseup",this._onMouseEvent),_.off("drag",this._onMouseEvent),_._canvasContainer&&_._canvasContainer.classList.remove("mapboxgl-track-pointer"),_._removePopup(this),this._map=void 0),this.fire(new a.C("close")),this}getLngLat(){return this._lngLat}setLngLat(_){this._lngLat=a.aU.convert(_),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(_){return this._altitude=_,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const _=this._map;return _&&(_.off("move",this._update),_.on("mousemove",this._onMouseEvent),_.on("drag",this._onMouseEvent),_._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(_){return this.setDOMContent(document.createTextNode(_))}setHTML(_){const d=document.createDocumentFragment(),g=document.createElement("body");let S;for(g.innerHTML=_;S=g.firstChild,S;)d.appendChild(S);return this.setDOMContent(d)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(_){return this.options.maxWidth=_,this._update(),this}setDOMContent(_){let d=this._content;if(d)for(;d.hasChildNodes();)d.firstChild&&d.removeChild(d.firstChild);else d=this._content=C("div","mapboxgl-popup-content",this._container||void 0);if(d.appendChild(_),this.options.closeButton){const g=this._closeButton=C("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(_){return this._classList.add(_),this._updateClassList(),this}removeClassName(_){return this._classList.delete(_),this._updateClassList(),this}setOffset(_){return this.options.offset=_,this._update(),this}toggleClassName(_){let d;return this._classList.delete(_)?d=!1:(this._classList.add(_),d=!0),this._updateClassList(),d}_onMouseEvent(_){this._update(_.point)}_getAnchor(_){if(this.options.anchor)return this.options.anchor;const d=this._map,g=this._container,S=this._pos;if(!d||!g||!S)return"bottom";const E=g.offsetWidth,R=g.offsetHeight,L=S.xd.transform.width-E/2;if(S.y+_d.transform.height-R){if(L)return"bottom-left";if(B)return"bottom-right"}return L?"left":B?"right":"bottom"}_updateClassList(){const _=this._container;if(!_)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"),_.className=d.join(" ")}_update(_){const d=this._map,g=this._content;if(!d||!this._lngLat&&!this._trackPointer||!g)return;let S=this._container;if(S||(S=this._container=C("div","mapboxgl-popup",d.getContainer()),this._tip=C("div","mapboxgl-popup-tip",S),S.appendChild(g)),this.options.maxWidth&&S.style.maxWidth!==this.options.maxWidth&&(S.style.maxWidth=this.options.maxWidth),d.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=a2(this._lngLat,this._pos,d.transform)),!this._trackPointer||_){const E=this._pos=this._trackPointer&&_ instanceof a.P?_:d.project(this._lngLat,this._altitude),R=Aw(this.options.offset),L=this._anchor=this._getAnchor(R.y),B=Aw(this.options.offset,L),U=E.add(B).round();d._requestDomTask(()=>{this._container&&L&&(this._container.style.transform=`${Ev[L]} translate(${U.x}px,${U.y}px)`)})}if(!this._marker&&d._showingGlobe()){const E=a.e$(d.transform,this._lngLat)?0:1;this._setOpacity(E)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const _=this._container.querySelector(OB);_&&_.focus()}_onClose(){this.remove()}_setOpacity(_){this._container&&(this._container.style.opacity=`${_}`),this._content&&(this._content.style.pointerEvents=_?"auto":"none")}},Marker:Bu,Style:Du,LngLat:a.aU,LngLatBounds:a.aK,Point:a.P,MercatorCoordinate:a.ag,FreeCameraOptions:q0,Evented:a.E,config:a.g,prewarm:function(){yn().acquire(ar)},clearPrewarmedResources:function(){const _=At;_&&(_.isPreloaded()&&_.numActive()===1?(_.release(ar),At=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 a.g.ACCESS_TOKEN},set accessToken(_){a.g.ACCESS_TOKEN=_},get baseApiUrl(){return a.g.API_URL},set baseApiUrl(_){a.g.API_URL=_},get workerCount(){return Wt.workerCount},set workerCount(_){Wt.workerCount=_},get maxParallelImageRequests(){return a.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(_){a.g.MAX_PARALLEL_IMAGE_REQUESTS=_},clearStorage(_){a.f7(_)},get workerUrl(){return Tt.workerUrl},set workerUrl(_){Tt.workerUrl=_},get workerClass(){return Tt.workerClass},set workerClass(_){Tt.workerClass=_},get workerParams(){return Tt.workerParams},set workerParams(_){Tt.workerParams=_},get dracoUrl(){return a.f6()},set dracoUrl(_){a.g.DRACO_URL=a.o.resolveURL(_)},get meshoptUrl(){return a.f5()},set meshoptUrl(_){const d=a.o.resolveURL(_);a.g.MESHOPT_URL=d,a.g.MESHOPT_SIMD_URL=d},get buildingGenUrl(){return a.f4()},set buildingGenUrl(_){a.g.BUILDING_GEN_URL=a.o.resolveURL(_)},setNow:a.o.setNow,restoreNow:a.o.restoreNow}});var c=i;return c})})(iSe);var Dtt=iSe.exports;const cc=wi(Dtt),Lie={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"},Mie={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 Ott(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function Ftt({listings:t,isLoading:e}){const r=Bi(),n=N.useRef(null),i=N.useRef(null),o=N.useRef([]),[c,a]=N.useState(""),[f,m]=N.useState(!0);return N.useEffect(()=>{(async()=>{m(!0);try{const{data:w}=await Ce.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w!=null&&w.value&&a(w.value)}catch(w){console.error("Error fetching mapbox token:",w)}m(!1)})()},[]),N.useEffect(()=>{if(!n.current||!c||i.current)return;cc.accessToken=c;const v=t.filter(A=>A.latitude!=null&&A.longitude!=null);let w=[-98.5795,39.8283],j=4;if(v.length>0){const A=v.reduce((I,M)=>I+M.longitude,0)/v.length,C=v.reduce((I,M)=>I+M.latitude,0)/v.length;w=[A,C],j=v.length===1?12:10}return i.current=new cc.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:w}),i.current.addControl(new cc.NavigationControl,"top-right"),()=>{var A;(A=i.current)==null||A.remove(),i.current=null}},[c]),N.useEffect(()=>{if(!i.current||!c)return;o.current.forEach(w=>w.remove()),o.current=[];const v=t.filter(w=>w.latitude!=null&&w.longitude!=null);if(v.forEach(w=>{var z,q,H;const j=Lie[w.status]||"#10B981",A=((z=w.photos)==null?void 0:z.find(K=>K.is_primary))||((q=w.photos)==null?void 0:q[0]),I=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${w.slug||w.id}`:`/public/listing/${w.slug||w.id}`,M=document.createElement("div");M.className="cursor-pointer",M.innerHTML=`
`;const D=new cc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${A!=null&&A.photo_url?``:""}
${Ott(w.price)}
${w.property_address||""}
${w.city}, ${w.state}
${Mie[w.status]||w.status} ${w.bedrooms?`${w.bedrooms} bed`:""} ${w.bathrooms?`${w.bathrooms} bath`:""}
${(H=w.agent)!=null&&H.name?`
Listed by ${w.agent.name}
`:""}
Click to view details →
`),F=new cc.Marker(M).setLngLat([w.longitude,w.latitude]).setPopup(D).addTo(i.current);o.current.push(F)}),v.length>1){const w=new cc.LngLatBounds;v.forEach(j=>w.extend([j.longitude,j.latitude])),i.current.fitBounds(w,{padding:60,maxZoom:13})}else v.length===1&&i.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[t,c]),N.useEffect(()=>(window.__navigateToPublicListing__=v=>{r(v)},()=>{delete window.__navigateToPublicListing__}),[r]),f||e?s.jsx(Al,{className:"w-full h-[500px] rounded-lg"}):!c||t.filter(v=>v.latitude!=null&&v.longitude!=null).length===0?null:s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(Lie).map(([v,w])=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:w}}),s.jsx("span",{className:"text-xs text-gray-600",children:Mie[v]})]},v))}),s.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const O6={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"},Btt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},m1="#0d0d0d",Die="#1a1a1a",ci="#c9a84c",Vy="#f0d78c";function oSe(){const[t,e]=N.useState(""),[r,n]=N.useState(!1),[i,o]=N.useState(!1),[c,a]=N.useState(!1),[f,m]=N.useState(-1),y=N.useRef(null),[v,w]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:j}=ytt(),A=N.useMemo(()=>{if(!j)return[];const oe=t.trim().toLowerCase(),de=[...j.cities.map(we=>({label:we.label,value:we.city,type:"city",count:we.count})),...j.neighborhoods.map(we=>({label:we.label,value:we.neighborhood,type:"neighborhood",count:we.count})),...j.zips.map(we=>({label:`ZIP ${we.label}`,value:we.zip,type:"zip",count:we.count}))];return(oe?de.filter(we=>we.label.toLowerCase().includes(oe)||we.value.toLowerCase().includes(oe)):de).slice(0,8)},[j,t]);N.useEffect(()=>{const oe=de=>{y.current&&!y.current.contains(de.target)&&a(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]);const{data:C,isLoading:I}=gtt({city:t||void 0,status:v.status||void 0,propertyType:v.propertyType||void 0,minPrice:v.minPrice?Number(v.minPrice):void 0,maxPrice:v.maxPrice?Number(v.maxPrice):void 0}),M=oe=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(oe),D=()=>{w({status:"",propertyType:"",minPrice:"",maxPrice:""}),e("")},F=t||v.status||v.propertyType||v.minPrice||v.maxPrice,z=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),q=oe=>z?`/${oe.slug||oe.id}`:`/public/listing/${oe.slug||oe.id}`,{featured:H,restListings:K,luxeCount:J,cities:Q,activeCount:ee}=N.useMemo(()=>{const oe=C||[],de=oe.filter(Ze=>Ze.status==="active"),ye=de.length>0?de:oe,we=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Le,Se,ve]=we.split("-").map(Number),me=Math.floor(Date.UTC(Le,Se-1,ve)/864e5),ke=ye.length>0?ye[me%ye.length]:void 0,Pe=oe.filter(Ze=>!ke||Ze.id!==ke.id),Ee=Array.from(new Set(oe.map(Ze=>Ze.city).filter(Boolean))).slice(0,8),xe=oe.filter(Ze=>(Ze.price||0)>=1e6).length,Ue=de.length;return{featured:ke,restListings:Pe,luxeCount:xe,cities:Ee,activeCount:Ue}},[C]);return s.jsxs(s.Fragment,{children:[s.jsxs(no,{children:[s.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),s.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),s.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),s.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),s.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),s.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:m1,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[s.jsx("style",{children:` .lu-serif { font-family: 'DM Serif Display', Georgia, serif; font-weight: 400; letter-spacing: -0.01em; } .lu-eyebrow { font-family: 'Fira Sans', sans-serif; font-weight: 500; letter-spacing: 0.3em; text-transform: uppercase; font-size: 11px; } .lu-gold { color: ${ci}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${ci}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),s.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[s.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[s.jsxs(xr,{to:"/",className:"flex items-center gap-3",children:[s.jsx("img",{src:Rie,alt:"LevelUp",className:"h-7"}),s.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),s.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[s.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),s.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),s.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),s.jsx(xr,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${ci}`,color:ci},children:"About LevelUp"})]}),s.jsx("button",{type:"button",onClick:()=>o(oe=>!oe),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${ci}`,color:ci},"aria-label":"Toggle menu","aria-expanded":i,children:i?s.jsx(Ci,{className:"w-5 h-5"}):s.jsx(p0,{className:"w-5 h-5"})})]}),i&&s.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:s.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[s.jsx("a",{href:"#featured",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),s.jsx("a",{href:"#collection",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),s.jsx("a",{href:"#map",onClick:()=>o(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),s.jsx(xr,{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"}),s.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 ${ci}`,color:ci},children:"About LevelUp"})]})})]}),s.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("img",{src:Mtt,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(13,13,13,0.55) 0%, rgba(13,13,13,0.25) 40%, rgba(13,13,13,0.9) 100%)"}})]}),s.jsxs("div",{className:"relative max-w-7xl mx-auto px-6 pt-24 md:pt-32 pb-16 flex flex-col justify-center",style:{minHeight:"92vh"},children:[s.jsxs("div",{className:"max-w-4xl",children:[s.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[s.jsx("span",{className:"h-px w-10",style:{background:ci}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),s.jsxs("h1",{className:"lu-serif lu-hero-title text-white text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.02] mb-6",children:["Homes with a",s.jsx("br",{}),s.jsx("span",{className:"italic",style:{color:Vy},children:"quiet"})," kind of luxury."]}),s.jsx("p",{className:"lu-hero-sub text-white/75 text-lg md:text-xl max-w-2xl mb-10 leading-relaxed",children:"A private, hand-picked collection of properties represented by LevelUp agents — from waterfront estates to architectural landmarks and everything in between."}),s.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:y,children:[s.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${ci}`,backdropFilter:"blur(12px)"},children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(nd,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:ci}}),s.jsx(Or,{placeholder:"City, neighborhood, or ZIP",value:t,onChange:oe=>{e(oe.target.value),a(!0),m(-1)},onFocus:()=>a(!0),onKeyDown:oe=>{if(!(!c||A.length===0))if(oe.key==="ArrowDown")oe.preventDefault(),m(de=>Math.min(de+1,A.length-1));else if(oe.key==="ArrowUp")oe.preventDefault(),m(de=>Math.max(de-1,0));else if(oe.key==="Enter"&&f>=0){oe.preventDefault();const de=A[f];e(de.value),a(!1)}else oe.key==="Escape"&&a(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),s.jsxs("button",{onClick:()=>n(!r),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[s.jsx(fFe,{className:"h-4 w-4"}),"Filters"]}),s.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:ci,color:m1},onClick:()=>a(!1),children:[s.jsx(nd,{className:"h-5 w-5"}),s.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),c&&A.length>0&&s.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[s.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:ci},children:"Suggestions"}),s.jsx("ul",{className:"max-h-80 overflow-y-auto",children:A.map((oe,de)=>s.jsx("li",{children:s.jsxs("button",{type:"button",onMouseEnter:()=>m(de),onClick:()=>{e(oe.value),a(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:f===de?"rgba(201,168,76,0.12)":"transparent"},children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[oe.type==="city"&&s.jsx(ii,{className:"h-4 w-4 shrink-0",style:{color:ci}}),oe.type==="neighborhood"&&s.jsx(to,{className:"h-4 w-4 shrink-0",style:{color:ci}}),oe.type==="zip"&&s.jsx(ta,{className:"h-4 w-4 shrink-0",style:{color:ci}}),s.jsx("span",{className:"text-white/90 truncate",children:oe.label})]}),s.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[oe.count," ",oe.count===1?"listing":"listings"]})]})},`${oe.type}-${oe.value}-${de}`))})]}),c&&t.trim()&&A.length===0&&s.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),r&&s.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),s.jsxs(Pa,{value:v.status||"all",onValueChange:oe=>w({...v,status:oe==="all"?"":oe}),children:[s.jsx(va,{className:"lu-input-dark",children:s.jsx(Ra,{})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"all",children:"Any status"}),Object.entries(O6).map(([oe,de])=>s.jsx(gn,{value:oe,children:de},oe))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),s.jsxs(Pa,{value:v.propertyType||"all",onValueChange:oe=>w({...v,propertyType:oe==="all"?"":oe}),children:[s.jsx(va,{className:"lu-input-dark",children:s.jsx(Ra,{})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"all",children:"Any type"}),Object.entries(Btt).map(([oe,de])=>s.jsx(gn,{value:oe,children:de},oe))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),s.jsx(Or,{type:"number",placeholder:"No min",value:v.minPrice,onChange:oe=>w({...v,minPrice:oe.target.value}),className:"lu-input-dark"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),s.jsx(Or,{type:"number",placeholder:"No max",value:v.maxPrice,onChange:oe=>w({...v,maxPrice:oe.target.value}),className:"lu-input-dark"})]}),F&&s.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:s.jsxs(Lt,{variant:"ghost",size:"sm",onClick:D,className:"text-white/70 hover:text-white gap-1",children:[s.jsx(Ci,{className:"h-4 w-4"})," Clear all"]})})]})]}),s.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((C==null?void 0:C.length)??0).toString()},{label:"Active Now",value:ee.toString()},{label:"Luxury $1M+",value:J.toString()}].map(oe=>s.jsxs("div",{children:[s.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:Vy},children:oe.value}),s.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:oe.label})]},oe.label))})]}),s.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[s.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),s.jsx(Wo,{className:"h-4 w-4 animate-bounce"})]})]})]}),Q.length>0&&s.jsx("section",{className:"py-8 overflow-hidden",style:{background:Die,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:s.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...Q,...Q,...Q].map((oe,de)=>s.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[oe,s.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:ci}})]},de))})}),H&&s.jsx("section",{id:"featured",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(ki,{className:"h-4 w-4",style:{color:ci}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",s.jsx("span",{className:"italic",style:{color:Vy},children:"standout"}),"."]})]}),s.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),s.jsx(xr,{to:q(H),className:"group block",children:s.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[s.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var de,ye;const oe=((de=H.photos)==null?void 0:de.find(we=>we.is_primary))||((ye=H.photos)==null?void 0:ye[0]);return oe?s.jsx("img",{src:oe.photo_url,alt:H.property_address||H.city,className:"w-full h-full object-cover lu-img-zoom"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(ta,{className:"h-16 w-16 text-white/20"})})})(),s.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:ci,color:m1},children:O6[H.status]||"Featured"})]}),s.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[s.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[s.jsx(ii,{className:"h-3.5 w-3.5",style:{color:ci}}),H.city,H.state?`, ${H.state}`:""]}),H.property_address&&s.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:H.property_address}),s.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:Vy},children:M(H.price)}),s.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[H.bedrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(ZT,{className:"h-4 w-4",style:{color:ci}}),H.bedrooms," bd"]}),H.bathrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(m0,{className:"h-4 w-4",style:{color:ci}}),H.bathrooms," ba"]}),H.square_footage&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(OH,{className:"h-4 w-4",style:{color:ci}}),H.square_footage.toLocaleString()," sf"]})]}),H.description&&s.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:H.description}),s.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:ci},children:["View Residence ",s.jsx(ei,{className:"h-4 w-4"})]})]})]})})]})}),s.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:Die},children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsxs("div",{className:"text-center mb-14",children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[s.jsx("span",{className:"h-px w-10",style:{background:ci}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),s.jsx("span",{className:"h-px w-10",style:{background:ci}})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",s.jsx("span",{className:"italic",style:{color:Vy},children:"carefully considered"}),"."]}),s.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),I?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((oe,de)=>s.jsxs("div",{className:"space-y-3",children:[s.jsx(Al,{className:"aspect-[4/5] bg-white/5"}),s.jsx(Al,{className:"h-6 w-32 bg-white/5"}),s.jsx(Al,{className:"h-4 w-full bg-white/5"})]},de))}):K.length>0?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:K.map(oe=>{var ye,we,Le,Se,ve;const de=((ye=oe.photos)==null?void 0:ye.find(me=>me.is_primary))||((we=oe.photos)==null?void 0:we[0]);return s.jsxs(xr,{to:q(oe),className:"group lu-card-hover block",children:[s.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[de?s.jsx("img",{src:de.photo_url,alt:oe.property_address||oe.city,className:"w-full h-full object-cover lu-img-zoom"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(ta,{className:"h-12 w-12 text-white/20"})}),s.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"linear-gradient(180deg, transparent 40%, rgba(13,13,13,0.85) 100%)"}}),s.jsx("div",{className:"absolute top-4 left-4 px-3 py-1 lu-eyebrow rounded-full",style:{background:"rgba(13,13,13,0.75)",color:ci,border:`1px solid ${ci}`},children:O6[oe.status]}),s.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[oe.bedrooms&&s.jsxs("span",{children:[oe.bedrooms," bd"]}),oe.bathrooms&&s.jsxs("span",{children:[oe.bathrooms," ba"]}),oe.square_footage&&s.jsxs("span",{children:[oe.square_footage.toLocaleString()," sf"]})]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[s.jsx(ii,{className:"h-3 w-3",style:{color:ci}}),oe.city,oe.state?`, ${oe.state}`:""]}),s.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:Vy},children:M(oe.price)}),oe.property_address&&s.jsx("p",{className:"text-white/70 text-sm truncate",children:oe.property_address}),((Le=oe.agent)==null?void 0:Le.name)&&s.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[s.jsx(to,{className:"h-3 w-3"}),oe.agent.name,(((Se=oe.agent.brokerage)==null?void 0:Se.name)||oe.agent.brokerage_name)&&s.jsxs("span",{className:"truncate",children:["· ",((ve=oe.agent.brokerage)==null?void 0:ve.name)||oe.agent.brokerage_name]})]})]})]},oe.id)})}):s.jsxs("div",{className:"text-center py-20",children:[s.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${ci}`},children:s.jsx(ta,{className:"h-8 w-8",style:{color:ci}})}),s.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),s.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),F&&s.jsx(Lt,{onClick:D,style:{background:ci,color:m1},className:"hover:brightness-110",children:"Clear filters"})]})]})}),C&&C.length>0&&s.jsx("section",{id:"map",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("span",{className:"h-px w-10",style:{background:ci}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",s.jsx("span",{className:"italic",style:{color:Vy},children:"on the map"}),"."]})]})}),s.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:s.jsx(Ftt,{listings:C,isLoading:I})})]})}),s.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[s.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${m1} 70%)`}}),s.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[s.jsx("span",{className:"h-px w-10",style:{background:ci}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),s.jsx("span",{className:"h-px w-10",style:{background:ci}})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",s.jsx("br",{}),s.jsx("span",{className:"italic",style:{color:Vy},children:"stage this good"}),"."]}),s.jsx("p",{className:"text-white/70 text-lg mb-10 max-w-2xl mx-auto",children:"Join LevelUp and get every listing published to this collection — with a cinematic microsite, lead capture, and marketing tools that do the heavy lifting."}),s.jsxs("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 px-8 py-4 rounded-full font-medium transition hover:brightness-110",style:{background:ci,color:m1},children:["Explore LevelUp",s.jsx(ei,{className:"h-4 w-4"})]})]})]}),s.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("img",{src:Rie,alt:"LevelUp",className:"h-6"}),s.jsx("span",{className:"h-4 w-px bg-white/20"}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),s.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),s.jsx(Wet,{}),s.jsx(Ket,{})]})}const $tt=Object.freeze(Object.defineProperty({__proto__:null,default:oSe},Symbol.toStringTag,{value:"Module"})),ztt=N.lazy(()=>Oe(()=>import("./PublicHomeValue-78d490U4.js"),[]));function Utt(){const t=xs(),e=window.location.hostname;if(!(e==="listings.relevelup.com"||e.startsWith("listings.")))return null;const n=t.pathname.slice(1);return!n||n===""?s.jsx(oSe,{}):n==="home-value"||n==="whats-my-home-worth"?s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(ztt,{})}):n.startsWith("public/")?null:s.jsx(kK,{slugOverride:n})}const Vtt=N.lazy(()=>Oe(()=>import("./CommercialMarketplace-DBj5IHB4.js"),[]));function qtt(){const e=xs().pathname.slice(1);return e?e.startsWith("public/")?null:s.jsx(kK,{slugOverride:e}):s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:s.jsx(Vtt,{})})}function wF({card:t,variant:e}){const r=t.brokerage_display_name||t.brokerage_logo_url,n=t.team_name||t.team_logo_url;if(!r&&!n)return null;const i={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[e];return s.jsx("div",{className:`rounded-2xl p-4 mb-6 ${i.container}`,children:s.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&s.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[t.brokerage_logo_url&&s.jsx("img",{src:t.brokerage_logo_url,alt:t.brokerage_display_name||"Brokerage",style:{height:`${t.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),t.brokerage_display_name&&!t.brokerage_logo_url&&s.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.brokerage_display_name})]}),n&&s.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[t.team_logo_url&&s.jsx("img",{src:t.team_logo_url,alt:t.team_name||"Team",style:{height:`${t.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.team_name})]})]})})}const Gtt=t=>mr({queryKey:["agent-card-public",t],queryFn:async()=>{if(!t)throw new Error("No slug provided");const{data:e,error:r}=await Ce.from("agent_cards").select("*").eq("slug",t).eq("is_published",!0).single();if(r)throw r;const{data:n}=await Ce.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:a}=await Ce.from("brokerages").select("name").eq("id",n.brokerage_id).single();i=(a==null?void 0:a.name)||null}let o=null;try{const{data:a}=await Ce.from("profiles").select("avatar_url").eq("id",e.user_id).single();if(a!=null&&a.avatar_url)o=a.avatar_url;else{const{data:f}=await Ce.storage.from("avatars").list(`${e.user_id}`);if(f&&f.length>0){const{data:m}=Ce.storage.from("avatars").getPublicUrl(`${e.user_id}/${f[0].name}`);o=`${m.publicUrl}?t=${Date.now()}`}}}catch{}const c={...n||{name:null,email:null,phone:null,brokerage_id:null},email:e.display_email||(n==null?void 0:n.email)||null};return{...e,social_links:e.social_links||[],profile:c,brokerage_name:e.brokerage_display_name||i,avatar_url:o}},enabled:!!t}),ptr=()=>mr({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:t,error:e}=await Ce.from("agent_cards").select("*").order("created_at",{ascending:!1});if(e)throw e;return t}}),gtr=t=>mr({queryKey:["agent-card",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Ce.from("agent_cards").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),ytr=()=>{const t=kr();return Ar({mutationFn:async e=>{const{data:r,error:n}=await Ce.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"]}),$t.success("Agent card created")},onError:e=>$t.error(e.message)})},xtr=()=>{const t=kr();return Ar({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Ce.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"]}),$t.success("Agent card updated")},onError:e=>$t.error(e.message)})},di=async(t,e,r,n)=>{const i=new URLSearchParams(window.location.search);await Ce.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:{}})},Htt=async(t,e)=>{const{error:r}=await Ce.from("agent_card_leads").insert({card_id:t,...e});if(r)throw r},vtr=t=>mr({queryKey:["agent-card-analytics",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Ce.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 Ce.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,a=(e==null?void 0:e.filter(f=>f.interaction_type==="contact_saved").length)||0;return{views:o,clicks:c,saves:a,leads:n||[],interactions:e||[]}},enabled:!!t});function SF({open:t,onOpenChange:e,cardId:r,type:n,agentName:i}){const[o,c]=N.useState(""),[a,f]=N.useState(""),[m,y]=N.useState(""),[v,w]=N.useState(""),[j,A]=N.useState(""),[C,I]=N.useState(!1),M=async D=>{if(D.preventDefault(),!o.trim()){$t.error("Please enter your name");return}I(!0);try{await Htt(r,{lead_type:n,name:o.trim(),email:a.trim()||void 0,phone:m.trim()||void 0,message:j.trim()||void 0,intent:v||void 0}),di(r,"lead_submitted",n),Ce.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:o.trim(),email:a.trim()||void 0,phone:m.trim()||void 0,message:j.trim()||void 0,intent:v||void 0}}).catch(F=>console.error("Card lead notify failed:",F)),$t.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(""),w(""),A("")}catch{$t.error("Something went wrong. Please try again.")}finally{I(!1)}};return s.jsx(Wa,{open:t,onOpenChange:e,children:s.jsxs(La,{className:"sm:max-w-md rounded-2xl",children:[s.jsxs(Ko,{children:[s.jsx(Po,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),s.jsx(sd,{children:n==="booking"?`Let ${i} know you'd like to connect.`:n==="connect"?`Share your info and ${i} will reach out.`:`Know someone who could use ${i}'s help?`})]}),s.jsxs("form",{onSubmit:M,className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lead-name",children:"Name *"}),s.jsx(Or,{id:"lead-name",value:o,onChange:D=>c(D.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lead-phone",children:"Phone"}),s.jsx(Or,{id:"lead-phone",type:"tel",value:m,onChange:D=>y(D.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lead-email",children:"Email"}),s.jsx(Or,{id:"lead-email",type:"email",value:a,onChange:D=>f(D.target.value),placeholder:"you@example.com"})]}),n==="booking"&&s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lead-intent",children:"I'm looking to..."}),s.jsxs(Pa,{value:v,onValueChange:w,children:[s.jsx(va,{children:s.jsx(Ra,{placeholder:"Select one"})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"buy",children:"Buy a home"}),s.jsx(gn,{value:"sell",children:"Sell my home"}),s.jsx(gn,{value:"both",children:"Buy & Sell"}),s.jsx(gn,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),s.jsx(Or,{id:"lead-message",value:j,onChange:D=>A(D.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),s.jsx(Lt,{type:"submit",className:"w-full rounded-2xl",disabled:C,children:C?"Sending...":"Submit"})]})]})})}const Wtt=t=>mr({queryKey:["card-blocks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Ce.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}),_tr=t=>mr({queryKey:["card-blocks-all",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Ce.from("card_blocks").select("*").eq("card_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),btr=()=>{const t=kr();return Ar({mutationFn:async e=>{const{data:r,error:n}=await Ce.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]}),$t.success("Block added")},onError:e=>$t.error(e.message)})},wtr=()=>{const t=kr();return Ar({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Ce.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"]}),$t.success("Block updated")},onError:e=>$t.error(e.message)})},Str=()=>{const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await Ce.from("card_blocks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),$t.success("Block removed")},onError:e=>$t.error(e.message)})};function Ktt(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 Ytt(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 Ztt={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 Xtt({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=Ytt(r.video_url),o=n||!!i,c=n?Ktt(r.video_url):i||r.video_url;return s.jsx("div",{className:Ztt[e],children:o?s.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:s.jsx("iframe",{src:c,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):s.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const Qtt={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 Jtt({block:t,variant:e}){const n=t.config.testimonials||[],[i,o]=N.useState(0);if(n.length===0)return null;const c=Qtt[e],a=n[i];return s.jsxs("div",{className:c.container,children:[s.jsxs("div",{className:c.card,children:[s.jsx(lFe,{className:"h-4 w-4 mb-2 opacity-30"}),s.jsxs("p",{className:`${c.quote} mb-3`,children:['"',a.quote,'"']}),s.jsxs("div",{children:[s.jsx("p",{className:c.name,children:a.name}),a.role&&s.jsx("p",{className:c.role,children:a.role})]})]}),n.length>1&&s.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[s.jsx("button",{onClick:()=>o(f=>(f-1+n.length)%n.length),className:c.nav,children:s.jsx(lp,{className:"h-4 w-4"})}),s.jsx("div",{className:"flex gap-1.5",children:n.map((f,m)=>s.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${m===i?c.dot:c.dotInactive}`,onClick:()=>o(m)},m))}),s.jsx("button",{onClick:()=>o(f=>(f+1)%n.length),className:c.nav,children:s.jsx(Wd,{className:"h-4 w-4"})})]})]})}const ert={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 trt({block:t,variant:e}){const n=t.config.tags||[];if(n.length===0)return null;const i=ert[e];return s.jsx("div",{className:i.container,children:n.map((o,c)=>s.jsx("span",{className:i.tag,children:o},c))})}const rrt={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 nrt({block:t,cardId:e,variant:r}){const i=t.config.links||[];if(i.length===0)return null;const o=rrt[r];return s.jsx("div",{className:o.container,children:i.map((c,a)=>s.jsxs("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(e,"button_click",`custom_link_${c.label}`),className:o.link,children:[s.jsx("span",{children:c.label}),s.jsx(mb,{className:`h-4 w-4 ${o.icon}`})]},a))})}const srt={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 irt({path:t,color:e,size:r=20}){return s.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:e,children:s.jsx("path",{d:t})})}const art={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 ort({block:t,cardId:e,variant:r}){const i=t.config.platforms||[],o=art[r];return i.length===0?null:s.jsxs("div",{className:o.container,children:[s.jsx("h3",{className:o.title,children:"Follow Me"}),s.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:i.map((c,a)=>{const f=srt[c.platform.toLowerCase()];return!f||!c.url?null:s.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(e,"button_click",`social_${c.platform}`),className:o.linkClass,title:f.label,children:s.jsx(irt,{path:f.icon,color:f.color})},a)})})]})}function TF({cardId:t,variant:e}){const{data:r}=Wtt(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"),s.jsxs(s.Fragment,{children:[i.map(c=>{switch(c.block_type){case"video_intro":return s.jsx(Xtt,{block:c,variant:e},c.id);case"testimonials":return s.jsx(Jtt,{block:c,variant:e},c.id);case"specialties":return s.jsx(trt,{block:c,variant:e},c.id);case"custom_links":return s.jsx(nrt,{block:c,cardId:t,variant:e},c.id);default:return null}}),o&&s.jsx(ort,{block:o,cardId:t,variant:e})]})}async function lrt(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 a=o.result.split(",")[1];i({base64:a,mimeType:n})},o.onerror=()=>i(null),o.readAsDataURL(r)})}catch{return null}}function crt(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 jF(t){const{first:e,last:r}=crt(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 a=await lrt(t.avatarUrl);if(a){const m={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[a.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${m}:${a.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),$t.success("Contact saved!")}function urt({card:t}){var M;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),o=((M=t.profile)==null?void 0:M.name)||"Agent",c=o.split(" ").map(D=>D[0]).join("").toUpperCase().slice(0,2),a=(D,F)=>{di(t.id,"button_click",D),F()},f=()=>a("call",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`tel:${t.profile.phone}`:$t.error("Phone number not available")}),m=()=>a("text",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`sms:${t.profile.phone}`:$t.error("Phone number not available")}),y=()=>a("email",()=>{var D;(D=t.profile)!=null&&D.email?window.location.href=`mailto:${t.profile.email}`:$t.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),di(t.id,"button_click","book"))},w=()=>{var D,F;di(t.id,"contact_saved"),jF({name:o,phone:(D=t.profile)==null?void 0:D.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},j=async()=>{di(t.id,"share_event");const D=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:F,url:D})}catch{}else await navigator.clipboard.writeText(D),$t.success("Link copied!")},A=()=>{i("referral"),r(!0),di(t.id,"button_click","refer")},C=()=>{i("connect"),r(!0),di(t.id,"button_click","connect")},I={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs($d,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(zd,{src:t.avatar_url||void 0,alt:o}),s.jsx(Ud,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:c})]}),s.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:o}),t.title&&s.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',t.positioning_statement,'"']})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[s.jsxs(Lt,{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:[s.jsx(Fn,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),s.jsxs(Lt,{onClick:m,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[s.jsx(Ph,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),s.jsxs(Lt,{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:[s.jsx(rs,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),s.jsxs(Lt,{onClick:v,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[s.jsx(bo,{className:"h-5 w-5 mr-2"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(vc,{className:"h-4 w-4 text-amber-500 fill-amber-500"}),s.jsx("span",{className:"font-bold text-slate-900",children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"bg-slate-50 rounded-2xl p-4 mb-6 border border-slate-100",children:s.jsxs("p",{className:"text-sm text-slate-600 italic text-center",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-2",children:"About Me"}),s.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.bio})]}),s.jsx(wF,{card:t,variant:"standard"}),s.jsx(TF,{cardId:t.id,variant:"standard"}),s.jsxs("div",{className:"space-y-2 mb-6",children:[t.show_save_contact&&s.jsxs(Lt,{variant:"ghost",onClick:w,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(yc,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs(Lt,{variant:"ghost",onClick:()=>{di(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(vc,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),t.show_refer_friend&&s.jsxs(Lt,{variant:"ghost",onClick:A,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(kl,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),s.jsxs(Lt,{variant:"ghost",onClick:C,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(T3,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),s.jsxs(Lt,{variant:"ghost",onClick:j,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(NC,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((D,F)=>s.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(t.id,"button_click",`social_${D.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:I[D.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),s.jsx(SF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function drt({card:t}){var M;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),o=((M=t.profile)==null?void 0:M.name)||"Agent",c=o.split(" ").map(D=>D[0]).join("").toUpperCase().slice(0,2),a=(D,F)=>{di(t.id,"button_click",D),F()},f=()=>a("call",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`tel:${t.profile.phone}`:$t.error("Phone number not available")}),m=()=>a("text",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`sms:${t.profile.phone}`:$t.error("Phone number not available")}),y=()=>a("email",()=>{var D;(D=t.profile)!=null&&D.email?window.location.href=`mailto:${t.profile.email}`:$t.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),di(t.id,"button_click","book"))},w=()=>{var D,F;di(t.id,"contact_saved"),jF({name:o,phone:(D=t.profile)==null?void 0:D.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},j=async()=>{di(t.id,"share_event");const D=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:F,url:D})}catch{}else await navigator.clipboard.writeText(D),$t.success("Link copied!")},A=()=>{i("referral"),r(!0),di(t.id,"button_click","refer")},C=()=>{i("connect"),r(!0),di(t.id,"button_click","connect")},I={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs($d,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[s.jsx(zd,{src:t.avatar_url||void 0,alt:o}),s.jsx(Ud,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:c})]}),s.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:o}),t.title&&s.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-[#c9a84c] tracking-widest uppercase mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Fn,label:"Call",handler:f},{icon:Ph,label:"Text",handler:m},{icon:rs,label:"Email",handler:y}].map(({icon:D,label:F,handler:z})=>s.jsxs("button",{onClick:z,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[s.jsx(D,{className:"h-5 w-5 text-[#c9a84c]"}),s.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:F})]},F))}),s.jsxs("button",{onClick:v,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[s.jsx(bo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(vc,{className:"h-4 w-4 text-[#c9a84c] fill-[#c9a84c]"}),s.jsx("span",{className:"font-bold text-white",children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"bg-[#1e2636] rounded-xl p-4 mb-6 border border-[#c9a84c]/10",children:s.jsxs("p",{className:"text-sm text-[#a0aec0] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-[#c9a84c] mb-2 tracking-wide uppercase",children:"About"}),s.jsx("p",{className:"text-sm text-[#a0aec0] leading-relaxed",children:t.bio})]}),s.jsx(wF,{card:t,variant:"luxury"}),s.jsx(TF,{cardId:t.id,variant:"luxury"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:w,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(yc,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{di(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(vc,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:A,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(kl,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),s.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(T3,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),s.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(NC,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((D,F)=>s.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(t.id,"button_click",`social_${D.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:I[D.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),s.jsx(SF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function hrt({card:t}){var F,z,q,H;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),o=((F=t.profile)==null?void 0:F.name)||"Agent",c=o.split(" ").map(K=>K[0]).join("").toUpperCase().slice(0,2),a={accent:((z=t.bold_theme_colors)==null?void 0:z.accent)||"#ff5722",dark:((q=t.bold_theme_colors)==null?void 0:q.dark)||"#1a1a2e",button:((H=t.bold_theme_colors)==null?void 0:H.button)||"#ff5722"},f=(K,J)=>{const Q=parseInt(K.replace("#",""),16),ee=Math.max(0,(Q>>16)-J),oe=Math.max(0,(Q>>8&255)-J),de=Math.max(0,(Q&255)-J);return`#${(ee<<16|oe<<8|de).toString(16).padStart(6,"0")}`};f(a.accent,25),f(a.dark,-20),f(a.button,25);const m=(K,J)=>{di(t.id,"button_click",K),J()},y=()=>m("call",()=>{var K;(K=t.profile)!=null&&K.phone?window.location.href=`tel:${t.profile.phone}`:$t.error("Phone number not available")}),v=()=>m("text",()=>{var K;(K=t.profile)!=null&&K.phone?window.location.href=`sms:${t.profile.phone}`:$t.error("Phone number not available")}),w=()=>m("email",()=>{var K;(K=t.profile)!=null&&K.email?window.location.href=`mailto:${t.profile.email}`:$t.error("Email not available")}),j=()=>{t.booking_url?m("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),di(t.id,"button_click","book"))},A=()=>{var K,J;di(t.id,"contact_saved"),jF({name:o,phone:(K=t.profile)==null?void 0:K.phone,email:(J=t.profile)==null?void 0:J.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},C=async()=>{di(t.id,"share_event");const K=`https://cards.relevelup.com/${t.slug}`,J="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:J,url:K})}catch{}else await navigator.clipboard.writeText(K),$t.success("Link copied!")},I=()=>{i("referral"),r(!0),di(t.id,"button_click","refer")},M=()=>{i("connect"),r(!0),di(t.id,"button_click","connect")},D={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen",style:{backgroundColor:a.accent},children:[s.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:a.dark},children:[t.show_photo&&s.jsxs($d,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${a.accent}`},children:[s.jsx(zd,{src:t.avatar_url||void 0,alt:o}),s.jsx(Ud,{className:"text-2xl font-black text-white",style:{backgroundColor:a.accent},children:c})]}),s.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:o}),t.title&&s.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${a.accent}cc`},children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-bold uppercase tracking-wider mb-1",style:{color:a.accent},children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:t.team_name})]}),s.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[s.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[t.positioning_statement&&s.jsx("p",{className:"text-center font-bold text-lg leading-snug mb-6 max-w-xs mx-auto",style:{color:a.dark},children:t.positioning_statement}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Fn,label:"Call",handler:y},{icon:Ph,label:"Text",handler:v},{icon:rs,label:"Email",handler:w}].map(({icon:K,label:J,handler:Q})=>s.jsxs("button",{onClick:Q,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:a.dark},children:[s.jsx(K,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs",children:J})]},J))}),s.jsxs("button",{onClick:j,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:a.button},children:[s.jsx(bo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:t.review_snippet&&s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(vc,{className:"h-5 w-5",style:{color:a.accent,fill:a.accent}}),s.jsx("span",{className:"font-black text-2xl",style:{color:a.dark},children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"rounded-2xl p-4 mb-6",style:{backgroundColor:`${a.accent}15`},children:s.jsxs("p",{className:"text-sm font-medium text-center",style:{color:a.dark},children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-xs font-black mb-2 uppercase tracking-wider",style:{color:a.accent},children:"About Me"}),s.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:t.bio})]}),s.jsx(wF,{card:t,variant:"bold"}),s.jsx(TF,{cardId:t.id,variant:"bold"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:A,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:a.dark},children:[s.jsx(yc,{className:"h-4 w-4",style:{color:a.accent}})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{di(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:a.dark},children:[s.jsx(vc,{className:"h-4 w-4",style:{color:a.accent}})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:I,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:a.dark},children:[s.jsx(kl,{className:"h-4 w-4",style:{color:a.accent}})," Refer a Friend"]}),s.jsxs("button",{onClick:M,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:a.dark},children:[s.jsx(T3,{className:"h-4 w-4",style:{color:a.accent}})," Connect with Me"]}),s.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(NC,{className:"h-4 w-4",style:{color:a.accent}})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-6",children:t.social_links.slice(0,3).map((K,J)=>s.jsx("a",{href:K.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(t.id,"button_click",`social_${K.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:a.dark},children:D[K.platform.toLowerCase()]||"🔗"},J))})]}),s.jsx("div",{className:"text-center py-6",children:s.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),s.jsx(SF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function frt({card:t}){var M;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),o=((M=t.profile)==null?void 0:M.name)||"Agent",c=o.split(" ").map(D=>D[0]).join("").toUpperCase().slice(0,2),a=(D,F)=>{di(t.id,"button_click",D),F()},f=()=>a("call",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`tel:${t.profile.phone}`:$t.error("Phone number not available")}),m=()=>a("text",()=>{var D;(D=t.profile)!=null&&D.phone?window.location.href=`sms:${t.profile.phone}`:$t.error("Phone number not available")}),y=()=>a("email",()=>{var D;(D=t.profile)!=null&&D.email?window.location.href=`mailto:${t.profile.email}`:$t.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),di(t.id,"button_click","book"))},w=()=>{var D,F;di(t.id,"contact_saved"),jF({name:o,phone:(D=t.profile)==null?void 0:D.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},j=async()=>{di(t.id,"share_event");const D=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:F,url:D})}catch{}else await navigator.clipboard.writeText(D),$t.success("Link copied!")},A=()=>{i("referral"),r(!0),di(t.id,"button_click","refer")},C=()=>{i("connect"),r(!0),di(t.id,"button_click","connect")},I={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[s.jsx("div",{className:"bg-[#1b3a4b] h-2"}),s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs($d,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(zd,{src:t.avatar_url||void 0,alt:o}),s.jsx(Ud,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:c})]}),s.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:o}),t.title&&s.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Fn,label:"Call",handler:f},{icon:Ph,label:"Text",handler:m},{icon:rs,label:"Email",handler:y}].map(({icon:D,label:F,handler:z})=>s.jsxs("button",{onClick:z,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[s.jsx(D,{className:"h-5 w-5 text-[#1b3a4b]"}),s.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:F})]},F))}),s.jsxs("button",{onClick:v,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[s.jsx(bo,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:s.jsx("div",{className:"flex items-center justify-center gap-6",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(vc,{className:"h-4 w-4 text-[#d4a843] fill-[#d4a843]"}),s.jsx("span",{className:"font-bold text-[#1b3a4b] font-serif",children:"5.0"})]})})}),t.review_snippet&&s.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:s.jsxs("p",{className:"text-sm text-[#4a5568] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-[#1b3a4b] mb-2 font-serif",children:"About"}),s.jsx("p",{className:"text-sm text-[#4a5568] leading-relaxed",children:t.bio})]}),s.jsx(wF,{card:t,variant:"classic"}),s.jsx(TF,{cardId:t.id,variant:"classic"}),s.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:w,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(yc,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{di(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(vc,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:A,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(kl,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),s.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(T3,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),s.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(NC,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((D,F)=>s.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>di(t.id,"button_click",`social_${D.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:I[D.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),s.jsx(SF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function mrt({card:t}){switch(t.theme){case"luxury":return s.jsx(drt,{card:t});case"bold":return s.jsx(hrt,{card:t});case"classic":return s.jsx(frt,{card:t});case"standard":default:return s.jsx(urt,{card:t})}}function prt(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 grt(t){return`https://docs.google.com/gview?url=${encodeURIComponent(t)}&embedded=true`}function yrt(){if(typeof window>"u")return null;const t=prt(new URLSearchParams(window.location.search).get("oh_disclosure"));return t?s.jsx("div",{className:"sticky top-0 z-50 bg-primary text-primary-foreground shadow-md",children:s.jsxs("div",{className:"mx-auto flex max-w-md items-center justify-between gap-3 px-4 py-2.5",children:[s.jsx("span",{className:"text-sm font-medium",children:"Thanks for visiting the open house!"}),s.jsxs("a",{href:grt(t),target:"_blank",rel:"noopener noreferrer",className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-background px-3 py-1.5 text-xs font-semibold text-foreground",children:[s.jsx(Qm,{className:"h-3.5 w-3.5"})," See Disclosures"]})]})}):null}function xrt(){const t=xs();N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),s.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):s.jsx(vrt,{slug:e})}function vrt({slug:t}){return s.jsx(_rt,{slug:t})}function _rt({slug:t}){var o;const{data:e,isLoading:r,error:n}=Gtt(t);if(N.useEffect(()=>{e!=null&&e.id&&di(e.id,"card_view")},[e==null?void 0:e.id]),r)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:s.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[s.jsxs("div",{className:"flex flex-col items-center gap-4",children:[s.jsx(Al,{className:"h-28 w-28 rounded-full"}),s.jsx(Al,{className:"h-6 w-48"}),s.jsx(Al,{className:"h-4 w-36"})]}),s.jsx(Al,{className:"h-12 w-full"}),s.jsx(Al,{className:"h-12 w-full"})]})});if(n||!e)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const i=((o=e.profile)==null?void 0:o.name)||"Agent";return s.jsxs(s.Fragment,{children:[s.jsxs(no,{children:[s.jsxs("title",{children:[i," | Real Estate Agent"]}),s.jsx("meta",{name:"description",content:e.positioning_statement||`Connect with ${i}, your trusted real estate professional.`}),s.jsx("meta",{property:"og:title",content:`${i} | Real Estate Agent`}),s.jsx("meta",{property:"og:description",content:e.positioning_statement||`Connect with ${i}`}),e.avatar_url&&s.jsx("meta",{property:"og:image",content:e.avatar_url})]}),s.jsx(yrt,{}),s.jsx(mrt,{card:e})]})}function brt({presentationId:t,ctaLabel:e,agentName:r,prefillName:n,prefillEmail:i,prefillPhone:o}){const[c,a]=N.useState(n||""),[f,m]=N.useState(i||""),[y,v]=N.useState(o||""),[w,j]=N.useState(""),[A,C]=N.useState(""),[I,M]=N.useState(!1),[D,F]=N.useState(!1),z=async q=>{if(q.preventDefault(),!c.trim()){$t.error("Please enter your name");return}M(!0);try{const{error:H}=await Ce.from("smart_presentation_leads").insert({presentation_id:t,name:c.trim(),email:f.trim()||null,phone:y.trim()||null,intent:w||null,message:A.trim()||null});if(H)throw H;try{await Ce.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{}Ce.functions.invoke("presentation-lead-notify",{body:{presentationId:t,name:c.trim(),email:f.trim()||void 0,phone:y.trim()||void 0,intent:w||void 0,message:A.trim()||void 0}}).catch(K=>console.error("Presentation lead notify failed:",K)),F(!0)}catch{$t.error("Something went wrong. Please try again.")}finally{M(!1)}};return D?s.jsxs("div",{className:"text-center py-8",children:[s.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:s.jsx(pa,{className:"h-8 w-8 text-emerald-600"})}),s.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),s.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):s.jsxs("form",{onSubmit:z,className:"space-y-4 max-w-md mx-auto",children:[s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"pres-lead-name",children:"Name *"}),s.jsx(Or,{id:"pres-lead-name",value:c,onChange:q=>a(q.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"pres-lead-phone",children:"Phone"}),s.jsx(Or,{id:"pres-lead-phone",type:"tel",value:y,onChange:q=>v(q.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"pres-lead-email",children:"Email"}),s.jsx(Or,{id:"pres-lead-email",type:"email",value:f,onChange:q=>m(q.target.value),placeholder:"you@example.com"})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),s.jsxs(Pa,{value:w,onValueChange:j,children:[s.jsx(va,{children:s.jsx(Ra,{placeholder:"Select one"})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"buy",children:"Buy a home"}),s.jsx(gn,{value:"sell",children:"Sell my home"}),s.jsx(gn,{value:"both",children:"Buy & Sell"}),s.jsx(gn,{value:"other",children:"Something else"})]})]})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"pres-lead-message",children:"Message (optional)"}),s.jsx(Or,{id:"pres-lead-message",value:A,onChange:q=>C(q.target.value),placeholder:"Anything you'd like us to know"})]}),s.jsx(Lt,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:I,children:I?"Sending...":e})]})}function wrt(){const t=xs();N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),s.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):s.jsx(Srt,{shareToken:e})}function Srt({shareToken:t}){var A;const[e,r]=N.useState(null),[n,i]=N.useState(!0),[o,c]=N.useState(0),[a,f]=N.useState(!1);N.useEffect(()=>{m()},[t]);const m=async()=>{const{data:C,error:I}=await Ce.from("smart_presentations").select("*").eq("share_token",t).eq("status","published").single();if(I||!C){f(!0),i(!1);return}const{data:M}=await Ce.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",C.owner_user_id).single();let D;if(M!=null&&M.brokerage_id){const{data:z}=await Ce.from("brokerages").select("name").eq("id",M.brokerage_id).single();D=(z==null?void 0:z.name)||void 0}let F=null;if(C.contact_id){const{data:z}=await Ce.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",C.contact_id).single();F=z}r({...C,owner_name:M==null?void 0:M.name,owner_email:M==null?void 0:M.email,owner_phone:M==null?void 0:M.phone,owner_avatar:M==null?void 0:M.avatar_url,owner_title:(M==null?void 0:M.title)||void 0,brokerage_name:D,contact_name:F?[F.first_name,F.last_name].filter(Boolean).join(" "):void 0,contact_email:(F==null?void 0:F.email)||void 0,contact_phone:(F==null?void 0:F.phone)||void 0}),i(!1);try{await Ce.rpc("log_presentation_view",{p_presentation_id:C.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 Ce.rpc("log_presentation_view",{p_presentation_id:e.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}e.cta_url&&window.open(e.cta_url,"_blank")}},v=C=>{const I=C.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(I)return`https://www.youtube.com/embed/${I[1]}?rel=0`;if(C.includes("iframe.mediadelivery.net/play/")){const F=C.replace("/play/","/embed/"),z=F.includes("?")?"&":"?";return`${F}${z}responsive=true`}if(C.includes("iframe.mediadelivery.net")){const F=C.includes("?")?"&":"?";return`${C}${F}responsive=true`}const M=C.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(M)return`https://www.loom.com/embed/${M[1]}`;const D=C.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return D?`https://iframe.mediadelivery.net/embed/${D[1]}/${D[2]}?responsive=true`:C};if(n)return s.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:s.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[s.jsx(Al,{className:"h-12 w-3/4 mx-auto"}),s.jsx(Al,{className:"h-64 w-full"}),s.jsx(Al,{className:"h-8 w-1/2 mx-auto"})]})});if(a||!e)return s.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),s.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const w=e.sections.filter(C=>C.is_visible!==!1),j=w[o];return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[s.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:s.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:s.jsxs("div",{className:"flex items-center gap-3",children:[e.owner_avatar&&s.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),s.jsxs("div",{className:"text-right text-sm",children:[s.jsx("p",{className:"font-semibold text-gray-900",children:e.owner_name}),e.owner_title&&s.jsx("p",{className:"text-gray-500 text-xs",children:e.owner_title}),e.brokerage_name&&!e.owner_title&&s.jsx("p",{className:"text-gray-500 text-xs",children:e.brokerage_name})]})]})})}),s.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[s.jsxs("div",{className:"text-center mb-8",children:[s.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:e.heading||(e.client_name?`Welcome, ${e.client_name}!`:e.title)}),e.property_address&&s.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",s.jsx("strong",{children:e.property_address}),"."]})]}),s.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[s.jsxs("div",{className:"md:col-span-3",children:[j!=null&&j.video_url?s.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:s.jsx("iframe",{src:v(j.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"})}):j!=null&&j.image_url?s.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:s.jsx("img",{src:j.image_url,alt:j.title,className:"w-full h-auto object-cover",loading:"lazy"})}):s.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[s.jsx("span",{className:"text-5xl mb-3",children:j==null?void 0:j.icon}),s.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:j==null?void 0:j.title}),s.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:j==null?void 0:j.description})]}),(j==null?void 0:j.text)&&s.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:j.text}})]}),s.jsx("div",{className:"md:col-span-2 space-y-3",children:w.map((C,I)=>s.jsx("button",{onClick:()=>c(I),className:Xt("w-full text-left p-4 rounded-xl border transition-all",o===I?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(I+1).padStart(2,"0"),"."]}),s.jsxs("div",{children:[s.jsx("span",{className:"mr-2",children:C.icon}),s.jsx("span",{className:"font-semibold text-gray-900",children:C.title}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:C.description})]})]})},I))})]}),s.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[e.owner_avatar&&s.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),s.jsx("h3",{className:"text-lg font-bold text-gray-900",children:e.owner_name}),e.owner_title&&s.jsx("p",{className:"text-sm text-gray-500",children:e.owner_title}),e.brokerage_name&&s.jsx("p",{className:"text-sm text-gray-500",children:e.brokerage_name}),s.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[e.owner_phone&&s.jsx("a",{href:`tel:${e.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:e.owner_phone}),e.owner_email&&s.jsx("a",{href:`mailto:${e.owner_email}`,className:"hover:text-blue-600 transition-colors",children:e.owner_email})]})]}),e.cta_label&&s.jsxs("div",{className:"text-center mt-8 py-8",children:[s.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(A=e.cta_url)!=null&&A.trim()?s.jsxs(Lt,{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,s.jsx(mb,{className:"h-5 w-5 ml-2"})]}):s.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:s.jsx(brt,{presentationId:e.id,ctaLabel:e.cta_label,agentName:e.owner_name||void 0,prefillName:e.contact_name,prefillEmail:e.contact_email,prefillPhone:e.contact_phone})})]})]}),s.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})}function Ttr(){const{user:t}=Zn(),e=zs(),{data:r}=dj();return mr({queryKey:["open-houses",e,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:i}=await Ce.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:a}=await Ce.rpc("get_team_open_houses",{_user_id:e});if(!a&&c){const f=[...new Set(c.map(v=>v.agent_id))],m={};if(f.length>0){const{data:v}=await Ce.from("profiles").select("id, name").in("id",f);v==null||v.forEach(w=>{w.name&&(m[w.id]=w.name)})}const y=c.map(v=>({...v,agent_name:m[v.agent_id]||void 0}));o=[...o,...y]}}return o.sort((c,a)=>a.event_date.localeCompare(c.event_date)),o},enabled:!!t&&!!e})}function jtr(t){const{user:e}=Zn();return mr({queryKey:["open-house",t],queryFn:async()=>{const{data:r,error:n}=await Ce.from("open_houses").select("*").eq("id",t).single();if(n)throw n;return r},enabled:!!e&&!!t})}function Etr(t){const{user:e}=Zn(),r=kr();return N.useEffect(()=>{if(!t)return;const n=`visitors-${t}-${Math.random().toString(36).slice(2,10)}`,i=Ce.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()=>{Ce.removeChannel(i)}},[t,r]),mr({queryKey:["open-house-visitors",t],queryFn:async()=>{const{data:n,error:i}=await Ce.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 ktr(){const t=kr(),e=zs();return Ar({mutationFn:async r=>{const{data:n,error:i}=await Ce.from("open_houses").insert({...r,agent_id:e}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Fi({title:"Open house created!"})},onError:r=>{Fi({title:"Error",description:r.message,variant:"destructive"})}})}function Atr(){const t=kr();return Ar({mutationFn:async({id:e,...r})=>{const{error:n}=await Ce.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 Ntr(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await Ce.from("open_houses").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Fi({title:"Open house deleted"})}})}function lSe(t){return mr({queryKey:["public-open-house",t],queryFn:async()=>{const{data:e,error:r}=await Ce.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 Ce.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 Ctr(t){const{user:e}=Zn();return mr({queryKey:["survey-questions",t],queryFn:async()=>{const{data:r,error:n}=await Ce.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;return r},enabled:!!e&&!!t})}function Trt(t){return mr({queryKey:["public-survey-questions",t],queryFn:async()=>{const{data:e,error:r}=await Ce.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 jrt(){return Ar({mutationFn:async t=>{const{error:e}=await Ce.from("open_house_survey_responses").insert(t);if(e)throw e}})}function Itr(t){const{user:e}=Zn();return mr({queryKey:["survey-responses",t],queryFn:async()=>{const{data:r,error:n}=await Ce.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;const i=(r||[]).map(a=>a.id);if(i.length===0)return{questions:[],responses:[]};const{data:o,error:c}=await Ce.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 Ptr(){const t=kr();return Ar({mutationFn:async e=>{const{data:r,error:n}=await Ce.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 Rtr(){const t=kr();return Ar({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Ce.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 Ltr(){const t=kr();return Ar({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Ce.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 Mtr(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await Ce.rpc("seed_default_survey_questions",{_open_house_id:e});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r]})}})}function Ert(){return Ar({mutationFn:async t=>{const e=crypto.randomUUID(),{error:r}=await Ce.from("open_house_visitors").insert({...t,id:e});if(r)throw r;return{id:e}}})}function krt(){return Ar({mutationFn:async({visitor_id:t,...e})=>{const{error:r}=await Ce.from("open_house_visitors").update(e).eq("id",t);if(r)throw r}})}function Art(){return Ar({mutationFn:async t=>{await Ce.rpc("increment_open_house_scan",{_slug:t})}})}async function cSe(t){const{data:e,error:r}=await Ce.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 Ce.from("open_house_room_media").select("*").in("room_id",i).order("sort_order");if(c)throw c;const a={};return(o||[]).forEach(f=>{var y;const m=f;(a[y=m.room_id]||(a[y]=[])).push(m)}),n.map(f=>({...f,media:a[f.id]||[]}))}function Dtr(t){const{user:e}=Zn();return mr({queryKey:["open-house-rooms",t],queryFn:()=>cSe(t),enabled:!!e&&!!t})}function Nrt(t){return mr({queryKey:["public-open-house-rooms",t],queryFn:()=>cSe(t),enabled:!!t})}function Otr(){const t=kr();return Ar({mutationFn:async e=>{const{data:r,error:n}=await Ce.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 Ftr(){const t=kr();return Ar({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Ce.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 Btr(){const t=kr();return Ar({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Ce.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 $tr(){const t=kr();return Ar({mutationFn:async({open_house_id:e,...r})=>{const{data:n,error:i}=await Ce.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 ztr(){const t=kr();return Ar({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Ce.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 Utr(){const t=kr();return Ar({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(a=>[a.id,a])),c=r.map((a,f)=>({...o.get(a),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 Vtr(){const t=kr();return Ar({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 a=new Map(c.media.map(f=>[f.id,f]));return{...c,media:n.map((f,m)=>{const y=a.get(f);return y?{...y,sort_order:m}: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 qtr(t){const{user:e}=Zn();return mr({queryKey:["open-house-leads",t],queryFn:async()=>{const{data:r,error:n}=await Ce.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 Gtr(){const t=kr();return Ar({mutationFn:async({id:e,status:r,open_house_id:n})=>{const{error:i}=await Ce.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 EF="Switch",[Crt,Htr]=dl(EF),[Irt,Prt]=Crt(EF),uSe=N.forwardRef((t,e)=>{const{__scopeSwitch:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:f="on",onCheckedChange:m,form:y,...v}=t,[w,j]=N.useState(null),A=is(e,F=>j(F)),C=N.useRef(!1),I=w?y||!!w.closest("form"):!0,[M,D]=rd({prop:i,defaultProp:o??!1,onChange:m,caller:EF});return s.jsxs(Irt,{scope:r,checked:M,disabled:a,children:[s.jsx(cn.button,{type:"button",role:"switch","aria-checked":M,"aria-required":c,"data-state":mSe(M),"data-disabled":a?"":void 0,disabled:a,value:f,...v,ref:A,onClick:Gr(t.onClick,F=>{D(z=>!z),I&&(C.current=F.isPropagationStopped(),C.current||F.stopPropagation())})}),I&&s.jsx(fSe,{control:w,bubbles:!C.current,name:n,value:f,checked:M,required:c,disabled:a,form:y,style:{transform:"translateX(-100%)"}})]})});uSe.displayName=EF;var dSe="SwitchThumb",hSe=N.forwardRef((t,e)=>{const{__scopeSwitch:r,...n}=t,i=Prt(dSe,r);return s.jsx(cn.span,{"data-state":mSe(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e})});hSe.displayName=dSe;var Rrt="SwitchBubbleInput",fSe=N.forwardRef(({__scopeSwitch:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=N.useRef(null),a=is(c,o),f=KC(r),m=OC(e);return N.useEffect(()=>{const y=c.current;if(!y)return;const v=window.HTMLInputElement.prototype,j=Object.getOwnPropertyDescriptor(v,"checked").set;if(f!==r&&j){const A=new Event("click",{bubbles:n});j.call(y,r),y.dispatchEvent(A)}},[f,r,n]),s.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...m,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});fSe.displayName=Rrt;function mSe(t){return t?"checked":"unchecked"}var pSe=uSe,Lrt=hSe;const gj=N.forwardRef(({className:t,...e},r)=>s.jsx(pSe,{className:Xt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",t),...e,ref:r,children:s.jsx(Lrt,{className:Xt("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")})}));gj.displayName=pSe.displayName;const Mrt=["Excellent","Good","Neutral","Bad","Very Bad"],Drt=[5,4,3,2,1];function Ort({questions:t,visitorId:e,onComplete:r,onSkip:n}){const i=jrt(),[o,c]=N.useState({}),a=t.filter(w=>w.question_type==="rating"),f=t.filter(w=>w.question_type!=="rating"),m=(w,j)=>{c(A=>({...A,[w]:{rating_value:j}}))},y=(w,j)=>{c(A=>({...A,[w]:{text_value:j}}))},v=async()=>{const w=Object.entries(o).filter(([,j])=>j.rating_value!=null||j.text_value&&j.text_value.trim()).map(([j,A])=>{var C;return{visitor_id:e,question_id:j,rating_value:A.rating_value??null,text_value:((C=A.text_value)==null?void 0:C.trim())||null}});if(w.length>0)try{await i.mutateAsync(w)}catch{}r()};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),s.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),s.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),a.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("div",{className:"flex-1"}),Mrt.map(w=>s.jsx("div",{className:"w-12 text-center",children:s.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:w})},w))]}),a.map(w=>s.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[s.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:w.question_text}),Drt.map(j=>{var A;return s.jsx("div",{className:"w-12 flex justify-center",children:s.jsx("button",{type:"button",onClick:()=>m(w.id,j),className:`w-6 h-6 rounded-full border-2 transition-all ${((A=o[w.id])==null?void 0:A.rating_value)===j?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},j)})]},w.id))]}),f.map(w=>{var j;return s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:w.question_text}),s.jsx(qc,{value:((j=o[w.id])==null?void 0:j.text_value)||"",onChange:A=>y(w.id,A.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},w.id)}),s.jsx(Lt,{onClick:v,disabled:i.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:i.isPending?s.jsx(zc,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function Yq(t){return/iframe\.mediadelivery\.net\/embed\//.test(t)}function Frt({rooms:t}){var C;const[e,r]=N.useState(((C=t[0])==null?void 0:C.id)||""),[n,i]=N.useState(null),[o,c]=N.useState(null),a=N.useRef({}),f=t.find(I=>I.id===n)||t[0],m=o!==null?f==null?void 0:f.media[o]:null,y=(f==null?void 0:f.media.length)??0,v=()=>{c(null),i(null)},w=()=>c(I=>I===null||y===0?I:(I-1+y)%y),j=()=>c(I=>I===null||y===0?I:(I+1)%y);N.useEffect(()=>{if(o===null)return;const I=M=>{M.key==="Escape"?v():M.key==="ArrowLeft"?w():M.key==="ArrowRight"&&j()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[o,y]),N.useEffect(()=>{const I=new IntersectionObserver(M=>{const D=M.filter(F=>F.isIntersecting).sort((F,z)=>F.boundingClientRect.top-z.boundingClientRect.top);D[0]&&r(D[0].target.dataset.roomId||"")},{rootMargin:"-90px 0px -55% 0px"});return Object.values(a.current).forEach(M=>M&&I.observe(M)),()=>I.disconnect()},[t]);const A=I=>{r(I);const M=a.current[I];M&&window.scrollTo({top:M.getBoundingClientRect().top+window.scrollY-80,behavior:"smooth"})};return t.length?s.jsxs("div",{className:"hidden md:block",children:[s.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:s.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(I=>s.jsxs("button",{onClick:()=>A(I.id),className:Xt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",e===I.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[I.name,s.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:I.media.length})]},I.id))})}),t.map(I=>s.jsxs("section",{"data-room-id":I.id,ref:M=>{a.current[I.id]=M},className:"mt-10 first:mt-6",children:[s.jsx("h3",{className:"text-2xl font-bold",children:I.name}),I.description&&s.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:I.description}),I.media.length===0?s.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):s.jsx("div",{className:"mt-5 grid grid-cols-2 gap-4",children:I.media.map((M,D)=>s.jsx("button",{onClick:()=>{i(I.id),c(D)},className:Xt("relative aspect-[3/2] rounded-xl overflow-hidden bg-white/5 group",D===0&&I.media.length!==2&&"col-span-2 aspect-[16/9]"),children:M.kind==="video"?s.jsxs(s.Fragment,{children:[Yq(M.url)?s.jsx("div",{className:"absolute inset-0 bg-slate-900"}):s.jsx("video",{src:M.url,className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:s.jsx("div",{className:"w-14 h-14 rounded-full bg-white/90 flex items-center justify-center",children:s.jsx(dA,{className:"h-6 w-6 text-slate-900"})})})]}):s.jsx("img",{src:M.url,alt:I.name,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-[1.03] transition-transform duration-500"})},M.id))})]},I.id)),m&&f&&s.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:v,children:[s.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[f.name," — ",(o??0)+1," / ",y]}),s.jsx("button",{onClick:I=>{I.stopPropagation(),v()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),y>1&&s.jsx("button",{onClick:I=>{I.stopPropagation(),w()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:s.jsx(lp,{className:"h-6 w-6"})}),m.kind==="video"?Yq(m.url)?s.jsx("iframe",{src:`${m.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:I=>I.stopPropagation()},m.url):s.jsx("video",{src:m.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:I=>I.stopPropagation()},m.url):s.jsx("img",{src:m.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:I=>I.stopPropagation()}),y>1&&s.jsx("button",{onClick:I=>{I.stopPropagation(),j()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:s.jsx(Wd,{className:"h-6 w-6"})})]})]}):null}function Brt({rooms:t}){var a;const e=[];t.forEach(f=>{e.push({type:"cover",roomId:f.id,roomName:f.name,description:f.description,mediaCount:f.media.length}),f.media.forEach((m,y)=>{e.push({type:"media",roomId:f.id,roomName:f.name,url:m.url,kind:m.kind,index:y,total:f.media.length})})});const r=N.useRef(null),[n,i]=N.useState(0);N.useEffect(()=>{const f=r.current;if(!f)return;let m=0;const y=()=>{cancelAnimationFrame(m),m=requestAnimationFrame(()=>{const v=Math.round(f.scrollLeft/f.clientWidth);i(v)})};return f.addEventListener("scroll",y,{passive:!0}),()=>{f.removeEventListener("scroll",y),cancelAnimationFrame(m)}},[]);const o=f=>{const m=r.current;m&&m.scrollTo({left:f*m.clientWidth,behavior:"smooth"})};if(!e.length)return null;const c=(a=e[n])==null?void 0:a.roomId;return s.jsxs("div",{className:"md:hidden -mx-5",children:[s.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:s.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(f=>{const m=e.findIndex(v=>v.roomId===f.id),y=c===f.id;return s.jsx("button",{onClick:()=>o(m),className:Xt("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)})})}),s.jsx("div",{ref:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:e.map((f,m)=>s.jsx("div",{className:"shrink-0 w-screen snap-center",children:s.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[f.type==="cover"?s.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),s.jsx("h3",{className:"text-3xl font-bold",children:f.roomName}),f.description&&s.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:f.description}),s.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[f.mediaCount," ",f.mediaCount===1?"item":"items"," — swipe to view →"]})]}):f.kind==="video"?Yq(f.url)?s.jsx("iframe",{src:f.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):s.jsx("video",{src:f.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.jsx("img",{src:f.url,alt:f.roomName,className:"w-full h-full object-cover"}),f.type==="media"&&s.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[s.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:f.roomName}),s.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[f.index+1," / ",f.total]})]})]})},m))}),s.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[s.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:[s.jsx(lp,{className:"h-4 w-4"})," Prev"]}),s.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",e.length]}),s.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 ",s.jsx(Wd,{className:"h-4 w-4"})]})]})]})}const F6={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ph},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:bo},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Qm},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:_g}},$rt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function zrt(t){return t==null||t<=0?null:`$${t.toLocaleString("en-US")}`}function Urt({openHouse:t,visitorId:e,visitorName:r,visitorEmail:n,visitorPhone:i,previewMode:o=!1}){var Vt;const c=t.profiles,a=((Vt=c==null?void 0:c.name)==null?void 0:Vt.split(" ").map(xt=>xt[0]).join("").slice(0,2))||"?",f=t.brand_color_override||null,[m,y]=N.useState(null),[v,w]=N.useState(""),[j,A]=N.useState(n||""),[C,I]=N.useState(i||""),[M,D]=N.useState(!1),[F,z]=N.useState(null),[q,H]=N.useState(""),[K,J]=N.useState(""),[Q,ee]=N.useState(""),[oe,de]=N.useState([]),[ye,we]=N.useState(""),[Le,Se]=N.useState(""),[ve,me]=N.useState(""),[ke,Pe]=N.useState(""),Ee=zrt(t.price),xe=t.tour_mode==="rooms",{data:Ue=[]}=Nrt(xe?t.id:void 0),Ze=[t.enable_question&&"question",t.enable_showing&&"showing",t.enable_disclosures&&"disclosure",t.enable_offer&&"offer"].filter(Boolean),lt=xt=>{y(xt),w(""),H(""),J(""),ee(""),de([]),we(""),Se(""),me(""),Pe("")},wt=()=>{y(null)},yt=xt=>{de(or=>or.includes(xt)?or.filter(Tr=>Tr!==xt):[...or,xt])},gt=xt=>xt==="showing"?{preferred_date:q||null,preferred_time:K||null,alternate_date:Q||null}:xt==="disclosure"?{requested_documents:oe}:xt==="offer"?{offer_amount:ye||null,financing:Le||null,timeline:ve||null,pre_approved:ke||null}:{},ft=m?m==="showing"?!!q:m==="question"?v.trim().length>0:!0:!1,kt=async()=>{if(m){if(o){Fi({title:"Preview mode",description:"Lead not sent — this is just a preview."}),z(m),setTimeout(()=>{y(null),z(null)},1500);return}D(!0);try{const xt=gt(m),{error:or}=await Ce.from("open_house_leads").insert({open_house_id:t.id,visitor_id:e,action_type:m,payload:{message:v.trim()||null,email:j.trim()||null,phone:C.trim()||null,visitor_name:r,...xt}});if(or)throw or;Ce.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:t.id,visitor_id:e,action_type:m,message:v.trim()||null,visitor_name:r,visitor_email:j.trim()||null,visitor_phone:C.trim()||null,extras:xt}}).catch(()=>{}),z(m),Fi({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{wt(),z(null)},1400)}catch(xt){Fi({title:"Something went wrong",description:xt.message,variant:"destructive"})}finally{D(!1)}}};return s.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[s.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[t.hero_video_url?s.jsx("video",{src:t.hero_video_url,poster:t.hero_video_thumbnail_url||t.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):t.photo_url?s.jsx("img",{src:t.photo_url,alt:t.property_address,className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),s.jsxs("div",{className:"max-w-5xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[s.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[s.jsx("h1",{className:"text-2xl font-bold leading-tight",children:t.property_address}),t.city&&s.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[s.jsx(ii,{className:"h-3.5 w-3.5"}),t.city,t.state?`, ${t.state}`:""," ",t.zip]}),Ee&&s.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:Ee}),s.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[t.beds!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ZT,{className:"h-4 w-4"}),t.beds," bd"]}),t.baths!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(m0,{className:"h-4 w-4"}),t.baths," ba"]}),t.sqft!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(OH,{className:"h-4 w-4"}),t.sqft.toLocaleString()," sqft"]})]}),t.property_description?s.jsx("p",{className:"text-white/80 text-sm mt-5 whitespace-pre-wrap leading-relaxed",children:t.property_description}):t.agent_greeting&&s.jsxs("p",{className:"text-white/70 text-sm mt-5 border-l-2 border-white/20 pl-3 italic",children:['"',t.agent_greeting,'"']})]}),c&&s.jsxs("div",{className:"mt-5 flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl p-4",children:[t.team_photo_url?s.jsx("img",{src:t.team_photo_url,alt:c.name||"Team",className:"h-16 w-24 shrink-0 rounded-lg object-cover ring-2 ring-white/20"}):s.jsxs(s.Fragment,{children:[s.jsxs($d,{className:"h-12 w-12 ring-2 ring-white/20",style:f?{boxShadow:`0 0 0 2px ${f}`}:void 0,children:[s.jsx(zd,{src:c.avatar_url||"",alt:c.name||""}),s.jsx(Ud,{className:"bg-white/10 text-white",children:a})]}),t.co_host_name&&s.jsxs($d,{className:"h-12 w-12 -ml-6 ring-2 ring-slate-950",children:[s.jsx(zd,{src:t.co_host_photo_url||"",alt:t.co_host_name}),s.jsx(Ud,{className:"bg-white/10 text-white",children:String(t.co_host_name).split(" ").map(xt=>xt[0]).join("").slice(0,2)})]})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("p",{className:"font-semibold text-white truncate",children:[c.name,t.co_host_name?` & ${t.co_host_name}`:""]}),(t.brokerage_display_name||c.title)&&s.jsx("p",{className:"text-xs text-white/60 truncate",children:[!t.co_host_name&&c.title,t.brokerage_display_name].filter(Boolean).join(" · ")})]}),(c.phone||c.email)&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.phone&&s.jsx("a",{href:`tel:${c.phone}`,"aria-label":`Call ${c.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:f?{backgroundColor:`${f}33`,color:"white"}:void 0,children:s.jsx(Fn,{className:"h-4 w-4"})}),c.email&&s.jsx("a",{href:`mailto:${c.email}`,"aria-label":`Email ${c.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:f?{backgroundColor:`${f}33`,color:"white"}:void 0,children:s.jsx(rs,{className:"h-4 w-4"})})]})]}),xe&&Ue.length>0&&s.jsxs("div",{className:"mt-8",children:[s.jsx(Frt,{rooms:Ue}),s.jsx(Brt,{rooms:Ue})]}),Ze.length>0&&s.jsxs("div",{className:"mt-10 pt-6 border-t border-white/10",children:[s.jsx("p",{className:"text-xs uppercase tracking-wider text-white/40 mb-3",children:"Interested in this home?"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:Ze.map(xt=>{const or=F6[xt],Tr=or.icon;return s.jsxs("button",{onClick:()=>lt(xt),className:"flex items-center gap-2 px-4 py-2.5 rounded-full border border-white/15 bg-white/5 text-white/90 hover:bg-white/10 hover:border-white/30 transition-colors text-sm",children:[s.jsx(Tr,{className:"h-4 w-4",style:f?{color:f}:void 0}),s.jsx("span",{className:"font-medium",children:or.label})]},xt)})})]}),s.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),s.jsx(R_e,{open:!!m,onOpenChange:xt=>!xt&&wt(),children:s.jsx(RW,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:m&&s.jsxs(s.Fragment,{children:[s.jsxs(M_e,{className:"text-left",children:[s.jsx(D_e,{children:F6[m].title}),s.jsxs(O_e,{children:[(c==null?void 0:c.name)||"The agent"," will be notified by email."]})]}),F===m?s.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:s.jsx(Il,{className:"h-7 w-7 text-green-600"})}),s.jsx("p",{className:"font-medium",children:"Message sent!"})]}):s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Email"}),s.jsx(Or,{type:"email",value:j,onChange:xt=>A(xt.target.value),placeholder:"you@example.com",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Phone"}),s.jsx(Or,{type:"tel",value:C,onChange:xt=>I(xt.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),m==="showing"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Preferred date *"}),s.jsx(Or,{type:"date",value:q,onChange:xt=>H(xt.target.value),className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Preferred time"}),s.jsx(Or,{type:"time",value:K,onChange:xt=>J(xt.target.value),className:"mt-1"})]})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Alternate date (optional)"}),s.jsx(Or,{type:"date",value:Q,onChange:xt=>ee(xt.target.value),className:"mt-1"})]})]}),m==="disclosure"&&s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Which documents? (select all that apply)"}),s.jsx("div",{className:"mt-2 space-y-2",children:$rt.map(xt=>s.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[s.jsx(mj,{checked:oe.includes(xt),onCheckedChange:()=>yt(xt)}),s.jsx("span",{children:xt})]},xt))})]}),m==="offer"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Estimated offer"}),s.jsx(Or,{value:ye,onChange:xt=>we(xt.target.value),placeholder:"$",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Financing"}),s.jsxs(Pa,{value:Le,onValueChange:Se,children:[s.jsx(va,{className:"mt-1",children:s.jsx(Ra,{placeholder:"Select..."})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"Cash",children:"Cash"}),s.jsx(gn,{value:"Conventional",children:"Conventional"}),s.jsx(gn,{value:"FHA",children:"FHA"}),s.jsx(gn,{value:"VA",children:"VA"}),s.jsx(gn,{value:"Other",children:"Other"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Timeline"}),s.jsxs(Pa,{value:ve,onValueChange:me,children:[s.jsx(va,{className:"mt-1",children:s.jsx(Ra,{placeholder:"Select..."})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"ASAP",children:"ASAP"}),s.jsx(gn,{value:"30 days",children:"30 days"}),s.jsx(gn,{value:"60 days",children:"60 days"}),s.jsx(gn,{value:"90+ days",children:"90+ days"})]})]})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-xs",children:"Pre-approved?"}),s.jsxs(Pa,{value:ke,onValueChange:Pe,children:[s.jsx(va,{className:"mt-1",children:s.jsx(Ra,{placeholder:"Select..."})}),s.jsxs(_a,{children:[s.jsx(gn,{value:"Yes",children:"Yes"}),s.jsx(gn,{value:"No",children:"No"}),s.jsx(gn,{value:"In progress",children:"In progress"})]})]})]})]})]}),s.jsxs("div",{children:[s.jsxs(Br,{className:"text-xs",children:["Message",m==="question"?" *":" (optional)"]}),s.jsx(qc,{value:v,onChange:xt=>w(xt.target.value),placeholder:F6[m].placeholder,rows:4,className:"mt-1"})]}),s.jsx(Lt,{onClick:kt,disabled:M||!ft,className:"w-full h-12 text-white hover:opacity-90",style:f?{backgroundColor:f}:void 0,children:M?s.jsx(zc,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const Vrt=qg({first_name:Ds().trim().min(1,"First name is required").max(50),last_name:Ds().trim().max(50).optional(),email:Ds().trim().email("Please enter a valid email").max(255).optional().or(bO("")),phone:Ds().trim().max(20).optional().or(bO(""))}),qrt=[{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 gSe({slug:t}={}){var Kt;const e=id(),r=t||e.slug,[n]=y0(),i=n.get("kiosk")==="1"||n.get("mode")==="kiosk",o=8,{data:c,isLoading:a,error:f}=lSe(r),m=Ert(),y=krt(),v=Art(),w=N.useRef(!1),[j,A]=N.useState("welcome"),[C,I]=N.useState(null),[M,D]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[F,z]=N.useState(""),[q,H]=N.useState(!1),[K,J]=N.useState(!1),[Q,ee]=N.useState(""),[oe,de]=N.useState(""),[ye,we]=N.useState(o),[Le,Se]=N.useState(!1),[ve,me]=N.useState(null),ke=c==null?void 0:c.agent_card_slug,Pe=ke?`https://cards.relevelup.com/${ke}${c!=null&&c.disclosure_pdf_url?`?oh_disclosure=${encodeURIComponent(c.disclosure_pdf_url)}`:""}`:null,Ee=j==="done"&&!i&&!!Pe&&!!(c!=null&&c.auto_forward_to_card);N.useEffect(()=>{if(!Ee||Le){me(null);return}let At=c!=null&&c.disclosure_pdf_url?10:3;me(At);const pr=setInterval(()=>{if(At-=1,At<=0){clearInterval(pr),window.location.href=Pe;return}me(At)},1e3);return()=>clearInterval(pr)},[Ee,Le,Pe,c==null?void 0:c.disclosure_pdf_url]);const xe=N.useCallback(()=>{I(null),D({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),z(""),H(!1),J(!1),ee(""),de(""),we(o),A(i?"info":"welcome")},[i]),Ue=N.useCallback((At,pr)=>{c!=null&&c.id&&Ce.functions.invoke("guestbook-lead-notify",{body:{open_house_id:c.id,visitor_id:At,first_name:pr.first_name??M.first_name,last_name:pr.last_name??M.last_name,email:pr.email??M.email,phone:pr.phone??M.phone,visitor_intent:pr.visitor_intent??F,message:pr.message,wants_market_updates:pr.wants_market_updates??q,has_agent:pr.has_agent??K,working_with_agent_name:pr.working_with_agent_name??Q,visitor_address:pr.visitor_address??M.visitor_address}}).catch(yn=>console.error("Guest book lead notify failed:",yn))},[c==null?void 0:c.id,M,F,q,K,Q]);N.useEffect(()=>{if(!i||j!=="done")return;we(o);const At=setInterval(()=>{we(pr=>pr<=1?(clearInterval(At),xe(),0):pr-1)},1e3);return()=>clearInterval(At)},[i,j,xe]),N.useEffect(()=>{if(!i)return;A(pr=>pr==="welcome"?"info":pr);let At=null;return(async()=>{var pr,yn;try{At=await((yn=(pr=navigator.wakeLock)==null?void 0:pr.request)==null?void 0:yn.call(pr,"screen"))}catch{}})(),()=>{var pr;try{(pr=At==null?void 0:At.release)==null||pr.call(At)}catch{}}},[i]);const Ze=N.useCallback(()=>{var pr;const At=document.documentElement;document.fullscreenElement||(pr=At.requestFullscreen||At.webkitRequestFullscreen)==null||pr.call(At).catch(()=>{})},[]),{data:lt,isLoading:wt}=Trt(c==null?void 0:c.id),yt=!!(c!=null&&c.enable_survey),gt=(c==null?void 0:c.ask_visitor_intent)!==!1,ft=(c==null?void 0:c.ask_visitor_address)===!0;N.useEffect(()=>{if(!r||!(c!=null&&c.id)||w.current)return;const At=`oh_scan_${c.id}`;if(sessionStorage.getItem(At)){w.current=!0;return}w.current=!0,sessionStorage.setItem(At,"1"),v.mutate(r)},[r,c==null?void 0:c.id]),N.useEffect(()=>{j==="pending_survey"&&(wt||A(yt&&((lt==null?void 0:lt.length)??0)>0?"survey":"done"))},[j,wt,yt,lt]);const kt=At=>{if(!At)return"";const[pr,yn]=At.split(":"),Gn=parseInt(pr),Bn=Gn>=12?"PM":"AM";return`${Gn>12?Gn-12:Gn||12}:${yn} ${Bn}`},Vt=async()=>{de("");const At=Vrt.safeParse(M);if(!At.success){de(At.error.issues[0].message);return}if(!M.email&&!M.phone){de("Please provide either an email or phone number");return}const pr=(c==null?void 0:c.kind)==="virtual";let yn=null;if(!C&&(c!=null&&c.id))try{const Gn=await m.mutateAsync({open_house_id:c.id,first_name:M.first_name.trim(),last_name:M.last_name.trim()||void 0,email:M.email.trim()||void 0,phone:M.phone.trim()||void 0,visitor_address:ft&&M.visitor_address.trim()?M.visitor_address.trim():void 0,wants_market_updates:q,has_agent:K,working_with_agent_name:K&&Q.trim()?Q.trim():void 0,partial_signin:pr?!1:gt});yn=Gn.id,I(Gn.id)}catch{if(pr){de("We could not start the virtual tour. Please try again.");return}}if(pr){gt?A("intent"):(yn&&Ue(yn,{}),A("done"));return}if(!gt){yn&&Ue(yn,{}),yt?!wt&<&<.length>0?A("survey"):A("pending_survey"):A("done");return}A("intent")},xt=async At=>{z(At);try{let pr=C;if(pr?await y.mutateAsync({visitor_id:pr,visitor_intent:At,wants_market_updates:q,has_agent:K,working_with_agent_name:K&&Q.trim()?Q.trim():null,partial_signin:!1}):(pr=(await m.mutateAsync({open_house_id:c.id,first_name:M.first_name.trim(),last_name:M.last_name.trim()||void 0,email:M.email.trim()||void 0,phone:M.phone.trim()||void 0,visitor_address:ft&&M.visitor_address.trim()?M.visitor_address.trim():void 0,visitor_intent:At,wants_market_updates:q,has_agent:K,working_with_agent_name:K&&Q.trim()?Q.trim():void 0,partial_signin:!1})).id,I(pr)),pr&&Ue(pr,{visitor_intent:At,wants_market_updates:q,has_agent:K,working_with_agent_name:K&&Q.trim()?Q.trim():null}),(c==null?void 0:c.kind)==="virtual"){A("done");return}yt?!wt&<&<.length>0?A("survey"):A("pending_survey"):A("done")}catch{de("Something went wrong. Please try again.")}};if(a)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:s.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(f||!c)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx(ta,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),s.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const or=c.profiles,Tr=((Kt=or==null?void 0:or.name)==null?void 0:Kt.split(" ").map(At=>At[0]).join("").slice(0,2))||"?",rn=c.event_type==="community",Lr=c.kind==="virtual",$r=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Lr&&($r||j==="done"))return!$r&&!C?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:s.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):s.jsxs(s.Fragment,{children:[s.jsxs(no,{children:[s.jsxs("title",{children:["Virtual Tour | ",c.property_address]}),s.jsx("meta",{name:"description",content:`Take a virtual tour of ${c.property_address}`}),s.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),$r&&s.jsx("div",{className:"fixed top-3 left-1/2 -translate-x-1/2 z-[100] bg-amber-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full shadow-lg pointer-events-none",children:"Agent Preview Mode — visitors won't see this"}),s.jsx(Urt,{openHouse:c,visitorId:$r?"preview":C,visitorName:$r?"Preview Visitor":`${M.first_name} ${M.last_name}`.trim(),visitorEmail:$r?"":M.email,visitorPhone:$r?"":M.phone,previewMode:$r})]});const Nn=`${Lr?"Virtual Open House":rn?"Community Event":"Open House"} — ${c.property_address}`,Tt=[[c.city,c.state].filter(Boolean).join(", "),c.event_date?Ls(new Date(c.event_date+"T00:00:00"),"EEE, MMM d"):null,or!=null&&or.name?`Hosted by ${or.name}`:null].filter(Boolean).join(" · "),Zt=c.photo_url||"",ar=Zt&&Zt.includes("/storage/v1/object/public/")?Zt.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Zt||"https://dashboard.relevelup.com/og-image.png",Wt=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return s.jsxs(s.Fragment,{children:[s.jsxs(no,{children:[s.jsx("title",{children:Nn}),s.jsx("meta",{name:"description",content:Tt||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:title",content:Nn}),s.jsx("meta",{property:"og:description",content:Tt||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:image",content:ar}),s.jsx("meta",{property:"og:image:width",content:"1200"}),s.jsx("meta",{property:"og:image:height",content:"630"}),s.jsx("meta",{property:"og:url",content:Wt}),s.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:Nn}),s.jsx("meta",{name:"twitter:description",content:Tt||`Sign in to ${c.property_address}`}),s.jsx("meta",{name:"twitter:image",content:ar}),s.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:s.jsxs("div",{className:"w-full max-w-md",children:[s.jsxs("div",{className:"text-center mb-6",children:[s.jsxs($d,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[s.jsx(zd,{src:(or==null?void 0:or.avatar_url)||"",alt:(or==null?void 0:or.name)||""}),s.jsx(Ud,{className:"bg-white/10 text-white text-lg",children:Tr})]}),s.jsx("p",{className:"text-white/60 text-sm",children:or==null?void 0:or.name}),(or==null?void 0:or.title)&&s.jsx("p",{className:"text-white/40 text-xs",children:or.title})]}),s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[c.photo_url&&s.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[s.jsx("img",{src:c.photo_url,alt:c.property_address,className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),s.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[s.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:c.property_address}),s.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[c.city&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ii,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!Lr&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bo,{className:"h-3 w-3"}),Ls(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Hl,{className:"h-3 w-3"}),kt(c.start_time),c.end_time?` – ${kt(c.end_time)}`:""]})]})]})]})]}),!c.photo_url&&s.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:rn?s.jsx(to,{className:"h-5 w-5 text-white"}):s.jsx(ta,{className:"h-5 w-5 text-white"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:c.property_address}),s.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[c.city&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ii,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!Lr&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bo,{className:"h-3 w-3"}),Ls(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Hl,{className:"h-3 w-3"}),kt(c.start_time),c.end_time?` – ${kt(c.end_time)}`:""]})]})]})]})]})}),s.jsxs("div",{className:"p-6",children:[j==="welcome"&&s.jsxs("div",{className:"text-center space-y-6",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),s.jsx("p",{className:"text-slate-500 text-sm",children:c.agent_greeting||"Please sign in below."})]}),s.jsxs(Lt,{onClick:()=>A("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",s.jsx(ei,{className:"h-5 w-5 ml-2"})]}),s.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),j==="info"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{onClick:()=>A("welcome"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(Hx,{className:"h-4 w-4"})}),s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{className:"text-slate-600 text-xs",children:"First Name *"}),s.jsx(Or,{value:M.first_name,onChange:At=>D(pr=>({...pr,first_name:At.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-slate-600 text-xs",children:"Last Name"}),s.jsx(Or,{value:M.last_name,onChange:At=>D(pr=>({...pr,last_name:At.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-slate-600 text-xs",children:"Email"}),s.jsx(Or,{type:"email",value:M.email,onChange:At=>D(pr=>({...pr,email:At.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),s.jsxs("div",{children:[s.jsx(Br,{className:"text-slate-600 text-xs",children:"Phone"}),s.jsx(Or,{type:"tel",value:M.phone,onChange:At=>D(pr=>({...pr,phone:At.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ft&&s.jsxs("div",{children:[s.jsx(Br,{className:"text-slate-600 text-xs",children:"Your Home Address"}),s.jsx(Or,{value:M.visitor_address,onChange:At=>D(pr=>({...pr,visitor_address:At.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[s.jsx("input",{type:"checkbox",checked:q,onChange:At=>H(At.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),s.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),s.jsxs("div",{className:"space-y-2 pt-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs font-medium text-slate-400",children:K?"Yes":"No"}),s.jsx(gj,{checked:K,onCheckedChange:J})]})]}),K&&s.jsx(Or,{value:Q,onChange:At=>ee(At.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),oe&&s.jsx("p",{className:"text-destructive text-sm",children:oe}),s.jsxs(Lt,{onClick:Vt,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",s.jsx(ei,{className:"h-5 w-5 ml-2"})]})]}),j==="intent"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{onClick:()=>A("info"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(Hx,{className:"h-4 w-4"})}),s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:qrt.map(At=>s.jsxs("button",{onClick:()=>xt(At.value),disabled:m.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[s.jsx("span",{className:"text-2xl",children:At.emoji}),s.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:At.label})]},At.value))}),oe&&s.jsx("p",{className:"text-destructive text-sm text-center",children:oe})]}),j==="pending_survey"&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[s.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),s.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),j==="survey"&&C&<&&s.jsx(Ort,{questions:lt,visitorId:C,onComplete:()=>A("done"),onSkip:()=>A("done")}),j==="done"&&s.jsxs("div",{className:"text-center space-y-4 py-4",children:[s.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:s.jsx(Il,{className:"h-8 w-8 text-green-600"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),s.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",M.first_name,". ",rn?"Enjoy the event!":"Enjoy the open house!"]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[(c==null?void 0:c.disclosure_pdf_url)&&s.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(c.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",onClick:()=>Se(!0),className:"inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[s.jsx(Qm,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),Pe&&s.jsxs("a",{href:Pe,className:"inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-slate-900 hover:bg-slate-800 text-white font-medium text-sm transition-colors",children:[s.jsx(ei,{className:"h-4 w-4"}),"View ",or!=null&&or.name?`${or.name.split(" ")[0]}'s`:"My"," Business Card"]})]}),Pe&&ve!==null&&!Le&&s.jsxs("p",{className:"text-xs text-slate-400",children:["Opening the business card in ",ve,"s…"," ",s.jsx("button",{type:"button",className:"underline",onClick:()=>Se(!0),children:"Stay here"})]}),(or==null?void 0:or.name)&&s.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",s.jsx("strong",{className:"text-slate-600",children:or.name})]}),i&&s.jsxs("div",{className:"pt-4 space-y-3",children:[s.jsx(Lt,{onClick:xe,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),s.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",ye,"s…"]})]})]})]})]}),s.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),i&&s.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[s.jsx(gFe,{className:"h-3 w-3"})," Tablet Mode"]}),s.jsx("button",{onClick:Ze,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:s.jsx(Z3e,{className:"h-3 w-3"})})]})]})})]})}const Grt=Object.freeze(Object.defineProperty({__proto__:null,default:gSe},Symbol.toStringTag,{value:"Module"}));function Wtr(t){return mr({queryKey:["open-house-rsvps",t],queryFn:async()=>{const{data:e,error:r}=await Ce.from("open_house_rsvps").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(r)throw r;return e||[]},enabled:!!t})}function Hrt(){const t=kr();return Ar({mutationFn:async e=>{const{error:r}=await Ce.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 Ktr(t){const e=kr();return Ar({mutationFn:async r=>{const{error:n}=await Ce.from("open_house_rsvps").delete().eq("id",r);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}function Ytr(t){const e=kr();return Ar({mutationFn:async({id:r,checkedIn:n})=>{const{error:i}=await Ce.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 Wrt=qg({first_name:Ds().trim().min(1,"First name is required").max(50),last_name:Ds().trim().max(50).optional(),email:Ds().trim().email("Please enter a valid email").max(255),phone:Ds().trim().max(20).optional().or(bO("")),message:Ds().trim().max(500).optional().or(bO(""))}),B6=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}`},Krt=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 ySe({slug:t}={}){const e=id(),r=t||e.slug,{data:n,isLoading:i,error:o}=lSe(r),c=Hrt(),[a,f]=N.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[m,y]=N.useState(!1),[v,w]=N.useState(""),[j,A]=N.useState(""),[C,I]=N.useState(!1),M=N.useMemo(()=>Krt(n==null?void 0:n.event_date),[n==null?void 0:n.event_date]),D=N.useMemo(()=>{const J=n==null?void 0:n.photo_url;return J?J.includes("/storage/v1/object/public/")?J.replace("/object/public/","/render/image/public/")+"?width=1600&quality=80":J:""},[n]),F=n==null?void 0:n.profiles,z=[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),q=async()=>{A("");const J=Wrt.safeParse(a);if(!J.success){A(J.error.issues[0].message);return}try{await c.mutateAsync({open_house_id:n.id,first_name:a.first_name.trim(),last_name:a.last_name.trim()||void 0,email:a.email.trim(),phone:a.phone.trim()||void 0,has_agent:m,working_with_agent_name:m&&v.trim()?v.trim():void 0,message:a.message.trim()||void 0}),I(!0)}catch(Q){A((Q==null?void 0:Q.message)||"Something went wrong. Please try again.")}},H=N.useMemo(()=>{if(!n||!M)return"";const J=we=>String(we).padStart(2,"0"),Q=`${M.getFullYear()}${J(M.getMonth()+1)}${J(M.getDate())}`,ee=(n.start_time||"12:00").slice(0,5).replace(":","")+"00",oe=(n.end_time||"14:00").slice(0,5).replace(":","")+"00",de=encodeURIComponent(`Open House — ${n.property_address}`),ye=encodeURIComponent([n.property_address,z,n.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${de}&dates=${Q}T${ee}/${Q}T${oe}&location=${ye}`},[n,M,z]);if(i)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:s.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(o||!n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:s.jsxs("div",{className:"text-white/80",children:[s.jsx(ta,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),s.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),s.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const K=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([n.property_address,z,n.zip].filter(Boolean).join(", "))}`;return s.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[s.jsxs(no,{children:[s.jsx("title",{children:`RSVP — Open House at ${n.property_address}`}),s.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${n.property_address}${M?` on ${Ls(M,"EEEE, MMMM d")}`:""}.`})]}),s.jsxs("header",{className:"relative",children:[s.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[D&&s.jsx("img",{src:D,alt:n.property_address,className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:s.jsxs("div",{className:"mx-auto max-w-3xl",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),s.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:n.property_address}),z&&s.jsxs("p",{className:"mt-1 text-white/70",children:[z," ",n.zip||""]}),s.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[M&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bo,{className:"h-4 w-4 text-[#d4b978]"}),Ls(M,"EEEE, MMMM d, yyyy")]}),n.start_time&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hl,{className:"h-4 w-4 text-[#d4b978]"}),B6(n.start_time),n.end_time?` – ${B6(n.end_time)}`:""]})]})]})})]}),s.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),s.jsxs("main",{className:"mx-auto max-w-3xl px-5 py-8 sm:py-12 space-y-8",children:[(n.price||n.beds||n.baths||n.sqft)&&s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[n.price?s.jsx(NL,{icon:s.jsx(ta,{className:"h-4 w-4"}),label:"Price",value:`$${Number(n.price).toLocaleString()}`}):null,n.beds?s.jsx(NL,{icon:s.jsx(vye,{className:"h-4 w-4"}),label:"Beds",value:String(n.beds)}):null,n.baths?s.jsx(NL,{icon:s.jsx(m0,{className:"h-4 w-4"}),label:"Baths",value:String(n.baths)}):null,n.sqft?s.jsx(NL,{icon:s.jsx(AC,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(n.sqft).toLocaleString()}):null]}),n.property_description&&s.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:n.property_description}),s.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:C?s.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[s.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:s.jsx(Il,{className:"h-7 w-7 text-emerald-600"})}),s.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),s.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",M?Ls(M,"EEEE, MMMM d"):"soon",n.start_time?` at ${B6(n.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),s.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[H&&s.jsx(Lt,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:s.jsxs("a",{href:H,target:"_blank",rel:"noreferrer",children:[s.jsx(_ye,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),s.jsx(Lt,{asChild:!0,variant:"outline",children:s.jsxs("a",{href:K,target:"_blank",rel:"noreferrer",children:[s.jsx(ii,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):s.jsxs("div",{className:"p-6 sm:p-8",children:[s.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),s.jsx("p",{className:"mt-1 text-sm text-[#5b6b72]",children:"Let us know you're coming and we'll save you a spot and send a reminder."}),s.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"rsvp-first",children:"First name *"}),s.jsx(Or,{id:"rsvp-first",value:a.first_name,onChange:J=>f(Q=>({...Q,first_name:J.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"rsvp-last",children:"Last name"}),s.jsx(Or,{id:"rsvp-last",value:a.last_name,onChange:J=>f(Q=>({...Q,last_name:J.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"rsvp-email",children:"Email *"}),s.jsx(Or,{id:"rsvp-email",type:"email",value:a.email,onChange:J=>f(Q=>({...Q,email:J.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Br,{htmlFor:"rsvp-phone",children:"Phone"}),s.jsx(Or,{id:"rsvp-phone",type:"tel",value:a.phone,onChange:J=>f(Q=>({...Q,phone:J.target.value})),className:"h-11"})]})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),s.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),s.jsx(gj,{checked:m,onCheckedChange:y})]}),m&&s.jsx(Or,{value:v,onChange:J=>w(J.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),s.jsxs("div",{className:"mt-4 space-y-1.5",children:[s.jsx(Br,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),s.jsx(qc,{id:"rsvp-msg",rows:3,value:a.message,onChange:J=>f(Q=>({...Q,message:J.target.value})),className:"resize-y"})]}),j&&s.jsx("p",{className:"mt-3 text-sm text-destructive",children:j}),s.jsx(Lt,{onClick:q,disabled:c.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:c.isPending?"Reserving…":s.jsxs(s.Fragment,{children:["RSVP for this open house",s.jsx(ei,{className:"ml-2 h-4 w-4"})]})}),s.jsx("p",{className:"mt-3 text-center text-xs text-[#8b979c]",children:"We'll only use your info to follow up about this property."})]})}),(F==null?void 0:F.name)&&s.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[s.jsxs($d,{className:"h-14 w-14",children:[s.jsx(zd,{src:F.avatar_url||void 0,alt:F.name}),s.jsx(Ud,{children:F.name.slice(0,1)})]}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),s.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:F.name}),F.title&&s.jsx("p",{className:"text-sm text-[#5b6b72]",children:F.title}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[F.phone&&s.jsx("a",{href:`tel:${F.phone}`,children:F.phone}),F.email&&s.jsx("a",{href:`mailto:${F.email}`,className:"truncate",children:F.email})]})]})]}),s.jsx("div",{className:"text-center",children:s.jsxs("a",{href:K,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[s.jsx(ii,{className:"h-4 w-4"}),"Get directions to ",n.property_address]})})]})]})}function NL({icon:t,label:e,value:r}){return s.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[t,e]}),s.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:r})]})}const Yrt=Object.freeze(Object.defineProperty({__proto__:null,default:ySe},Symbol.toStringTag,{value:"Module"}));function Ztr(t){const{user:e}=Zn();return mr({queryKey:["cohost-tokens",t],queryFn:async()=>{const{data:r,error:n}=await Ce.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 Xtr(){const t=kr(),{user:e}=Zn();return Ar({mutationFn:async({openHouseId:r,label:n})=>{const{data:i,error:o}=await Ce.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 Qtr(){const t=kr();return Ar({mutationFn:async({id:e,openHouseId:r})=>{const{error:n}=await Ce.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 Zrt(t){return mr({queryKey:["cohost-validate",t],queryFn:async()=>{const{data:e,error:r}=await Ce.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 np=(t,e,r)=>r>e?e:r{},fT=()=>{};const t0={},vSe=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function _Se(t){return typeof t=="object"&&t!==null}const bSe=t=>/^0[^.\s]+$/u.test(t);function wSe(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ah=t=>t,Qrt=(t,e)=>r=>e(t(r)),tI=(...t)=>t.reduce(Qrt),_N=(t,e,r)=>{const n=e-t;return n===0?1:(r-t)/n};class IK{constructor(){this.subscriptions=[]}add(e){return CK(this.subscriptions,e),()=>jO(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,Sh=t=>t/1e3;function SSe(t,e){return e?t*(1e3/e):0}const TSe=(t,e,r)=>(((1-3*r+3*e)*t+(3*r-6*e))*t+3*e)*t,Jrt=1e-7,ent=12;function tnt(t,e,r,n,i){let o,c,a=0;do c=e+(r-e)/2,o=TSe(c,n,i)-t,o>0?r=c:e=c;while(Math.abs(o)>Jrt&&++atnt(o,0,1,t,r);return o=>o===0||o===1?o:TSe(i(o),e,n)}const jSe=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ESe=t=>e=>1-t(1-e),kSe=rI(.33,1.53,.69,.99),PK=ESe(kSe),ASe=jSe(PK),NSe=t=>t>=1?1:(t*=2)<1?.5*PK(t):.5*(2-Math.pow(2,-10*(t-1))),RK=t=>1-Math.sin(Math.acos(t)),CSe=ESe(RK),ISe=jSe(RK),rnt=rI(.42,0,1,1),nnt=rI(0,0,.58,1),PSe=rI(.42,0,.58,1),snt=t=>Array.isArray(t)&&typeof t[0]!="number",RSe=t=>Array.isArray(t)&&typeof t[0]=="number",Oie={linear:Ah,easeIn:rnt,easeInOut:PSe,easeOut:nnt,circIn:RK,circInOut:ISe,circOut:CSe,backIn:PK,backInOut:ASe,backOut:kSe,anticipate:NSe},int=t=>typeof t=="string",Fie=t=>{if(RSe(t)){fT(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,r,n,i]=t;return rI(e,r,n,i)}else if(int(t))return fT(Oie[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Oie[t];return t},CL=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Bie={value:null,addProjectionMetrics:null};function ant(t,e){let r=new Set,n=new Set,i=!1,o=!1;const c=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},f=0;function m(v){c.has(v)&&(y.schedule(v),t()),f++,v(a)}const y={schedule:(v,w=!1,j=!1)=>{const C=j&&i?r:n;return w&&c.add(v),C.add(v),v},cancel:v=>{n.delete(v),c.delete(v)},process:v=>{if(a=v,i){o=!0;return}i=!0;const w=r;r=n,n=w,r.forEach(m),e&&Bie.value&&Bie.value.frameloop[e].push(f),f=0,r.clear(),i=!1,o&&(o=!1,y.process(v))}};return y}const ont=40;function LSe(t,e){let r=!1,n=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>r=!0,c=CL.reduce((F,z)=>(F[z]=ant(o,e?z:void 0),F),{}),{setup:a,read:f,resolveKeyframes:m,preUpdate:y,update:v,preRender:w,render:j,postRender:A}=c,C=()=>{const F=t0.useManualTiming,z=F?i.timestamp:performance.now();r=!1,F||(i.delta=n?1e3/60:Math.max(Math.min(z-i.timestamp,ont),1)),i.timestamp=z,i.isProcessing=!0,a.process(i),f.process(i),m.process(i),y.process(i),v.process(i),w.process(i),j.process(i),A.process(i),i.isProcessing=!1,r&&e&&(n=!1,t(C))},I=()=>{r=!0,n=!0,i.isProcessing||t(C)};return{schedule:CL.reduce((F,z)=>{const q=c[z];return F[z]=(H,K=!1,J=!1)=>(r||I(),q.schedule(H,K,J)),F},{}),cancel:F=>{for(let z=0;z(YM===void 0&&xu.set(sc.isProcessing||t0.useManualTiming?sc.timestamp:performance.now()),YM),set:t=>{YM=t,queueMicrotask(lnt)}},MSe=t=>e=>typeof e=="string"&&e.startsWith(t),DSe=MSe("--"),cnt=MSe("var(--"),LK=t=>cnt(t)?unt.test(t.split("/*")[0].trim()):!1,unt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function $ie(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const yj={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},bN={...yj,transform:t=>np(0,1,t)},IL={...yj,default:1},xA=t=>Math.round(t*1e5)/1e5,MK=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function dnt(t){return t==null}const hnt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,DK=(t,e)=>r=>!!(typeof r=="string"&&hnt.test(r)&&r.startsWith(t)||e&&!dnt(r)&&Object.prototype.hasOwnProperty.call(r,e)),OSe=(t,e,r)=>n=>{if(typeof n!="string")return n;const[i,o,c,a]=n.match(MK);return{[t]:parseFloat(i),[e]:parseFloat(o),[r]:parseFloat(c),alpha:a!==void 0?parseFloat(a):1}},fnt=t=>np(0,255,t),z6={...yj,transform:t=>Math.round(fnt(t))},p_={test:DK("rgb","red"),parse:OSe("red","green","blue"),transform:({red:t,green:e,blue:r,alpha:n=1})=>"rgba("+z6.transform(t)+", "+z6.transform(e)+", "+z6.transform(r)+", "+xA(bN.transform(n))+")"};function mnt(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 Zq={test:DK("#"),parse:mnt,transform:p_.transform},nI=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Xy=nI("deg"),Ym=nI("%"),Dn=nI("px"),pnt=nI("vh"),gnt=nI("vw"),zie={...Ym,parse:t=>Ym.parse(t)/100,transform:t=>Ym.transform(t*100)},J1={test:DK("hsl","hue"),parse:OSe("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:r,alpha:n=1})=>"hsla("+Math.round(t)+", "+Ym.transform(xA(e))+", "+Ym.transform(xA(r))+", "+xA(bN.transform(n))+")"},il={test:t=>p_.test(t)||Zq.test(t)||J1.test(t),parse:t=>p_.test(t)?p_.parse(t):J1.test(t)?J1.parse(t):Zq.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?p_.transform(t):J1.transform(t),getAnimatableNone:t=>{const e=il.parse(t);return e.alpha=0,il.transform(e)}},ynt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function xnt(t){var e,r;return isNaN(t)&&typeof t=="string"&&(((e=t.match(MK))==null?void 0:e.length)||0)+(((r=t.match(ynt))==null?void 0:r.length)||0)>0}const FSe="number",BSe="color",vnt="var",_nt="var(",Uie="${}",bnt=/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 mT(t){const e=t.toString(),r=[],n={color:[],number:[],var:[]},i=[];let o=0;const a=e.replace(bnt,f=>(il.test(f)?(n.color.push(o),i.push(BSe),r.push(il.parse(f))):f.startsWith(_nt)?(n.var.push(o),i.push(vnt),r.push(f)):(n.number.push(o),i.push(FSe),r.push(parseFloat(f))),++o,Uie)).split(Uie);return{values:r,split:a,indexes:n,types:i}}function wnt(t){return mT(t).values}function $Se({split:t,types:e}){const r=t.length;return n=>{let i="";for(let o=0;otypeof t=="number"?0:il.test(t)?il.getAnimatableNone(t):t,jnt=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:Tnt(t);function Ent(t){const e=mT(t);return $Se(e)(e.values.map((n,i)=>jnt(n,e.split[i])))}const Ff={test:xnt,parse:wnt,createTransformer:Snt,getAnimatableNone:Ent};function U6(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 knt({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 a=r<.5?r*(1+e):r+e-r*e,f=2*r-a;i=U6(f,a,t+1/3),o=U6(f,a,t),c=U6(f,a,t-1/3)}return{red:Math.round(i*255),green:Math.round(o*255),blue:Math.round(c*255),alpha:n}}function EO(t,e){return r=>r>0?e:t}const Ga=(t,e,r)=>t+(e-t)*r,V6=(t,e,r)=>{const n=t*t,i=r*(e*e-n)+n;return i<0?0:Math.sqrt(i)},Ant=[Zq,p_,J1],Nnt=t=>Ant.find(e=>e.test(t));function Vie(t){const e=Nnt(t);if(AF(!!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===J1&&(r=knt(r)),r}const qie=(t,e)=>{const r=Vie(t),n=Vie(e);if(!r||!n)return EO(t,e);const i={...r};return o=>(i.red=V6(r.red,n.red,o),i.green=V6(r.green,n.green,o),i.blue=V6(r.blue,n.blue,o),i.alpha=Ga(r.alpha,n.alpha,o),p_.transform(i))},Xq=new Set(["none","hidden"]);function Cnt(t,e){return Xq.has(t)?r=>r<=0?t:e:r=>r>=1?e:t}function Int(t,e){return r=>Ga(t,e,r)}function OK(t){return typeof t=="number"?Int:typeof t=="string"?LK(t)?EO:il.test(t)?qie:Lnt:Array.isArray(t)?zSe:typeof t=="object"?il.test(t)?qie:Pnt:EO}function zSe(t,e){const r=[...t],n=r.length,i=t.map((o,c)=>OK(o)(o,e[c]));return o=>{for(let c=0;c{for(const o in n)r[o]=n[o](i);return r}}function Rnt(t,e){const r=[],n={color:0,var:0,number:0};for(let i=0;i{const r=Ff.createTransformer(e),n=mT(t),i=mT(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?Xq.has(t)&&!i.values.length||Xq.has(e)&&!n.values.length?Cnt(t,e):tI(zSe(Rnt(n,i),i.values),r):(AF(!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"),EO(t,e))};function USe(t,e,r){return typeof t=="number"&&typeof e=="number"&&typeof r=="number"?Ga(t,e,r):OK(t)(t,e)}const Mnt=t=>{const e=({timestamp:r})=>t(r);return{start:(r=!0)=>ga.update(e,r),stop:()=>r0(e),now:()=>sc.isProcessing?sc.timestamp:xu.now()}},VSe=(t,e,r=10)=>{let n="";const i=Math.max(Math.round(e/r),2);for(let o=0;o=kO?1/0:e}function Dnt(t,e=100,r){const n=r({...t,keyframes:[0,e]}),i=Math.min(FK(n),kO);return{type:"keyframes",ease:o=>n.next(i*o).value/e,duration:Sh(i)}}const fo={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 Qq(t,e){return t*Math.sqrt(1-e*e)}const Ont=12;function Fnt(t,e,r){let n=r;for(let i=1;i{const y=m*c,v=y*t,w=y-r,j=Qq(m,c),A=Math.exp(-v);return q6-w/j*A},o=m=>{const v=m*c*t,w=v*r+r,j=Math.pow(c,2)*Math.pow(m,2)*t,A=Math.exp(-v),C=Qq(Math.pow(m,2),c);return(-i(m)+q6>0?-1:1)*((w-j)*A)/C}):(i=m=>{const y=Math.exp(-m*t),v=(m-r)*t+1;return-q6+y*v},o=m=>{const y=Math.exp(-m*t),v=(r-m)*(t*t);return y*v});const a=5/t,f=Fnt(i,o,a);if(t=td(t),isNaN(f))return{stiffness:fo.stiffness,damping:fo.damping,duration:t};{const m=Math.pow(f,2)*n;return{stiffness:m,damping:c*2*Math.sqrt(n*m),duration:t}}}const $nt=["duration","bounce"],znt=["stiffness","damping","mass"];function Gie(t,e){return e.some(r=>t[r]!==void 0)}function Unt(t){let e={velocity:fo.velocity,stiffness:fo.stiffness,damping:fo.damping,mass:fo.mass,isResolvedFromDuration:!1,...t};if(!Gie(t,znt)&&Gie(t,$nt))if(e.velocity=0,t.visualDuration){const r=t.visualDuration,n=2*Math.PI/(r*1.2),i=n*n,o=2*np(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:fo.mass,stiffness:i,damping:o}}else{const r=Bnt({...t,velocity:0});e={...e,...r,mass:fo.mass},e.isResolvedFromDuration=!0}return e}function AO(t=fo.visualDuration,e=fo.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],a={done:!1,value:o},{stiffness:f,damping:m,mass:y,duration:v,velocity:w,isResolvedFromDuration:j}=Unt({...r,velocity:-Sh(r.velocity||0)}),A=w||0,C=m/(2*Math.sqrt(f*y)),I=c-o,M=Sh(Math.sqrt(f/y)),D=Math.abs(I)<5;n||(n=D?fo.restSpeed.granular:fo.restSpeed.default),i||(i=D?fo.restDelta.granular:fo.restDelta.default);let F,z,q,H,K,J;if(C<1)q=Qq(M,C),H=(A+C*M*I)/q,F=ee=>{const oe=Math.exp(-C*M*ee);return c-oe*(H*Math.sin(q*ee)+I*Math.cos(q*ee))},K=C*M*H+I*q,J=C*M*I-H*q,z=ee=>Math.exp(-C*M*ee)*(K*Math.sin(q*ee)+J*Math.cos(q*ee));else if(C===1){F=oe=>c-Math.exp(-M*oe)*(I+(A+M*I)*oe);const ee=A+M*I;z=oe=>Math.exp(-M*oe)*(M*ee*oe-A)}else{const ee=M*Math.sqrt(C*C-1);F=we=>{const Le=Math.exp(-C*M*we),Se=Math.min(ee*we,300);return c-Le*((A+C*M*I)*Math.sinh(Se)+ee*I*Math.cosh(Se))/ee};const oe=(A+C*M*I)/ee,de=C*M*oe-I*ee,ye=C*M*I-oe*ee;z=we=>{const Le=Math.exp(-C*M*we),Se=Math.min(ee*we,300);return Le*(de*Math.sinh(Se)+ye*Math.cosh(Se))}}const Q={calculatedDuration:j&&v||null,velocity:ee=>td(z(ee)),next:ee=>{if(!j&&C<1){const de=Math.exp(-C*M*ee),ye=Math.sin(q*ee),we=Math.cos(q*ee),Le=c-de*(H*ye+I*we),Se=td(de*(K*ye+J*we));return a.done=Math.abs(Se)<=n&&Math.abs(c-Le)<=i,a.value=a.done?c:Le,a}const oe=F(ee);if(j)a.done=ee>=v;else{const de=td(z(ee));a.done=Math.abs(de)<=n&&Math.abs(c-oe)<=i}return a.value=a.done?c:oe,a},toString:()=>{const ee=Math.min(FK(Q),kO),oe=VSe(de=>Q.next(ee*de).value,ee,30);return ee+"ms "+oe},toTransition:()=>{}};return Q}AO.applyToOptions=t=>{const e=Dnt(t,100,AO);return t.ease=e.ease,t.duration=td(e.duration),t.type="keyframes",t};const Vnt=5;function qSe(t,e,r){const n=Math.max(e-Vnt,0);return SSe(r-t(n),e-n)}function Jq({keyframes:t,velocity:e=0,power:r=.8,timeConstant:n=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:c,min:a,max:f,restDelta:m=.5,restSpeed:y}){const v=t[0],w={done:!1,value:v},j=J=>a!==void 0&&Jf,A=J=>a===void 0?f:f===void 0||Math.abs(a-J)-C*Math.exp(-J/n),F=J=>M+D(J),z=J=>{const Q=D(J),ee=F(J);w.done=Math.abs(Q)<=m,w.value=w.done?M:ee};let q,H;const K=J=>{j(w.value)&&(q=J,H=AO({keyframes:[w.value,A(w.value)],velocity:qSe(F,J,w.value),damping:i,stiffness:o,restDelta:m,restSpeed:y}))};return K(0),{calculatedDuration:null,next:J=>{let Q=!1;return!H&&q===void 0&&(Q=!0,z(J),K(J)),q!==void 0&&J>=q?H.next(J-q):(!Q&&z(J),w)}}}function qnt(t,e,r){const n=[],i=r||t0.mix||USe,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 a=qnt(e,n,i),f=a.length,m=y=>{if(c&&y1)for(;vm(np(t[0],t[o-1],y)):m}function Hnt(t,e){const r=t[t.length-1];for(let n=1;n<=e;n++){const i=_N(0,e,n);t.push(Ga(r,1,i))}}function Wnt(t){const e=[0];return Hnt(e,t.length-1),e}function Knt(t,e){return t.map(r=>r*e)}function Ynt(t,e){return t.map(()=>e||PSe).splice(0,t.length-1)}function vA({duration:t=300,keyframes:e,times:r,ease:n="easeInOut"}){const i=snt(n)?n.map(Fie):Fie(n),o={done:!1,value:e[0]},c=Knt(r&&r.length===e.length?r:Wnt(e),t),a=Gnt(c,e,{ease:Array.isArray(i)?i:Ynt(e,i)});return{calculatedDuration:t,next:f=>(o.value=a(f),o.done=f>=t,o)}}const Znt=t=>t!==null;function NF(t,{repeat:e,repeatType:r="loop"},n,i=1){const o=t.filter(Znt),a=i<0||e&&r!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Xnt={decay:Jq,inertia:Jq,tween:vA,keyframes:vA,spring:AO};function GSe(t){typeof t.type=="string"&&(t.type=Xnt[t.type])}class BK{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 Qnt=t=>t/100;class NO extends BK{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!==xu.now()&&this.tick(xu.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;GSe(e);const{type:r=vA,repeat:n=0,repeatDelay:i=0,repeatType:o,velocity:c=0}=e;let{keyframes:a}=e;const f=r||vA;f!==vA&&typeof a[0]!="number"&&(this.mixKeyframes=tI(Qnt,USe(a[0],a[1])),a=[0,100]);const m=f({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=f({...e,keyframes:[...a].reverse(),velocity:-c})),m.calculatedDuration===null&&(m.calculatedDuration=FK(m));const{calculatedDuration:y}=m;this.calculatedDuration=y,this.resolvedDuration=y+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=m}updateTime(e){const r=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(e,r=!1){const{generator:n,totalDuration:i,mixKeyframes:o,mirroredGenerator:c,resolvedDuration:a,calculatedDuration:f}=this;if(this.startTime===null)return n.next(0);const{delay:m=0,keyframes:y,repeat:v,repeatType:w,repeatDelay:j,type:A,onUpdate:C,finalKeyframe:I}=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 M=this.currentTime-m*(this.playbackSpeed>=0?1:-1),D=this.playbackSpeed>=0?M<0:M>i;this.currentTime=Math.max(M,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let F=this.currentTime,z=n;if(v){const J=Math.min(this.currentTime,i)/a;let Q=Math.floor(J),ee=J%1;!ee&&J>=1&&(ee=1),ee===1&&Q--,Q=Math.min(Q,v+1),!!(Q%2)&&(w==="reverse"?(ee=1-ee,j&&(ee-=j/a)):w==="mirror"&&(z=c)),F=np(0,1,ee)*a}let q;D?(this.delayState.value=y[0],q=this.delayState):q=z.next(F),o&&!D&&(q.value=o(q.value));let{done:H}=q;!D&&f!==null&&(H=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const K=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&H);return K&&A!==Jq&&(q.value=NF(y,this.options,I,this.speed)),C&&C(q.value),K&&this.finish(),q}then(e,r){return this.finished.then(e,r)}get duration(){return Sh(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Sh(e)}get time(){return Sh(this.currentTime)}set time(e){e=td(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 qSe(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(xu.now()),this.playbackSpeed=e,r&&this.driver&&(this.time=Sh(this.currentTime))}play(){var i,o;if(this.isStopped)return;const{driver:e=Mnt,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(xu.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 Jnt(t){for(let e=1;et*180/Math.PI,e9=t=>{const e=g_(Math.atan2(t[1],t[0]));return t9(e)},est={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:e9,rotateZ:e9,skewX:t=>g_(Math.atan(t[1])),skewY:t=>g_(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},t9=t=>(t=t%360,t<0&&(t+=360),t),Hie=e9,Wie=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Kie=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),tst={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Wie,scaleY:Kie,scale:t=>(Wie(t)+Kie(t))/2,rotateX:t=>t9(g_(Math.atan2(t[6],t[5]))),rotateY:t=>t9(g_(Math.atan2(-t[2],t[0]))),rotateZ:Hie,rotate:Hie,skewX:t=>g_(Math.atan(t[4])),skewY:t=>g_(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function r9(t){return t.includes("scale")?1:0}function n9(t,e){if(!t||t==="none")return r9(e);const r=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,i;if(r)n=tst,i=r;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=est,i=a}if(!i)return r9(e);const o=n[e],c=i[1].split(",").map(nst);return typeof o=="function"?o(c):c[o]}const rst=(t,e)=>{const{transform:r="none"}=getComputedStyle(t);return n9(r,e)};function nst(t){return parseFloat(t.trim())}const xj=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],vj=new Set(xj),Yie=t=>t===yj||t===Dn,sst=new Set(["x","y","z"]),ist=xj.filter(t=>!sst.has(t));function ast(t){const e=[];return ist.forEach(r=>{const n=t.getValue(r);n!==void 0&&(e.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),e}const Sx={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})=>n9(e,"x"),y:(t,{transform:e})=>n9(e,"y")};Sx.translateX=Sx.x;Sx.translateY=Sx.y;const M_=new Set;let s9=!1,i9=!1,a9=!1;function HSe(){if(i9){const t=Array.from(M_).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),r=new Map;e.forEach(n=>{const i=ast(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 a;(a=n.getValue(o))==null||a.set(c)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}i9=!1,s9=!1,M_.forEach(t=>t.complete(a9)),M_.clear()}function WSe(){M_.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(i9=!0)})}function ost(){a9=!0,WSe(),HSe(),a9=!1}class $K{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?(M_.add(this),s9||(s9=!0,ga.read(WSe),ga.resolveKeyframes(HSe))):(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 a=n.readValue(r,c);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=c),i&&o===void 0&&i.set(e[0])}Jnt(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),M_.delete(this)}cancel(){this.state==="scheduled"&&(M_.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const lst=t=>t.startsWith("--");function KSe(t,e,r){lst(e)?t.style.setProperty(e,r):t.style[e]=r}const cst={};function YSe(t,e){const r=wSe(t);return()=>cst[e]??r()}const ust=YSe(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),ZSe=YSe(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Wk=([t,e,r,n])=>`cubic-bezier(${t}, ${e}, ${r}, ${n})`,Zie={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Wk([0,.65,.55,1]),circOut:Wk([.55,0,1,.45]),backIn:Wk([.31,.01,.66,-.59]),backOut:Wk([.33,1.53,.69,.99])};function XSe(t,e){if(t)return typeof t=="function"?ZSe()?VSe(t,e):"ease-out":RSe(t)?Wk(t):Array.isArray(t)?t.map(r=>XSe(r,e)||Zie.easeOut):Zie[t]}function dst(t,e,r,{delay:n=0,duration:i=300,repeat:o=0,repeatType:c="loop",ease:a="easeOut",times:f}={},m=void 0){const y={[e]:r};f&&(y.offset=f);const v=XSe(a,i);Array.isArray(v)&&(y.easing=v);const w={delay:n,duration:i,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:o+1,direction:c==="reverse"?"alternate":"normal"};return m&&(w.pseudoElement=m),t.animate(y,w)}function QSe(t){return typeof t=="function"&&"applyToOptions"in t}function hst({type:t,...e}){return QSe(t)&&ZSe()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class JSe extends BK{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:a,onComplete:f}=e;this.isPseudoElement=!!o,this.allowFlatten=c,this.options=e,fT(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const m=hst(e);this.animation=dst(r,n,i,m,o),m.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const y=NF(i,this.options,a,this.speed);this.updateMotionValue&&this.updateMotionValue(y),KSe(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 Sh(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Sh(e)}get time(){return Sh(Number(this.animation.currentTime)||0)}set time(e){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=td(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&&ust()?(this.animation.timeline=e,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),Ah):i(this)}}const eTe={anticipate:NSe,backInOut:ASe,circInOut:ISe};function fst(t){return t in eTe}function mst(t){typeof t.ease=="string"&&fst(t.ease)&&(t.ease=eTe[t.ease])}const G6=10;class pst extends JSe{constructor(e){mst(e),GSe(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 a=new NO({...c,autoplay:!1}),f=Math.max(G6,xu.now()-this.startTime),m=np(0,G6,f-G6),y=a.sample(f).value,{name:v}=this.options;o&&v&&KSe(o,v,y),r.setWithVelocity(a.sample(Math.max(0,f-m)).value,y,m),a.stop()}}const Xie=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ff.test(t)||t==="0")&&!t.startsWith("url("));function gst(t){const e=t[0];if(t.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function wst(t){var v;const{motionValue:e,name:r,repeatDelay:n,repeatType:i,damping:o,type:c,keyframes:a}=t;if(!(((v=e==null?void 0:e.owner)==null?void 0:v.current)instanceof HTMLElement))return!1;const{onUpdate:m,transformTemplate:y}=e.owner.getProps();return bst()&&r&&(tTe.has(r)||_st.has(r)&&vst(a))&&(r!=="transform"||!y)&&!m&&!n&&i!=="mirror"&&o!==0&&c!=="inertia"}const Sst=40;class Tst extends BK{constructor({autoplay:e=!0,delay:r=0,type:n="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:c="loop",keyframes:a,name:f,motionValue:m,element:y,...v}){var A;super(),this.stop=()=>{var C,I;this._animation&&(this._animation.stop(),(C=this.stopTimeline)==null||C.call(this)),(I=this.keyframeResolver)==null||I.cancel()},this.createdAt=xu.now();const w={autoplay:e,delay:r,type:n,repeat:i,repeatDelay:o,repeatType:c,name:f,motionValue:m,element:y,...v},j=(y==null?void 0:y.KeyframeResolver)||$K;this.keyframeResolver=new j(a,(C,I,M)=>this.onKeyframesResolved(C,I,w,!M),f,m,y),(A=this.keyframeResolver)==null||A.scheduleResolve()}onKeyframesResolved(e,r,n,i){var M,D;this.keyframeResolver=void 0;const{name:o,type:c,velocity:a,delay:f,isHandoff:m,onUpdate:y}=n;this.resolvedAt=xu.now();let v=!0;yst(e,o,c,a)||(v=!1,(t0.instantAnimations||!f)&&(y==null||y(NF(e,n,r))),e[0]=e[e.length-1],o9(n),n.repeat=0);const j={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>Sst?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:e},A=v&&!m&&wst(j),C=(D=(M=j.motionValue)==null?void 0:M.owner)==null?void 0:D.current;let I;if(A)try{I=new pst({...j,element:C})}catch{I=new NO(j)}else I=new NO(j);I.finished.then(()=>{this.notifyFinished()}).catch(Ah),this.pendingTimeline&&(this.stopTimeline=I.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=I}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(),ost()),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 rTe(t,e,r,n=0,i=1){const o=Array.from(t).sort((m,y)=>m.sortNodePosition(y)).indexOf(e),c=t.size,a=(c-1)*n;return typeof r=="function"?r(o,c):i===1?o*n:a-o*n}const jst=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Est(t){const e=jst.exec(t);if(!e)return[,];const[,r,n,i]=e;return[`--${r??n}`,i]}const kst=4;function nTe(t,e,r=1){fT(r<=kst,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,i]=Est(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const c=o.trim();return vSe(c)?parseFloat(c):c}return LK(i)?nTe(i,e,r+1):i}const Ast={type:"spring",stiffness:500,damping:25,restSpeed:10},Nst=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Cst={type:"keyframes",duration:.8},Ist={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Pst=(t,{keyframes:e})=>e.length>2?Cst:vj.has(t)?t.startsWith("scale")?Nst(e[1]):Ast:Ist;function sTe(t,e){if(t!=null&&t.inherit&&e){const{inherit:r,...n}=t;return{...e,...n}}return t}function zK(t,e){const r=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return r!==t?sTe(r,t):r}const Rst=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function Lst(t){for(const e in t)if(!Rst.has(e))return!0;return!1}const UK=(t,e,r,n={},i,o)=>c=>{const a=zK(n,t)||{},f=a.delay||n.delay||0;let{elapsed:m=0}=n;m=m-td(f);const y={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-m,onUpdate:w=>{e.set(w),a.onUpdate&&a.onUpdate(w)},onComplete:()=>{c(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:i};Lst(a)||Object.assign(y,Pst(t,y)),y.duration&&(y.duration=td(y.duration)),y.repeatDelay&&(y.repeatDelay=td(y.repeatDelay)),y.from!==void 0&&(y.keyframes[0]=y.from);let v=!1;if((y.type===!1||y.duration===0&&!y.repeatDelay)&&(o9(y),y.delay===0&&(v=!0)),(t0.instantAnimations||t0.skipAnimations||i!=null&&i.shouldSkipAnimations)&&(v=!0,o9(y),y.delay=0),y.allowFlatten=!a.type&&!a.ease,v&&!o&&e.get()!==void 0){const w=NF(y.keyframes,a);if(w!==void 0){ga.update(()=>{y.onUpdate(w),y.onComplete()});return}}return a.isSync?new NO(y):new Tst(y)};function Qie(t){const e=[{},{}];return t==null||t.values.forEach((r,n)=>{e[0][n]=r.get(),e[1][n]=r.getVelocity()}),e}function VK(t,e,r,n){if(typeof e=="function"){const[i,o]=Qie(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]=Qie(n);e=e(r!==void 0?r:t.custom,i,o)}return e}function D_(t,e,r){const n=t.getProps();return VK(n,e,r!==void 0?r:n.custom,t)}const iTe=new Set(["width","height","top","left","right","bottom",...xj]),Jie=30,Mst=t=>!isNaN(parseFloat(t));class Dst{constructor(e,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var o;const i=xu.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=xu.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Mst(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 IK);const n=this.events[e].add(r);return e==="change"?()=>{n(),ga.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=xu.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Jie)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,Jie);return SSe(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 pT(t,e){return new Dst(t,e)}const l9=t=>Array.isArray(t);function Ost(t,e,r){t.hasValue(e)?t.getValue(e).set(r):t.addValue(e,pT(r))}function Fst(t){return l9(t)?t[t.length-1]||0:t}function Bst(t,e){const r=D_(t,e);let{transitionEnd:n={},transition:i={},...o}=r||{};o={...o,...n};for(const c in o){const a=Fst(o[c]);Ost(t,c,a)}}const pc=t=>!!(t&&t.getVelocity);function $st(t){return!!(pc(t)&&t.add)}function c9(t,e){const r=t.getValue("willChange");if($st(r))return r.add(e);if(!r&&t0.WillChange){const n=new t0.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function qK(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const zst="framerAppearId",aTe="data-"+qK(zst);function oTe(t){return t.props[aTe]}function Ust({protectedKeys:t,needsAnimating:e},r){const n=t.hasOwnProperty(r)&&e[r]!==!0;return e[r]=!1,n}function lTe(t,e,{delay:r=0,transitionOverride:n,type:i}={}){let{transition:o,transitionEnd:c,...a}=e;const f=t.getDefaultTransition();o=o?sTe(o,f):f;const m=o==null?void 0:o.reduceMotion;n&&(o=n);const y=[],v=i&&t.animationState&&t.animationState.getState()[i];for(const w in a){const j=t.getValue(w,t.latestValues[w]??null),A=a[w];if(A===void 0||v&&Ust(v,w))continue;const C={delay:r,...zK(o||{},w)},I=j.get();if(I!==void 0&&!j.isAnimating()&&!Array.isArray(A)&&A===I&&!C.velocity){ga.update(()=>j.set(A));continue}let M=!1;if(window.MotionHandoffAnimation){const z=oTe(t);if(z){const q=window.MotionHandoffAnimation(z,w,ga);q!==null&&(C.startTime=q,M=!0)}}c9(t,w);const D=m??t.shouldReduceMotion;j.start(UK(w,j,A,D&&iTe.has(w)?{type:!1}:C,t,M));const F=j.animation;F&&y.push(F)}if(c){const w=()=>ga.update(()=>{c&&Bst(t,c)});y.length?Promise.all(y).then(w):w()}return y}function u9(t,e,r={}){var f;const n=D_(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(lTe(t,n,r)):()=>Promise.resolve(),c=t.variantChildren&&t.variantChildren.size?(m=0)=>{const{delayChildren:y=0,staggerChildren:v,staggerDirection:w}=i;return Vst(t,e,m,y,v,w,r)}:()=>Promise.resolve(),{when:a}=i;if(a){const[m,y]=a==="beforeChildren"?[o,c]:[c,o];return m().then(()=>y())}else return Promise.all([o(),c(r.delay)])}function Vst(t,e,r=0,n=0,i=0,o=1,c){const a=[];for(const f of t.variantChildren)f.notify("AnimationStart",e),a.push(u9(f,e,{...c,delay:r+(typeof n=="function"?0:n)+rTe(t.variantChildren,f,n,i,o)}).then(()=>f.notify("AnimationComplete",e)));return Promise.all(a)}function qst(t,e,r={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const i=e.map(o=>u9(t,o,r));n=Promise.all(i)}else if(typeof e=="string")n=u9(t,e,r);else{const i=typeof e=="function"?D_(t,e,r.custom):e;n=Promise.all(lTe(t,i,r))}return n.then(()=>{t.notify("AnimationComplete",e)})}const Gst={test:t=>t==="auto",parse:t=>t},cTe=t=>e=>e.test(t),uTe=[yj,Dn,Ym,Xy,gnt,pnt,Gst],eae=t=>uTe.find(cTe(t));function Hst(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||bSe(t):!0}const Wst=new Set(["brightness","contrast","saturate","opacity"]);function Kst(t){const[e,r]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=r.match(MK)||[];if(!n)return t;const i=r.replace(n,"");let o=Wst.has(e)?1:0;return n!==r&&(o*=100),e+"("+o+i+")"}const Yst=/\b([a-z-]*)\(.*?\)/gu,d9={...Ff,getAnimatableNone:t=>{const e=t.match(Yst);return e?e.map(Kst).join(" "):t}},h9={...Ff,getAnimatableNone:t=>{const e=Ff.parse(t);return Ff.createTransformer(t)(e.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},tae={...yj,transform:Math.round},Zst={rotate:Xy,rotateX:Xy,rotateY:Xy,rotateZ:Xy,scale:IL,scaleX:IL,scaleY:IL,scaleZ:IL,skew:Xy,skewX:Xy,skewY:Xy,distance:Dn,translateX:Dn,translateY:Dn,translateZ:Dn,x:Dn,y:Dn,z:Dn,perspective:Dn,transformPerspective:Dn,opacity:bN,originX:zie,originY:zie,originZ:Dn},GK={borderWidth:Dn,borderTopWidth:Dn,borderRightWidth:Dn,borderBottomWidth:Dn,borderLeftWidth:Dn,borderRadius:Dn,borderTopLeftRadius:Dn,borderTopRightRadius:Dn,borderBottomRightRadius:Dn,borderBottomLeftRadius:Dn,width:Dn,maxWidth:Dn,height:Dn,maxHeight:Dn,top:Dn,right:Dn,bottom:Dn,left:Dn,inset:Dn,insetBlock:Dn,insetBlockStart:Dn,insetBlockEnd:Dn,insetInline:Dn,insetInlineStart:Dn,insetInlineEnd:Dn,padding:Dn,paddingTop:Dn,paddingRight:Dn,paddingBottom:Dn,paddingLeft:Dn,paddingBlock:Dn,paddingBlockStart:Dn,paddingBlockEnd:Dn,paddingInline:Dn,paddingInlineStart:Dn,paddingInlineEnd:Dn,margin:Dn,marginTop:Dn,marginRight:Dn,marginBottom:Dn,marginLeft:Dn,marginBlock:Dn,marginBlockStart:Dn,marginBlockEnd:Dn,marginInline:Dn,marginInlineStart:Dn,marginInlineEnd:Dn,fontSize:Dn,backgroundPositionX:Dn,backgroundPositionY:Dn,...Zst,zIndex:tae,fillOpacity:bN,strokeOpacity:bN,numOctaves:tae},Xst={...GK,color:il,backgroundColor:il,outlineColor:il,fill:il,stroke:il,borderColor:il,borderTopColor:il,borderRightColor:il,borderBottomColor:il,borderLeftColor:il,filter:d9,WebkitFilter:d9,mask:h9,WebkitMask:h9},dTe=t=>Xst[t],Qst=new Set([d9,h9]);function hTe(t,e){let r=dTe(t);return Qst.has(r)||(r=Ff),r.getAnimatableNone?r.getAnimatableNone(e):void 0}const Jst=new Set(["auto","none","0"]);function eit(t,e,r){let n=0,i;for(;n{e.getValue(f).set(m)}),this.resolveNoneKeyframes()}}function fTe(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 mTe=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function ZM(t){return _Se(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:HK,cancel:Jtr}=LSe(queueMicrotask,!1),hf={x:!1,y:!1};function pTe(){return hf.x||hf.y}function rit(t){return t==="x"||t==="y"?hf[t]?null:(hf[t]=!0,()=>{hf[t]=!1}):hf.x||hf.y?null:(hf.x=hf.y=!0,()=>{hf.x=hf.y=!1})}function gTe(t,e){const r=fTe(t),n=new AbortController,i={passive:!0,...e,signal:n.signal};return[r,i,()=>n.abort()]}function nit(t){return!(t.pointerType==="touch"||pTe())}function sit(t,e,r={}){const[n,i,o]=gTe(t,r);return n.forEach(c=>{let a=!1,f=!1,m;const y=()=>{c.removeEventListener("pointerleave",A)},v=I=>{m&&(m(I),m=void 0),y()},w=I=>{a=!1,window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),f&&(f=!1,v(I))},j=()=>{a=!0,window.addEventListener("pointerup",w,i),window.addEventListener("pointercancel",w,i)},A=I=>{if(I.pointerType!=="touch"){if(a){f=!0;return}v(I)}},C=I=>{if(!nit(I))return;f=!1;const M=e(c,I);typeof M=="function"&&(m=M,c.addEventListener("pointerleave",A,i))};c.addEventListener("pointerenter",C,i),c.addEventListener("pointerdown",j,i)}),o}const yTe=(t,e)=>e?t===e?!0:yTe(t,e.parentElement):!1,WK=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,iit=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function ait(t){return iit.has(t.tagName)||t.isContentEditable===!0}const oit=new Set(["INPUT","SELECT","TEXTAREA"]);function lit(t){return oit.has(t.tagName)||t.isContentEditable===!0}const XM=new WeakSet;function rae(t){return e=>{e.key==="Enter"&&t(e)}}function H6(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const cit=(t,e)=>{const r=t.currentTarget;if(!r)return;const n=rae(()=>{if(XM.has(r))return;H6(r,"down");const i=rae(()=>{H6(r,"up")}),o=()=>H6(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 nae(t){return WK(t)&&!pTe()}const sae=new WeakSet;function uit(t,e,r={}){const[n,i,o]=gTe(t,r),c=a=>{const f=a.currentTarget;if(!nae(a)||sae.has(a))return;XM.add(f),r.stopPropagation&&sae.add(a);const m=e(f,a),y=(j,A)=>{window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",w),XM.has(f)&&XM.delete(f),nae(j)&&typeof m=="function"&&m(j,{success:A})},v=j=>{y(j,f===window||f===document||r.useGlobalTarget||yTe(f,j.target))},w=j=>{y(j,!1)};window.addEventListener("pointerup",v,i),window.addEventListener("pointercancel",w,i)};return n.forEach(a=>{(r.useGlobalTarget?window:a).addEventListener("pointerdown",c,i),ZM(a)&&(a.addEventListener("focus",m=>cit(m,i)),!ait(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function KK(t){return _Se(t)&&"ownerSVGElement"in t}const QM=new WeakMap;let Qy;const xTe=(t,e,r)=>(n,i)=>i&&i[0]?i[0][t+"Size"]:KK(n)&&"getBBox"in n?n.getBBox()[e]:n[r],dit=xTe("inline","width","offsetWidth"),hit=xTe("block","height","offsetHeight");function fit({target:t,borderBoxSize:e}){var r;(r=QM.get(t))==null||r.forEach(n=>{n(t,{get width(){return dit(t,e)},get height(){return hit(t,e)}})})}function mit(t){t.forEach(fit)}function pit(){typeof ResizeObserver>"u"||(Qy=new ResizeObserver(mit))}function git(t,e){Qy||pit();const r=fTe(t);return r.forEach(n=>{let i=QM.get(n);i||(i=new Set,QM.set(n,i)),i.add(e),Qy==null||Qy.observe(n)}),()=>{r.forEach(n=>{const i=QM.get(n);i==null||i.delete(e),i!=null&&i.size||Qy==null||Qy.unobserve(n)})}}const JM=new Set;let eS;function yit(){eS=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};JM.forEach(e=>e(t))},window.addEventListener("resize",eS)}function xit(t){return JM.add(t),eS||yit(),()=>{JM.delete(t),!JM.size&&typeof eS=="function"&&(window.removeEventListener("resize",eS),eS=void 0)}}function iae(t,e){return typeof t=="function"?xit(t):git(t,e)}function vit(t){return KK(t)&&t.tagName==="svg"}const _it=[...uTe,il,Ff],bit=t=>_it.find(cTe(t)),aae=()=>({translate:0,scale:1,origin:0,originPoint:0}),tS=()=>({x:aae(),y:aae()}),oae=()=>({min:0,max:0}),bl=()=>({x:oae(),y:oae()}),wit=new WeakMap;function CF(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function wN(t){return typeof t=="string"||Array.isArray(t)}const YK=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ZK=["initial",...YK];function IF(t){return CF(t.animate)||ZK.some(e=>wN(t[e]))}function vTe(t){return!!(IF(t)||t.variants)}function Sit(t,e,r){for(const n in e){const i=e[n],o=r[n];if(pc(i))t.addValue(n,i);else if(pc(o))t.addValue(n,pT(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,pT(c!==void 0?c:i,{owner:t}))}}for(const n in r)e[n]===void 0&&t.removeValue(n);return e}const f9={current:null},_Te={current:!1},Tit=typeof window<"u";function jit(){if(_Te.current=!0,!!Tit)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>f9.current=t.matches;t.addEventListener("change",e),e()}else f9.current=!1}const lae=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let CO={};function bTe(t){CO=t}function Eit(){return CO}class kit{scrapeMotionValuesFromProps(e,r,n){return{}}constructor({parent:e,props:r,presenceContext:n,reducedMotionConfig:i,skipAnimations:o,blockInitialAnimation:c,visualState:a},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=$K,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 j=xu.now();this.renderScheduledAtthis.bindToMotionValue(o,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(_Te.current||jit(),this.shouldReduceMotion=f9.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(),r0(this.notifyUpdate),r0(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&&tTe.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:a,times:f,ease:m,duration:y}=r.accelerate,v=new JSe({element:this.current,name:e,keyframes:a,times:f,ease:m,duration:td(y)}),w=c(v);this.valueSubscriptions.set(e,()=>{w(),v.cancel()});return}const n=vj.has(e);n&&this.onBindTransform&&this.onBindTransform();const i=r.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&ga.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 CO){const r=CO[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):bl()}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=pT(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"&&(vSe(n)||bSe(n))?n=parseFloat(n):!bit(n)&&Ff.test(r)&&(n=hTe(e,r)),this.setBaseTarget(e,pc(n)?n.get():n)),pc(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=VK(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&&!pc(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 IK),this.events[e].add(r)}notify(e,...r){this.events[e]&&this.events[e].notify(...r)}scheduleRenderMicrotask(){HK.render(this.render)}}class wTe extends kit{constructor(){super(...arguments),this.KeyframeResolver=tit}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;pc(e)&&(this.childSubscription=e.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class j0{constructor(e){this.isMounted=!1,this.node=e}update(){}}function STe({top:t,left:e,right:r,bottom:n}){return{x:{min:e,max:r},y:{min:t,max:n}}}function Ait({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Nit(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 W6(t){return t===void 0||t===1}function m9({scale:t,scaleX:e,scaleY:r}){return!W6(t)||!W6(e)||!W6(r)}function r_(t){return m9(t)||TTe(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function TTe(t){return cae(t.x)||cae(t.y)}function cae(t){return t&&t!=="0%"}function IO(t,e,r){const n=t-r,i=e*n;return r+i}function uae(t,e,r,n,i){return i!==void 0&&(t=IO(t,i,n)),IO(t,r,n)+e}function p9(t,e=0,r=1,n,i){t.min=uae(t.min,e,r,n,i),t.max=uae(t.max,e,r,n,i)}function jTe(t,{x:e,y:r}){p9(t.x,e.translate,e.scale,e.originPoint),p9(t.y,r.translate,r.scale,r.originPoint)}const dae=.999999999999,hae=1.0000000000001;function Cit(t,e,r,n=!1){var a;const i=r.length;if(!i)return;e.x=e.y=1;let o,c;for(let f=0;fdae&&(e.x=1),e.ydae&&(e.y=1)}function Rm(t,e){t.min+=e,t.max+=e}function fae(t,e,r,n,i=.5){const o=Ga(t.min,t.max,i);p9(t,e,r,o,n)}function mae(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function eD(t,e,r){const n=r??t;fae(t.x,mae(e.x,n.x),e.scaleX,e.scale,e.originX),fae(t.y,mae(e.y,n.y),e.scaleY,e.scale,e.originY)}function ETe(t,e){return STe(Nit(t.getBoundingClientRect(),e))}function Iit(t,e,r){const n=ETe(t,r),{scroll:i}=e;return i&&(Rm(n.x,i.offset.x),Rm(n.y,i.offset.y)),n}const Pit={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Rit=xj.length;function Lit(t,e,r){let n="",i=!0;for(let o=0;o{if(!e.target)return t;if(typeof t=="string")if(Dn.test(t))t=parseFloat(t);else return t;const r=pae(t,e.target.x),n=pae(t,e.target.y);return`${r}% ${n}%`}},Mit={correct:(t,{treeScale:e,projectionDelta:r})=>{const n=t,i=Ff.parse(t);if(i.length>5)return n;const o=Ff.createTransformer(t),c=typeof i[0]!="number"?1:0,a=r.x.scale*e.x,f=r.y.scale*e.y;i[0+c]/=a,i[1+c]/=f;const m=Ga(a,f,.5);return typeof i[2+c]=="number"&&(i[2+c]/=m),typeof i[3+c]=="number"&&(i[3+c]/=m),o(i)}},g9={borderRadius:{...pk,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:pk,borderTopRightRadius:pk,borderBottomLeftRadius:pk,borderBottomRightRadius:pk,boxShadow:Mit};function ATe(t,{layout:e,layoutId:r}){return vj.has(t)||t.startsWith("origin")||(e||r!==void 0)&&(!!g9[t]||t==="opacity")}function QK(t,e,r){var c;const n=t.style,i=e==null?void 0:e.style,o={};if(!n)return o;for(const a in n)(pc(n[a])||i&&pc(i[a])||ATe(a,t)||((c=r==null?void 0:r.getValue(a))==null?void 0:c.liveStyle)!==void 0)&&(o[a]=n[a]);return o}function Dit(t){return window.getComputedStyle(t)}class Oit extends wTe{constructor(){super(...arguments),this.type="html",this.renderInstance=kTe}readValueFromInstance(e,r){var n;if(vj.has(r))return(n=this.projection)!=null&&n.isProjecting?r9(r):rst(e,r);{const i=Dit(e),o=(DSe(r)?i.getPropertyValue(r):i[r])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:r}){return ETe(e,r)}build(e,r,n){XK(e,r,n.transformTemplate)}scrapeMotionValuesFromProps(e,r,n){return QK(e,r,n)}}const Fit={offset:"stroke-dashoffset",array:"stroke-dasharray"},Bit={offset:"strokeDashoffset",array:"strokeDasharray"};function $it(t,e,r=1,n=0,i=!0){t.pathLength=1;const o=i?Fit:Bit;t[o.offset]=`${-n}`,t[o.array]=`${e} ${r}`}const zit=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function NTe(t,{attrX:e,attrY:r,attrScale:n,pathLength:i,pathSpacing:o=1,pathOffset:c=0,...a},f,m,y){if(XK(t,a,m),f){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:v,style:w}=t;v.transform&&(w.transform=v.transform,delete v.transform),(w.transform||v.transformOrigin)&&(w.transformOrigin=v.transformOrigin??"50% 50%",delete v.transformOrigin),w.transform&&(w.transformBox=(y==null?void 0:y.transformBox)??"fill-box",delete v.transformBox);for(const j of zit)v[j]!==void 0&&(w[j]=v[j],delete v[j]);e!==void 0&&(v.x=e),r!==void 0&&(v.y=r),n!==void 0&&(v.scale=n),i!==void 0&&$it(v,i,o,c,!1)}const CTe=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"]),ITe=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Uit(t,e,r,n){kTe(t,e,void 0,n);for(const i in e.attrs)t.setAttribute(CTe.has(i)?i:qK(i),e.attrs[i])}function PTe(t,e,r){const n=QK(t,e,r);for(const i in t)if(pc(t[i])||pc(e[i])){const o=xj.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;n[o]=t[i]}return n}class Vit extends wTe{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=bl}getBaseTargetFromProps(e,r){return e[r]}readValueFromInstance(e,r){if(vj.has(r)){const n=dTe(r);return n&&n.default||0}return r=CTe.has(r)?r:qK(r),e.getAttribute(r)}scrapeMotionValuesFromProps(e,r,n){return PTe(e,r,n)}build(e,r,n){NTe(e,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,r,n,i){Uit(e,r,n,i)}mount(e){this.isSVGTag=ITe(e.tagName),super.mount(e)}}const qit=ZK.length;function RTe(t){if(!t)return;if(!t.isControllingVariants){const r=t.parent?RTe(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})=>qst(t,r,n)))}function Kit(t){let e=Wit(t),r=gae(),n=!0,i=!1;const o=m=>(y,v)=>{var j;const w=D_(t,v,m==="exit"?(j=t.presenceContext)==null?void 0:j.custom:void 0);if(w){const{transition:A,transitionEnd:C,...I}=w;y={...y,...I,...C}}return y};function c(m){e=m(t)}function a(m){const{props:y}=t,v=RTe(t.parent)||{},w=[],j=new Set;let A={},C=1/0;for(let M=0;MC&&q,ee=!1;const oe=Array.isArray(z)?z:[z];let de=oe.reduce(o(D),{});H===!1&&(de={});const{prevResolvedValues:ye={}}=F,we={...ye,...de},Le=me=>{Q=!0,j.has(me)&&(ee=!0,j.delete(me)),F.needsAnimating[me]=!0;const ke=t.getValue(me);ke&&(ke.liveStyle=!1)};for(const me in we){const ke=de[me],Pe=ye[me];if(A.hasOwnProperty(me))continue;let Ee=!1;l9(ke)&&l9(Pe)?Ee=!LTe(ke,Pe):Ee=ke!==Pe,Ee?ke!=null?Le(me):j.add(me):ke!==void 0&&j.has(me)?Le(me):F.protectedKeys[me]=!0}F.prevProp=z,F.prevResolvedValues=de,F.isActive&&(A={...A,...de}),(n||i)&&t.blockInitialAnimation&&(Q=!1);const Se=K&&J;Q&&(!Se||ee)&&w.push(...oe.map(me=>{const ke={type:D};if(typeof me=="string"&&(n||i)&&!Se&&t.manuallyAnimateOnMount&&t.parent){const{parent:Pe}=t,Ee=D_(Pe,me);if(Pe.enteringChildren&&Ee){const{delayChildren:xe}=Ee.transition||{};ke.delay=rTe(Pe.enteringChildren,t,xe)}}return{animation:me,options:ke}}))}if(j.size){const M={};if(typeof y.initial!="boolean"){const D=D_(t,Array.isArray(y.initial)?y.initial[0]:y.initial);D&&D.transition&&(M.transition=D.transition)}j.forEach(D=>{const F=t.getBaseTarget(D),z=t.getValue(D);z&&(z.liveStyle=!0),M[D]=F??null}),w.push({animation:M})}let I=!!w.length;return n&&(y.initial===!1||y.initial===y.animate)&&!t.manuallyAnimateOnMount&&(I=!1),n=!1,i=!1,I?e(w):Promise.resolve()}function f(m,y){var w;if(r[m].isActive===y)return Promise.resolve();(w=t.variantChildren)==null||w.forEach(j=>{var A;return(A=j.animationState)==null?void 0:A.setActive(m,y)}),r[m].isActive=y;const v=a(m);for(const j in r)r[j].protectedKeys={};return v}return{animateChanges:a,setActive:f,setAnimateFunction:c,getState:()=>r,reset:()=>{r=gae(),i=!0}}}function Yit(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!LTe(e,t):!1}function qv(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function gae(){return{animate:qv(!0),whileInView:qv(),whileHover:qv(),whileTap:qv(),whileDrag:qv(),whileFocus:qv(),exit:qv()}}function y9(t,e){t.min=e.min,t.max=e.max}function of(t,e){y9(t.x,e.x),y9(t.y,e.y)}function yae(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const MTe=1e-4,Zit=1-MTe,Xit=1+MTe,DTe=.01,Qit=0-DTe,Jit=0+DTe;function vu(t){return t.max-t.min}function eat(t,e,r){return Math.abs(t-e)<=r}function xae(t,e,r,n=.5){t.origin=n,t.originPoint=Ga(e.min,e.max,t.origin),t.scale=vu(r)/vu(e),t.translate=Ga(r.min,r.max,t.origin)-t.originPoint,(t.scale>=Zit&&t.scale<=Xit||isNaN(t.scale))&&(t.scale=1),(t.translate>=Qit&&t.translate<=Jit||isNaN(t.translate))&&(t.translate=0)}function _A(t,e,r,n){xae(t.x,e.x,r.x,n?n.originX:void 0),xae(t.y,e.y,r.y,n?n.originY:void 0)}function vae(t,e,r,n=0){const i=n?Ga(r.min,r.max,n):r.min;t.min=i+e.min,t.max=t.min+vu(e)}function tat(t,e,r,n){vae(t.x,e.x,r.x,n==null?void 0:n.x),vae(t.y,e.y,r.y,n==null?void 0:n.y)}function _ae(t,e,r,n=0){const i=n?Ga(r.min,r.max,n):r.min;t.min=e.min-i,t.max=t.min+vu(e)}function PO(t,e,r,n){_ae(t.x,e.x,r.x,n==null?void 0:n.x),_ae(t.y,e.y,r.y,n==null?void 0:n.y)}function bae(t,e,r,n,i){return t-=e,t=IO(t,1/r,n),i!==void 0&&(t=IO(t,1/i,n)),t}function rat(t,e=0,r=1,n=.5,i,o=t,c=t){if(Ym.test(e)&&(e=parseFloat(e),e=Ga(c.min,c.max,e/100)-c.min),typeof e!="number")return;let a=Ga(o.min,o.max,n);t===o&&(a-=e),t.min=bae(t.min,e,r,a,i),t.max=bae(t.max,e,r,a,i)}function wae(t,e,[r,n,i],o,c){rat(t,e[r],e[n],e[i],e.scale,o,c)}const nat=["x","scaleX","originX"],sat=["y","scaleY","originY"];function Sae(t,e,r,n){wae(t.x,e,nat,r?r.x:void 0,n?n.x:void 0),wae(t.y,e,sat,r?r.y:void 0,n?n.y:void 0)}function Tae(t){return t.translate===0&&t.scale===1}function OTe(t){return Tae(t.x)&&Tae(t.y)}function jae(t,e){return t.min===e.min&&t.max===e.max}function iat(t,e){return jae(t.x,e.x)&&jae(t.y,e.y)}function Eae(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function FTe(t,e){return Eae(t.x,e.x)&&Eae(t.y,e.y)}function kae(t){return vu(t.x)/vu(t.y)}function Aae(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function km(t){return[t("x"),t("y")]}function aat(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:m,rotate:y,rotateX:v,rotateY:w,skewX:j,skewY:A}=r;m&&(n=`perspective(${m}px) ${n}`),y&&(n+=`rotate(${y}deg) `),v&&(n+=`rotateX(${v}deg) `),w&&(n+=`rotateY(${w}deg) `),j&&(n+=`skewX(${j}deg) `),A&&(n+=`skewY(${A}deg) `)}const a=t.x.scale*e.x,f=t.y.scale*e.y;return(a!==1||f!==1)&&(n+=`scale(${a}, ${f})`),n||"none"}const BTe=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],oat=BTe.length,Nae=t=>typeof t=="string"?parseFloat(t):t,Cae=t=>typeof t=="number"||Dn.test(t);function lat(t,e,r,n,i,o){i?(t.opacity=Ga(0,r.opacity??1,cat(n)),t.opacityExit=Ga(e.opacity??1,0,uat(n))):o&&(t.opacity=Ga(e.opacity??1,r.opacity??1,n));for(let c=0;cne?1:r(_N(t,e,n))}function dat(t,e,r){const n=pc(t)?t:pT(t);return n.start(UK("",n,e,r)),n.animation}function SN(t,e,r,n={passive:!0}){return t.addEventListener(e,r,n),()=>t.removeEventListener(e,r)}const hat=(t,e)=>t.depth-e.depth;class fat{constructor(){this.children=[],this.isDirty=!1}add(e){CK(this.children,e),this.isDirty=!0}remove(e){jO(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(hat),this.isDirty=!1,this.children.forEach(e)}}function mat(t,e){const r=xu.now(),n=({timestamp:i})=>{const o=i-r;o>=e&&(r0(n),t(o-e))};return ga.setup(n,!0),()=>r0(n)}function tD(t){return pc(t)?t.get():t}class pat{constructor(){this.members=[]}add(e){CK(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&&(jO(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(jO(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 rD={hasAnimatedSinceResize:!0,hasEverUpdated:!1},K6=["","X","Y","Z"],gat=1e3;let yat=0;function Y6(t,e,r,n){const{latestValues:i}=e;i[t]&&(r[t]=i[t],e.setStaticValue(t,0),n&&(n[t]=0))}function zTe(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const r=oTe(e);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:i,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(r,"transform",ga,!(i||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&zTe(n)}function UTe({attachResizeListener:t,defaultParent:e,measureScroll:r,checkIsScrollRoot:n,resetTransform:i}){return class{constructor(c={},a=e==null?void 0:e()){this.id=yat++,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(_at),this.nodes.forEach(Eat),this.nodes.forEach(kat),this.nodes.forEach(bat)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=c,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let f=0;fthis.root.updateBlockedByResize=!1;ga.read(()=>{v=window.innerWidth}),t(c,()=>{const j=window.innerWidth;j!==v&&(v=j,this.root.updateBlockedByResize=!0,y&&y(),y=mat(w,250),rD.hasAnimatedSinceResize&&(rD.hasAnimatedSinceResize=!1,this.nodes.forEach(Lae)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&m&&(a||f)&&this.addEventListener("didUpdate",({delta:y,hasLayoutChanged:v,hasRelativeLayoutChanged:w,layout:j})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const A=this.options.transition||m.getDefaultTransition()||Pat,{onLayoutAnimationStart:C,onLayoutAnimationComplete:I}=m.getProps(),M=!this.targetLayout||!FTe(this.targetLayout,j),D=!v&&w;if(this.options.layoutRoot||this.resumeFrom||D||v&&(M||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const F={...zK(A,"layout"),onPlay:C,onComplete:I};(m.shouldReduceMotion||this.options.layoutRoot)&&(F.delay=0,F.type=!1),this.startAnimation(F),this.setAnimationOrigin(y,D)}else v||Lae(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=j})}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(),r0(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(Aat),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&&zTe(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&&!vu(this.snapshot.measuredBox.x)&&!vu(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 q=z/1e3;Mae(v.x,c.x,q),Mae(v.y,c.y,q),this.setTargetDelta(v),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(PO(w,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Cat(this.relativeTarget,this.relativeTargetOrigin,w,q),F&&iat(this.relativeTarget,F)&&(this.isProjectionDirty=!1),F||(F=bl()),of(F,this.relativeTarget)),C&&(this.animationValues=y,lat(y,m,this.latestValues,q,D,M)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=q},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(c){var a,f,m;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(m=(f=this.resumingFrom)==null?void 0:f.currentAnimation)==null||m.stop(),this.pendingAnimation&&(r0(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ga.update(()=>{rD.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=pT(0)),this.motionValue.jump(0,!1),this.currentAnimation=dat(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(gat),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:a,target:f,layout:m,latestValues:y}=c;if(!(!a||!f||!m)){if(this!==c&&this.layout&&m&&VTe(this.options.animationType,this.layout.layoutBox,m.layoutBox)){f=this.target||bl();const v=vu(this.layout.layoutBox.x);f.x.min=c.target.x.min,f.x.max=f.x.min+v;const w=vu(this.layout.layoutBox.y);f.y.min=c.target.y.min,f.y.max=f.y.min+w}of(a,f),eD(a,y),_A(this.projectionDeltaWithTransform,this.layoutCorrected,a,y)}}registerSharedNode(c,a){this.sharedNodes.has(c)||this.sharedNodes.set(c,new pat),this.sharedNodes.get(c).add(a);const m=a.options.initialPromotionConfig;a.promote({transition:m?m.transition:void 0,preserveFollowOpacity:m&&m.shouldPreserveFollowOpacity?m.shouldPreserveFollowOpacity(a):void 0})}isLead(){const c=this.getStack();return c?c.lead===this:!0}getLead(){var a;const{layoutId:c}=this.options;return c?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:c}=this.options;return c?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:c}=this.options;if(c)return this.root.sharedNodes.get(c)}promote({needsReset:c,transition:a,preserveFollowOpacity:f}={}){const m=this.getStack();m&&m.promote(this,f),c&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const c=this.getStack();return c?c.relegate(this):!1}resetSkewAndRotation(){const{visualElement:c}=this.options;if(!c)return;let a=!1;const{latestValues:f}=c;if((f.z||f.rotate||f.rotateX||f.rotateY||f.rotateZ||f.skewX||f.skewY)&&(a=!0),!a)return;const m={};f.z&&Y6("z",c,m,this.animationValues);for(let y=0;y{var a;return(a=c.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(Pae),this.root.sharedNodes.clear()}}}function xat(t){t.updateLayout()}function vat(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")km(v=>{const w=c?e.measuredBox[v]:e.layoutBox[v],j=vu(w);w.min=n[v].min,w.max=w.min+j});else if(o==="x"||o==="y"){const v=o==="x"?"y":"x";y9(c?e.measuredBox[v]:e.layoutBox[v],n[v])}else VTe(o,e.layoutBox,n)&&km(v=>{const w=c?e.measuredBox[v]:e.layoutBox[v],j=vu(n[v]);w.max=w.min+j,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[v].max=t.relativeTarget[v].min+j)});const a=tS();_A(a,n,e.layoutBox);const f=tS();c?_A(f,t.applyTransform(i,!0),e.measuredBox):_A(f,n,e.layoutBox);const m=!OTe(a);let y=!1;if(!t.resumeFrom){const v=t.getClosestProjectingParent();if(v&&!v.resumeFrom){const{snapshot:w,layout:j}=v;if(w&&j){const A=t.options.layoutAnchor||void 0,C=bl();PO(C,e.layoutBox,w.layoutBox,A);const I=bl();PO(I,n,j.layoutBox,A),FTe(C,I)||(y=!0),v.options.layoutRoot&&(t.relativeTarget=I,t.relativeTargetOrigin=C,t.relativeParent=v)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:f,layoutDelta:a,hasLayoutChanged:m,hasRelativeLayoutChanged:y})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function _at(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 bat(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function wat(t){t.clearSnapshot()}function Pae(t){t.clearMeasurements()}function Sat(t){t.isLayoutDirty=!0,t.updateLayout()}function Rae(t){t.isLayoutDirty=!1}function Tat(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function jat(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Lae(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Eat(t){t.resolveTargetDelta()}function kat(t){t.calcProjection()}function Aat(t){t.resetSkewAndRotation()}function Nat(t){t.removeLeadSnapshot()}function Mae(t,e,r){t.translate=Ga(e.translate,0,r),t.scale=Ga(e.scale,1,r),t.origin=e.origin,t.originPoint=e.originPoint}function Dae(t,e,r,n){t.min=Ga(e.min,r.min,n),t.max=Ga(e.max,r.max,n)}function Cat(t,e,r,n){Dae(t.x,e.x,r.x,n),Dae(t.y,e.y,r.y,n)}function Iat(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Pat={duration:.45,ease:[.4,0,.1,1]},Oae=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Fae=Oae("applewebkit/")&&!Oae("chrome/")?Math.round:Ah;function Bae(t){t.min=Fae(t.min),t.max=Fae(t.max)}function Rat(t){Bae(t.x),Bae(t.y)}function VTe(t,e,r){return t==="position"||t==="preserve-aspect"&&!eat(kae(e),kae(r),.2)}function Lat(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Mat=UTe({attachResizeListener:(t,e)=>SN(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}),Z6={current:void 0},qTe=UTe({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Z6.current){const t=new Mat({});t.mount(window),t.setOptions({layoutScroll:!0}),Z6.current=t}return Z6.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),JK=N.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function $ae(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Dat(...t){return e=>{let r=!1;const n=t.map(i=>{const o=$ae(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{width:j,height:A,top:C,left:I,right:M,bottom:D}=f.current;if(e||o===!1||!a.current||!j||!A)return;const F=r==="left"?`left: ${I}`:`right: ${M}`,z=n==="bottom"?`bottom: ${D}`:`top: ${C}`;a.current.dataset.motionPopId=c;const q=document.createElement("style");m&&(q.nonce=m);const H=i??document.head;return H.appendChild(q),q.sheet&&q.sheet.insertRule(` [data-motion-pop-id="${c}"] { position: absolute !important; width: ${j}px !important; height: ${A}px !important; ${F}px !important; ${z}px !important; } `),()=>{var K;(K=a.current)==null||K.removeAttribute("data-motion-pop-id"),H.contains(q)&&H.removeChild(q)}},[e]),s.jsx(Fat,{isPresent:e,childRef:a,sizeRef:f,pop:o,children:o===!1?t:N.cloneElement(t,{ref:v})})}const $at=({children:t,initial:e,isPresent:r,onExitComplete:n,custom:i,presenceAffectsLayout:o,mode:c,anchorX:a,anchorY:f,root:m})=>{const y=NK(zat),v=N.useId();let w=!0,j=N.useMemo(()=>(w=!1,{id:v,initial:e,isPresent:r,custom:i,onExitComplete:A=>{y.set(A,!0);for(const C of y.values())if(!C)return;n&&n()},register:A=>(y.set(A,!1),()=>y.delete(A))}),[r,y,n]);return o&&w&&(j={...j}),N.useMemo(()=>{y.forEach((A,C)=>y.set(C,!1))},[r]),N.useEffect(()=>{!r&&!y.size&&n&&n()},[r]),t=s.jsx(Bat,{pop:c==="popLayout",isPresent:r,anchorX:a,anchorY:f,root:m,children:t}),s.jsx(kF.Provider,{value:j,children:t})};function zat(){return new Map}function GTe(t=!0){const e=N.useContext(kF);if(e===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:i}=e,o=N.useId();N.useEffect(()=>{if(t)return i(o)},[t]);const c=N.useCallback(()=>t&&n&&n(o),[o,n,t]);return!r&&n?[!1,c]:[!0]}const PL=t=>t.key||"";function zae(t){const e=[];return N.Children.forEach(t,r=>{N.isValidElement(r)&&e.push(r)}),e}const HTe=({children:t,custom:e,initial:r=!0,onExitComplete:n,presenceAffectsLayout:i=!0,mode:o="sync",propagate:c=!1,anchorX:a="left",anchorY:f="top",root:m})=>{const[y,v]=GTe(c),w=N.useMemo(()=>zae(t),[t]),j=c&&!y?[]:w.map(PL),A=N.useRef(!0),C=N.useRef(w),I=NK(()=>new Map),M=N.useRef(new Set),[D,F]=N.useState(w),[z,q]=N.useState(w);xSe(()=>{A.current=!1,C.current=w;for(let J=0;J{const Q=PL(J),ee=c&&!y?!1:w===z||j.includes(Q),oe=()=>{if(M.current.has(Q))return;if(I.has(Q))M.current.add(Q),I.set(Q,!0);else return;let de=!0;I.forEach(ye=>{ye||(de=!1)}),de&&(K==null||K(),q(C.current),c&&(v==null||v()),n&&n())};return s.jsx($at,{isPresent:ee,initial:!A.current||r?void 0:!1,custom:e,presenceAffectsLayout:i,mode:o,root:m,onExitComplete:ee?void 0:oe,anchorX:a,anchorY:f,children:J},Q)})})},WTe=N.createContext({strict:!1}),Uae={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 Vae=!1;function Uat(){if(Vae)return;const t={};for(const e in Uae)t[e]={isEnabled:r=>Uae[e].some(n=>!!r[n])};bTe(t),Vae=!0}function KTe(){return Uat(),Eit()}function Vat(t){const e=KTe();for(const r in t)e[r]={...e[r],...t[r]};bTe(e)}const qat=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 RO(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||qat.has(t)}let YTe=t=>!RO(t);function Gat(t){typeof t=="function"&&(YTe=e=>e.startsWith("on")?!RO(e):t(e))}try{Gat(require("@emotion/is-prop-valid").default)}catch{}function Hat(t,e,r){const n={};for(const i in t)i==="values"&&typeof t.values=="object"||pc(t[i])||(YTe(i)||r===!0&&RO(i)||!e&&!RO(i)||t.draggable&&i.startsWith("onDrag"))&&(n[i]=t[i]);return n}const PF=N.createContext({});function Wat(t,e){if(IF(t)){const{initial:r,animate:n}=t;return{initial:r===!1||wN(r)?r:void 0,animate:wN(n)?n:void 0}}return t.inherit!==!1?e:{}}function Kat(t){const{initial:e,animate:r}=Wat(t,N.useContext(PF));return N.useMemo(()=>({initial:e,animate:r}),[qae(e),qae(r)])}function qae(t){return Array.isArray(t)?t.join(" "):t}const eY=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ZTe(t,e,r){for(const n in e)!pc(e[n])&&!ATe(n,r)&&(t[n]=e[n])}function Yat({transformTemplate:t},e){return N.useMemo(()=>{const r=eY();return XK(r,e,t),Object.assign({},r.vars,r.style)},[e])}function Zat(t,e){const r=t.style||{},n={};return ZTe(n,r,t),Object.assign(n,Yat(t,e)),n}function Xat(t,e){const r={},n=Zat(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 XTe=()=>({...eY(),attrs:{}});function Qat(t,e,r,n){const i=N.useMemo(()=>{const o=XTe();return NTe(o,e,ITe(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};ZTe(o,t.style,t),i.style={...o,...i.style}}return i}const Jat=["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 tY(t){return typeof t!="string"||t.includes("-")?!1:!!(Jat.indexOf(t)>-1||/[A-Z]/u.test(t))}function eot(t,e,r,{latestValues:n},i,o=!1,c){const f=(c??tY(t)?Qat:Xat)(e,n,i,t),m=Hat(e,typeof t=="string",o),y=t!==N.Fragment?{...m,...f,ref:r}:{},{children:v}=e,w=N.useMemo(()=>pc(v)?v.get():v,[v]);return N.createElement(t,{...y,children:w})}function tot({scrapeMotionValuesFromProps:t,createRenderState:e},r,n,i){return{latestValues:rot(r,n,i,t),renderState:e()}}function rot(t,e,r,n){const i={},o=n(t,{});for(const w in o)i[w]=tD(o[w]);let{initial:c,animate:a}=t;const f=IF(t),m=vTe(t);e&&m&&!f&&t.inherit!==!1&&(c===void 0&&(c=e.initial),a===void 0&&(a=e.animate));let y=r?r.initial===!1:!1;y=y||c===!1;const v=y?a:c;if(v&&typeof v!="boolean"&&!CF(v)){const w=Array.isArray(v)?v:[v];for(let j=0;j(e,r)=>{const n=N.useContext(PF),i=N.useContext(kF),o=()=>tot(t,e,n,i);return r?o():NK(o)},not=QTe({scrapeMotionValuesFromProps:QK,createRenderState:eY}),sot=QTe({scrapeMotionValuesFromProps:PTe,createRenderState:XTe}),iot=Symbol.for("motionComponentSymbol");function aot(t,e,r){const n=N.useRef(r);N.useInsertionEffect(()=>{n.current=r});const i=N.useRef(null);return N.useCallback(o=>{var a;o&&((a=t.onMount)==null||a.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 JTe=N.createContext({});function D1(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function oot(t,e,r,n,i,o){var F,z;const{visualElement:c}=N.useContext(PF),a=N.useContext(WTe),f=N.useContext(kF),m=N.useContext(JK),y=m.reducedMotion,v=m.skipAnimations,w=N.useRef(null),j=N.useRef(!1);n=n||a.renderer,!w.current&&n&&(w.current=n(t,{visualState:e,parent:c,props:r,presenceContext:f,blockInitialAnimation:f?f.initial===!1:!1,reducedMotionConfig:y,skipAnimations:v,isSVG:o}),j.current&&w.current&&(w.current.manuallyAnimateOnMount=!0));const A=w.current,C=N.useContext(JTe);A&&!A.projection&&i&&(A.type==="html"||A.type==="svg")&&lot(w.current,r,i,C);const I=N.useRef(!1);N.useInsertionEffect(()=>{A&&I.current&&A.update(r,f)});const M=r[aTe],D=N.useRef(!!M&&typeof window<"u"&&!((F=window.MotionHandoffIsComplete)!=null&&F.call(window,M))&&((z=window.MotionHasOptimisedAnimation)==null?void 0:z.call(window,M)));return xSe(()=>{j.current=!0,A&&(I.current=!0,window.MotionIsMounted=!0,A.updateFeatures(),A.scheduleRenderMicrotask(),D.current&&A.animationState&&A.animationState.animateChanges())}),N.useEffect(()=>{A&&(!D.current&&A.animationState&&A.animationState.animateChanges(),D.current&&(queueMicrotask(()=>{var q;(q=window.MotionHandoffMarkAsComplete)==null||q.call(window,M)}),D.current=!1),A.enteringChildren=void 0)}),A}function lot(t,e,r,n){const{layoutId:i,layout:o,drag:c,dragConstraints:a,layoutScroll:f,layoutRoot:m,layoutAnchor:y,layoutCrossfade:v}=e;t.projection=new r(t.latestValues,e["data-framer-portal-id"]?void 0:eje(t.parent)),t.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!c||a&&D1(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:v,layoutScroll:f,layoutRoot:m,layoutAnchor:y})}function eje(t){if(t)return t.options.allowProjection!==!1?t.projection:eje(t.parent)}function X6(t,{forwardMotionProps:e=!1,type:r}={},n,i){n&&Vat(n);const o=r?r==="svg":tY(t),c=o?sot:not;function a(m,y){let v;const w={...N.useContext(JK),...m,layoutId:cot(m)},{isStatic:j}=w,A=Kat(m),C=c(m,j);if(!j&&typeof window<"u"){uot();const I=dot(w);v=I.MeasureLayout,A.visualElement=oot(t,C,w,i,I.ProjectionNode,o)}return s.jsxs(PF.Provider,{value:A,children:[v&&A.visualElement?s.jsx(v,{visualElement:A.visualElement,...w}):null,eot(t,m,aot(C,A.visualElement,y),C,j,e,o)]})}a.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const f=N.forwardRef(a);return f[iot]=t,f}function cot({layoutId:t}){const e=N.useContext(AK).id;return e&&t!==void 0?e+"-"+t:t}function uot(t,e){N.useContext(WTe).strict}function dot(t){const e=KTe(),{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 hot(t,e){if(typeof Proxy>"u")return X6;const r=new Map,n=(o,c)=>X6(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,X6(c,void 0,t,e)),r.get(c))})}const fot=(t,e)=>e.isSVG??tY(t)?new Vit(e):new Oit(e,{allowProjection:t!==N.Fragment});class mot extends j0{constructor(e){super(e),e.animationState||(e.animationState=Kit(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();CF(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 pot=0;class got extends j0{constructor(){super(...arguments),this.id=pot++,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:a}=this.node.getProps();if(typeof c=="string"){const f=D_(this.node,c,a);if(f){const{transition:m,transitionEnd:y,...v}=f;for(const w in v)(o=this.node.getValue(w))==null||o.jump(v[w])}}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 yot={animation:{Feature:mot},exit:{Feature:got}};function sI(t){return{point:{x:t.pageX,y:t.pageY}}}const xot=t=>e=>WK(e)&&t(e,sI(e));function bA(t,e,r,n){return SN(t,e,xot(r),n)}const tje=({current:t})=>t?t.ownerDocument.defaultView:null,Gae=(t,e)=>Math.abs(t-e);function vot(t,e){const r=Gae(t.x,e.x),n=Gae(t.y,e.y);return Math.sqrt(r**2+n**2)}const Hae=new Set(["auto","scroll"]);class rje{constructor(e,r,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:o=!1,distanceThreshold:c=3,element:a}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=j=>{this.handleScroll(j.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=RL(this.lastRawMoveEventInfo,this.transformPagePoint));const j=Q6(this.lastMoveEventInfo,this.history),A=this.startEvent!==null,C=vot(j.offset,{x:0,y:0})>=this.distanceThreshold;if(!A&&!C)return;const{point:I}=j,{timestamp:M}=sc;this.history.push({...I,timestamp:M});const{onStart:D,onMove:F}=this.handlers;A||(D&&D(this.lastMoveEvent,j),this.startEvent=this.lastMoveEvent),F&&F(this.lastMoveEvent,j)},this.handlePointerMove=(j,A)=>{this.lastMoveEvent=j,this.lastRawMoveEventInfo=A,this.lastMoveEventInfo=RL(A,this.transformPagePoint),ga.update(this.updatePoint,!0)},this.handlePointerUp=(j,A)=>{this.end();const{onEnd:C,onSessionEnd:I,resumeAnimation:M}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&M&&M(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const D=Q6(j.type==="pointercancel"?this.lastMoveEventInfo:RL(A,this.transformPagePoint),this.history);this.startEvent&&C&&C(j,D),I&&I(j,D)},!WK(e))return;this.dragSnapToOrigin=o,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=c,this.contextWindow=i||window;const f=sI(e),m=RL(f,this.transformPagePoint),{point:y}=m,{timestamp:v}=sc;this.history=[{...y,timestamp:v}];const{onSessionStart:w}=r;w&&w(e,Q6(m,this.history)),this.removeListeners=tI(bA(this.contextWindow,"pointermove",this.handlePointerMove),bA(this.contextWindow,"pointerup",this.handlePointerUp),bA(this.contextWindow,"pointercancel",this.handlePointerUp)),a&&this.startScrollTracking(a)}startScrollTracking(e){let r=e.parentElement;for(;r;){const n=getComputedStyle(r);(Hae.has(n.overflowX)||Hae.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),ga.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),r0(this.updatePoint)}}function RL(t,e){return e?{point:e(t.point)}:t}function Wae(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Q6({point:t},e){return{point:t,delta:Wae(t,nje(e)),offset:Wae(t,_ot(e)),velocity:bot(e,.1)}}function _ot(t){return t[0]}function nje(t){return t[t.length-1]}function bot(t,e){if(t.length<2)return{x:0,y:0};let r=t.length-1,n=null;const i=nje(t);for(;r>=0&&(n=t[r],!(i.timestamp-n.timestamp>td(e)));)r--;if(!n)return{x:0,y:0};n===t[0]&&t.length>2&&i.timestamp-n.timestamp>td(e)*2&&(n=t[1]);const o=Sh(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 wot(t,{min:e,max:r},n){return e!==void 0&&tr&&(t=n?Ga(r,t,n.max):Math.min(t,r)),t}function Kae(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 Sot(t,{top:e,left:r,bottom:n,right:i}){return{x:Kae(t.x,r,i),y:Kae(t.y,e,n)}}function Yae(t,e){let r=e.min-t.min,n=e.max-t.max;return e.max-e.minn?r=_N(e.min,e.max-n,t.min):n>i&&(r=_N(t.min,t.max-i,e.min)),np(0,1,r)}function Eot(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 x9=.35;function kot(t=x9){return t===!1?t=0:t===!0&&(t=x9),{x:Zae(t,"left","right"),y:Zae(t,"top","bottom")}}function Zae(t,e,r){return{min:Xae(t,e),max:Xae(t,r)}}function Xae(t,e){return typeof t=="number"?t:t[e]||0}const Aot=new WeakMap;class Not{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=bl(),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=v=>{r&&this.snapToCursor(sI(v).point),this.stopAnimation()},c=(v,w)=>{const{drag:j,dragPropagation:A,onDragStart:C}=this.getProps();if(j&&!A&&(this.openDragLock&&this.openDragLock(),this.openDragLock=rit(j),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),km(M=>{let D=this.getAxisMotionValue(M).get()||0;if(Ym.test(D)){const{projection:F}=this.visualElement;if(F&&F.layout){const z=F.layout.layoutBox[M];z&&(D=vu(z)*(parseFloat(D)/100))}}this.originPoint[M]=D}),C&&ga.update(()=>C(v,w),!1,!0),c9(this.visualElement,"transform");const{animationState:I}=this.visualElement;I&&I.setActive("whileDrag",!0)},a=(v,w)=>{this.latestPointerEvent=v,this.latestPanInfo=w;const{dragPropagation:j,dragDirectionLock:A,onDirectionLock:C,onDrag:I}=this.getProps();if(!j&&!this.openDragLock)return;const{offset:M}=w;if(A&&this.currentDirection===null){this.currentDirection=Iot(M),this.currentDirection!==null&&C&&C(this.currentDirection);return}this.updateAxis("x",w.point,M),this.updateAxis("y",w.point,M),this.visualElement.render(),I&&ga.update(()=>I(v,w),!1,!0)},f=(v,w)=>{this.latestPointerEvent=v,this.latestPanInfo=w,this.stop(v,w),this.latestPointerEvent=null,this.latestPanInfo=null},m=()=>{const{dragSnapToOrigin:v}=this.getProps();(v||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:y}=this.getProps();this.panSession=new rje(e,{onSessionStart:o,onStart:c,onMove:a,onSessionEnd:f,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:n,contextWindow:tje(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:a}=this.getProps();a&&ga.postRender(()=>a(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||!LL(e,i,this.currentDirection))return;const o=this.getAxisMotionValue(e);let c=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(c=wot(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&&D1(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=Sot(n.layoutBox,e):this.constraints=!1,this.elastic=kot(r),i!==this.constraints&&!D1(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&km(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=Eot(n.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:r}=this.getProps();if(!e||!D1(e))return!1;const n=e.current;fT(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=Iit(n,i.root,this.visualElement.getTransformPagePoint());let c=Tot(i.layout.layoutBox,o);if(r){const a=r(Ait(c));this.hasMutatedConstraints=!!a,a&&(c=STe(a))}return c}startAnimation(e){const{drag:r,dragMomentum:n,dragElastic:i,dragTransition:o,dragSnapToOrigin:c,onDragTransitionEnd:a}=this.getProps(),f=this.constraints||{},m=km(y=>{if(!LL(y,r,this.currentDirection))return;let v=f&&f[y]||{};(c===!0||c===y)&&(v={min:0,max:0});const w=i?200:1e6,j=i?40:1e7,A={type:"inertia",velocity:n?e[y]:0,bounceStiffness:w,bounceDamping:j,timeConstant:750,restDelta:1,restSpeed:10,...o,...v};return this.startAxisValueAnimation(y,A)});return Promise.all(m).then(a)}startAxisValueAnimation(e,r){const n=this.getAxisMotionValue(e);return c9(this.visualElement,e),n.start(UK(e,n,0,r,this.visualElement,!1))}stopAnimation(){km(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){km(r=>{const{drag:n}=this.getProps();if(!LL(r,n,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(r);if(i&&i.layout){const{min:c,max:a}=i.layout.layoutBox[r],f=o.get()||0;o.set(e[r]-Ga(c,a,.5)+f)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!D1(r)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};km(c=>{const a=this.getAxisMotionValue(c);if(a&&this.constraints!==!1){const f=a.get();i[c]=jot({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(),km(c=>{if(!LL(c,e,null))return;const a=this.getAxisMotionValue(c),{min:f,max:m}=this.constraints[c];a.set(Ga(f,m,i[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Aot.set(this.visualElement,this);const e=this.visualElement.current,r=bA(e,"pointerdown",m=>{const{drag:y,dragListener:v=!0}=this.getProps(),w=m.target,j=w!==e&&lit(w);y&&v&&!j&&this.start(m)});let n;const i=()=>{const{dragConstraints:m}=this.getProps();D1(m)&&m.current&&(this.constraints=this.resolveRefConstraints(),n||(n=Cot(e,m.current,()=>this.scalePositionWithinConstraints())))},{projection:o}=this.visualElement,c=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),ga.read(i);const a=SN(window,"resize",()=>this.scalePositionWithinConstraints()),f=o.addEventListener("didUpdate",({delta:m,hasLayoutChanged:y})=>{this.isDragging&&y&&(km(v=>{const w=this.getAxisMotionValue(v);w&&(this.originPoint[v]+=m[v].translate,w.set(w.get()+m[v].translate))}),this.visualElement.render())});return()=>{a(),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=x9,dragMomentum:a=!0}=e;return{...e,drag:r,dragDirectionLock:n,dragPropagation:i,dragConstraints:o,dragElastic:c,dragMomentum:a}}}function Qae(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function Cot(t,e,r){const n=iae(t,Qae(r)),i=iae(e,Qae(r));return()=>{n(),i()}}function LL(t,e,r){return(e===!0||e===t)&&(r===null||r===t)}function Iot(t,e=10){let r=null;return Math.abs(t.y)>e?r="y":Math.abs(t.x)>e&&(r="x"),r}class Pot extends j0{constructor(e){super(e),this.removeGroupControls=Ah,this.removeListeners=Ah,this.controls=new Not(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ah}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 J6=t=>(e,r)=>{t&&ga.update(()=>t(e,r),!1,!0)};class Rot extends j0{constructor(){super(...arguments),this.removePointerDownListener=Ah}onPointerDown(e){this.session=new rje(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:tje(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:r,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:J6(e),onStart:J6(r),onMove:J6(n),onEnd:(o,c)=>{delete this.session,i&&ga.postRender(()=>i(o,c))}}}mount(){this.removePointerDownListener=bA(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 eU=!1;class Lot extends N.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),eU&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),rD.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}),eU=!0,i||e.layoutDependency!==r||r===void 0||e.isPresent!==o?c.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?c.promote():c.relegate()||ga.postRender(()=>{const a=c.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:r}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),HK.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:i}=e;eU=!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 sje(t){const[e,r]=GTe(),n=N.useContext(AK);return s.jsx(Lot,{...t,layoutGroup:n,switchLayoutGroup:N.useContext(JTe),isPresent:e,safeToRemove:r})}const Mot={pan:{Feature:Rot},drag:{Feature:Pot,ProjectionNode:qTe,MeasureLayout:sje}};function Jae(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&&ga.postRender(()=>o(e,sI(e)))}class Dot extends j0{mount(){const{current:e}=this.node;e&&(this.unmount=sit(e,(r,n)=>(Jae(this.node,n,"Start"),i=>Jae(this.node,i,"End"))))}unmount(){}}class Oot extends j0{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=tI(SN(this.node.current,"focus",()=>this.onFocus()),SN(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function eoe(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&&ga.postRender(()=>o(e,sI(e)))}class Fot extends j0{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=uit(e,(i,o)=>(eoe(this.node,o,"Start"),(c,{success:a})=>eoe(this.node,c,a?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const v9=new WeakMap,tU=new WeakMap,Bot=t=>{const e=v9.get(t.target);e&&e(t)},$ot=t=>{t.forEach(Bot)};function zot({root:t,...e}){const r=t||document;tU.has(r)||tU.set(r,{});const n=tU.get(r),i=JSON.stringify(e);return n[i]||(n[i]=new IntersectionObserver($ot,{root:t,...e})),n[i]}function Uot(t,e,r){const n=zot(e);return v9.set(t,r),n.observe(t),()=>{v9.delete(t),n.unobserve(t)}}const Vot={some:0,all:1};class qot extends j0{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:Vot[i]},a=m=>{const{isIntersecting:y}=m;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:v,onViewportLeave:w}=this.node.getProps(),j=y?v:w;j&&j(m)};this.stopObserver=Uot(this.node.current,c,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:r}=this.node;["amount","margin","root"].some(Got(e,r))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Got({viewport:t={}},{viewport:e={}}={}){return r=>t[r]!==e[r]}const Hot={inView:{Feature:qot},tap:{Feature:Fot},focus:{Feature:Oot},hover:{Feature:Dot}},Wot={layout:{ProjectionNode:qTe,MeasureLayout:sje}},Kot={...yot,...Hot,...Mot,...Wot},yr=hot(Kot,fot);function Yot(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 toe(t){return t.visitor_intent==="buying"&&!t.has_agent}function Zot({token:t}={}){var j;const e=id(),r=t||e.token,{data:n,isLoading:i,isError:o}=Zrt(r);kr();const c=(j=n==null?void 0:n.open_houses)==null?void 0:j.id,{data:a}=mr({queryKey:["cohost-visitors",r,c],queryFn:async()=>{const{data:A,error:C}=await Ce.rpc("get_cohost_visitors",{_token:r});if(C)throw C;return A||[]},enabled:!!r&&!!c,refetchInterval:15e3});if(i)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:s.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(o||!n)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),s.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const f=n.open_houses,m=(a==null?void 0:a.length)||0,y=(a==null?void 0:a.filter(A=>A.visitor_intent==="buying").length)||0,v=(a==null?void 0:a.filter(toe).length)||0,w=A=>{if(!A)return"";const[C,I]=A.split(":"),M=parseInt(C);return`${M>12?M-12:M||12}:${I} ${M>=12?"PM":"AM"}`};return s.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),s.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),s.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:f.property_address})]}),s.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(kl,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[s.jsx(Sye,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:v})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(ta,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:y})]})]})]}),s.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[s.jsx("span",{children:Ls(new Date(f.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),f.start_time&&s.jsxs("span",{children:[w(f.start_time),f.end_time?` – ${w(f.end_time)}`:""]})]}),s.jsx(hp,{className:"flex-1 p-4 sm:p-6",children:a!=null&&a.length?s.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:s.jsx(HTe,{children:a.map((A,C)=>{var D;const I=Yot(A.visitor_intent),M=toe(A);return s.jsxs(yr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:C*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${M?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[s.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${M?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(D=A.first_name[0])==null?void 0:D.toUpperCase()}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("span",{className:"font-semibold text-white truncate",children:[A.first_name," ",A.last_name||""]}),M&&s.jsx(gi,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),A.has_agent&&s.jsx(gi,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsxs(gi,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${I.color}`,children:[I.emoji," ",I.label]}),s.jsx("span",{className:"text-white/30 text-xs",children:Ls(new Date(A.created_at),"h:mm a")})]})]})]},A.id)})})}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[s.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:s.jsx(WD,{className:"h-10 w-10 text-white/20"})}),s.jsx("h2",{className:"text-xl font-bold text-white/60 mb-1",children:"Waiting for visitors..."}),s.jsx("p",{className:"text-white/30 text-sm",children:"New sign-ins will appear here in real-time"})]})})]})}function Xot(){const e=xs().pathname.slice(1);if(N.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),e.startsWith("live/")){const r=e.slice(5);if(r)return s.jsx(Zot,{token:r})}if(e.startsWith("rsvp/")){const r=e.slice(5);if(r)return s.jsx(ySe,{slug:r})}return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),s.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),s.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):s.jsx(gSe,{slug:e})}function Qot(t){const e=t.replace(/[^0-9.]/g,"");if(!/^\d*\.?\d*$/.test(e))return null;const r=Number(e)||0;return Number.isFinite(r)?{text:e,value:r}:null}function Jot({value:t,onValueChange:e,onBlur:r,...n}){const[i,o]=N.useState(null);return s.jsx(Or,{...n,inputMode:"decimal",value:(i==null?void 0:i.value)===t?i.text:t||"",onChange:c=>{const a=Qot(c.target.value);a&&(o(a),e(a.value))},onBlur:c=>{o(null),r==null||r(c)}})}const roe=[{key:"payoffs",label:"Loan payoff",cls:"bg-primary-foreground/55"},{key:"commission",label:"Commission",cls:"bg-primary-foreground/35"},{key:"titleTotal",label:"Title & closing",cls:"bg-primary-foreground/20"},{key:"concessions",label:"Concessions & credits",cls:"bg-destructive"}];function noe(t){if(!t)return null;const[e,r,n]=t.split(/[-/T]/).map(Number);return!e||!r||!n?null:new Intl.DateTimeFormat("en-US",{timeZone:"UTC",month:"long",day:"numeric",year:"numeric"}).format(Date.UTC(e,r-1,n))}function soe({value:t,className:e}){return s.jsx("span",{className:Xt("tabular-nums",e),children:wm(t)})}function elt({data:t,agent:e,interactive:r=!0,compact:n=!1}){var K,J;const i=r&&t.allow_client_edits!==!1,[o,c]=N.useState(()=>t.scenarios.map(Q=>({...Q}))),[a,f]=N.useState(()=>({...t.inputs})),[m,y]=N.useState(()=>Math.min(1,Math.max(0,t.scenarios.length-1))),[v,w]=N.useState(!1),j=N.useMemo(()=>o.map(Q=>OJe(a,Q,t.close_date)),[o,a,t.close_date]),A=j[m]??j[0],C=j[Math.min(1,j.length-1)],I=[t.property_address,[t.city,t.state].filter(Boolean).join(", "),t.zip].filter(Boolean).join(" · "),M=t.mode==="offers",D=j.reduce((Q,ee,oe)=>{var de;return ee.net>(((de=j[Q])==null?void 0:de.net)??-1/0)?oe:Q},0),F=(Q,ee)=>c(oe=>oe.map((de,ye)=>ye===Q?{...de,...ee}:de)),z=()=>{c(t.scenarios.map(Q=>({...Q}))),f({...t.inputs})};if(!A)return null;const q=Math.max(A.price,1),H=[{label:"Sale price",get:Q=>Q.price},{label:`Listing commission (${a.listingCommissionPct}%)`,get:Q=>-Q.listingCommission,sub:!0},{label:`Buyer agent commission (${a.buyerCommissionPct}%)`,get:Q=>-Q.buyerCommission,sub:!0,hide:!a.buyerCommissionPct},{label:"Brokerage fee",get:Q=>-Q.brokerageFee,sub:!0,hide:!a.brokerageFee},{label:"Title & settlement",get:Q=>-Q.titleTotal,sub:!0},{label:"Mortgage payoff(s)",get:Q=>-Q.payoffs,sub:!0},{label:a.taxesInArrears?"Prorated property taxes":"Property tax credit",get:Q=>-Q.taxProration,sub:!0,hide:!a.annualTaxes},{label:"Buyer concessions",get:Q=>-Q.concessions,sub:!0,hide:j.every(Q=>!Q.concessions)},{label:"Repair credits",get:Q=>-Q.repairs,sub:!0,hide:j.every(Q=>!Q.repairs)},{label:"Other costs",get:Q=>-Q.otherTotal,sub:!0,hide:!((K=j[0])!=null&&K.otherTotal)}];return s.jsxs("div",{className:Xt("space-y-6",!n&&"mx-auto max-w-5xl"),children:[!n&&s.jsxs("header",{className:"flex flex-col gap-5 rounded-3xl border bg-card p-6 shadow-sm sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[e!=null&&e.avatar_url?s.jsx("img",{src:e.avatar_url,alt:e.name??"Agent",className:"h-16 w-16 rounded-2xl object-cover"}):s.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-2xl bg-primary text-xl font-semibold text-primary-foreground",children:((e==null?void 0:e.name)??"A").slice(0,1)}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Prepared by"}),s.jsx("p",{className:"text-lg font-semibold text-foreground",children:(e==null?void 0:e.name)??"Your agent"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:[e==null?void 0:e.title,e==null?void 0:e.brokerage_name].filter(Boolean).join(" · ")})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 print:hidden",children:[(e==null?void 0:e.phone)&&s.jsxs(s.Fragment,{children:[s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",children:s.jsxs("a",{href:`tel:${e.phone}`,children:[s.jsx(Fn,{className:"mr-1.5 h-4 w-4"}),"Call"]})}),s.jsx(Lt,{asChild:!0,variant:"outline",size:"sm",children:s.jsxs("a",{href:`sms:${e.phone}`,children:[s.jsx(Ph,{className:"mr-1.5 h-4 w-4"}),"Text"]})})]}),(e==null?void 0:e.email)&&s.jsx(Lt,{asChild:!0,size:"sm",children:s.jsxs("a",{href:`mailto:${e.email}?subject=${encodeURIComponent(`Question about my net sheet${t.property_address?` — ${t.property_address}`:""}`)}`,children:[s.jsx(rs,{className:"mr-1.5 h-4 w-4"}),"Ask a question"]})})]})]}),s.jsxs("section",{className:"overflow-hidden rounded-3xl bg-primary p-6 text-primary-foreground shadow-lg sm:p-10",children:[s.jsxs("div",{className:"flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.22em] opacity-75",children:t.title||"Seller net sheet"}),I&&s.jsxs("p",{className:"flex items-center gap-2 text-sm opacity-90",children:[s.jsx(ii,{className:"h-4 w-4"}),I]}),s.jsxs("div",{children:[s.jsxs("p",{className:"text-sm opacity-80",children:["Estimated walk-away · ",(J=o[m])==null?void 0:J.label]}),s.jsx("p",{className:"font-serif text-5xl font-semibold tracking-tight tabular-nums sm:text-6xl",children:wm(A.net)})]}),s.jsxs("p",{className:"text-sm opacity-80",children:[Math.round(A.netPct*100),"% of the ",wm(A.price)," sale price",noe(t.close_date)&&s.jsxs(s.Fragment,{children:[" · ",s.jsx(bo,{className:"inline h-3.5 w-3.5 -mt-0.5"})," closing ",noe(t.close_date)]})]})]}),t.client_name&&s.jsxs("p",{className:"text-sm opacity-80 lg:text-right",children:["Prepared for",s.jsx("br",{}),s.jsx("span",{className:"text-lg font-semibold opacity-100",children:t.client_name})]})]}),s.jsxs("div",{className:"mt-8",children:[s.jsxs("div",{className:"flex h-4 w-full overflow-hidden rounded-full bg-primary-foreground/15",children:[s.jsx("div",{className:"h-full border-r-2 border-primary bg-primary-foreground transition-all duration-500",style:{width:`${Math.max(0,A.net/q*100)}%`}}),roe.map(Q=>{const ee=Q.key==="concessions"?A.concessions+A.repairs:A[Q.key];return ee>0?s.jsx("div",{className:Xt("h-full transition-all duration-500",Q.cls),style:{width:`${ee/q*100}%`}},Q.key):null})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-x-5 gap-y-1 text-xs opacity-85",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("i",{className:"h-2.5 w-2.5 rounded-full bg-primary-foreground"}),"Your net ",wm(A.net)]}),roe.map(Q=>{const ee=Q.key==="concessions"?A.concessions+A.repairs:A[Q.key];return ee>0?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("i",{className:Xt("h-2.5 w-2.5 rounded-full",Q.cls)}),Q.label," ",wm(ee)]},Q.key):null})]})]})]}),t.message&&!n&&s.jsx("p",{className:"rounded-2xl border bg-card p-5 text-sm leading-relaxed text-foreground",children:t.message}),s.jsx("section",{className:Xt("grid gap-4",o.length===3?"md:grid-cols-3":o.length===2?"md:grid-cols-2":""),children:o.map((Q,ee)=>{var ye,we;const oe=j[ee],de=oe.net-C.net;return s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>y(ee),onKeyDown:Le=>Le.key==="Enter"&&y(ee),className:Xt("relative cursor-pointer rounded-3xl border bg-card p-5 text-left transition-all",ee===m?"border-primary ring-2 ring-primary/30 shadow-md":"hover:border-primary/40"),children:[M&&ee===D&&j.length>1&&s.jsx("span",{className:"absolute right-4 top-4 rounded-full bg-primary px-2.5 py-0.5 text-[11px] font-semibold text-primary-foreground",children:"Highest net"}),s.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:Q.label}),s.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Sale price ",s.jsx(soe,{value:oe.price,className:"font-medium text-foreground"})]}),s.jsx("p",{className:"mt-3 text-3xl font-semibold tracking-tight text-foreground",children:s.jsx(soe,{value:oe.net})}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"estimated net"}),ee!==Math.min(1,j.length-1)&&j.length>1&&s.jsxs("p",{className:Xt("mt-2 inline-flex items-center gap-1 text-xs font-medium",de>=0?"text-primary":"text-destructive"),children:[s.jsx(Df,{className:Xt("h-3.5 w-3.5",de<0&&"rotate-180")}),de>=0?"+":"−",wm(Math.abs(de))," vs ",o[Math.min(1,o.length-1)].label.toLowerCase()]}),Q.note&&s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:Q.note}),i&&ee===m&&s.jsxs("div",{className:"mt-4 space-y-3 border-t pt-4 print:hidden",onClick:Le=>Le.stopPropagation(),children:[s.jsx("label",{className:"block text-xs font-medium text-muted-foreground",children:"Try a different price"}),s.jsx(Km,{min:Math.round((((ye=t.scenarios[ee])==null?void 0:ye.price)||oe.price)*.8/1e3)*1e3,max:Math.round((((we=t.scenarios[ee])==null?void 0:we.price)||oe.price)*1.2/1e3)*1e3||1e5,step:1e3,value:[Q.price],onValueChange:([Le])=>F(ee,{price:Le})}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Price"}),s.jsx(Or,{inputMode:"numeric",value:Q.price||"",onChange:Le=>F(ee,{price:Number(Le.target.value.replace(/\D/g,""))})})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Buyer credit"}),s.jsx(Or,{inputMode:"numeric",value:Q.concessions||"",placeholder:"0",onChange:Le=>F(ee,{concessions:Number(Le.target.value.replace(/\D/g,""))})})]})]})]})]},Q.id)})}),i&&s.jsxs("section",{className:"grid gap-4 rounded-3xl border bg-card p-5 sm:grid-cols-3 print:hidden",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Mortgage payoff"}),s.jsx(Or,{inputMode:"numeric",value:a.firstPayoff||"",placeholder:"0",onChange:Q=>f({...a,firstPayoff:Number(Q.target.value.replace(/\D/g,""))})})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Total commission %"}),s.jsx(Jot,{"aria-label":"Total commission %",value:a.listingCommissionPct+a.buyerCommissionPct,onValueChange:Q=>{const ee=a.listingCommissionPct+a.buyerCommissionPct,oe=t.inputs.listingCommissionPct+t.inputs.buyerCommissionPct,de=ee?a.listingCommissionPct/ee:oe?t.inputs.listingCommissionPct/oe:.5,ye=+(Q*de).toFixed(3);f({...a,listingCommissionPct:ye,buyerCommissionPct:+(Q-ye).toFixed(3)})}})]}),s.jsxs("div",{className:"flex items-end justify-between gap-3",children:[s.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes here are just for you — they don't change your agent's copy."}),s.jsxs(Lt,{variant:"ghost",size:"sm",onClick:z,children:[s.jsx(cFe,{className:"mr-1.5 h-4 w-4"}),"Reset"]})]})]}),s.jsxs("section",{className:"overflow-hidden rounded-3xl border bg-card",children:[s.jsxs("div",{className:"flex items-center justify-between border-b px-5 py-4",children:[s.jsx("h2",{className:"font-semibold text-foreground",children:"Line-by-line comparison"}),!n&&s.jsxs(Lt,{variant:"outline",size:"sm",className:"print:hidden",onClick:()=>window.print(),children:[s.jsx(oFe,{className:"mr-1.5 h-4 w-4"}),"Print / PDF"]})]}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full min-w-[520px] text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-left text-xs uppercase tracking-wider text-muted-foreground",children:[s.jsx("th",{className:"px-5 py-3 font-medium"}),o.map((Q,ee)=>s.jsx("th",{className:Xt("px-5 py-3 text-right font-medium",ee===m&&"text-primary"),children:Q.label},Q.id))]})}),s.jsxs("tbody",{children:[H.filter(Q=>!Q.hide).map(Q=>s.jsxs("tr",{className:"border-t",children:[s.jsx("td",{className:Xt("px-5 py-2.5",Q.sub?"text-muted-foreground":"font-medium text-foreground"),children:Q.label==="Title & settlement"?s.jsxs("button",{className:"inline-flex items-center gap-1 text-left hover:text-foreground",onClick:()=>w(ee=>!ee),children:[Q.label,s.jsx(Wo,{className:Xt("h-3.5 w-3.5 transition-transform",v&&"rotate-180")})]}):Q.label}),j.map((ee,oe)=>s.jsx("td",{className:Xt("px-5 py-2.5 text-right tabular-nums",Q.sub?"text-muted-foreground":"font-medium text-foreground"),children:Q.get(ee)<0?`−${wm(-Q.get(ee),!0)}`:wm(Q.get(ee),!0)},oe))]},Q.label)).flatMap(Q=>Q.key!=="Title & settlement"||!v?[Q]:[Q,...a.titleFees.map(ee=>s.jsxs("tr",{className:"bg-muted/40 text-xs",children:[s.jsx("td",{className:"px-5 py-1.5 pl-9 text-muted-foreground",children:ee.label}),j.map((oe,de)=>s.jsxs("td",{className:"px-5 py-1.5 text-right tabular-nums text-muted-foreground",children:["−",wm(ee.amount,!0)]},de))]},ee.id))]),s.jsxs("tr",{className:"border-t-2 border-primary/30 bg-primary/5",children:[s.jsx("td",{className:"px-5 py-4 font-semibold text-foreground",children:"Estimated net to you"}),j.map((Q,ee)=>s.jsx("td",{className:"px-5 py-4 text-right text-lg font-semibold tabular-nums text-primary",children:wm(Q.net,!0)},ee))]})]})]})})]}),s.jsx("p",{className:"px-1 text-xs leading-relaxed text-muted-foreground",children:"These figures are estimates for planning only and are not a guarantee of final proceeds. Actual amounts are set by your title company at closing and may vary with payoff figures, prorations, taxes, and contract terms."})]})}function tlt({dealId:t}){const{data:e}=mr({queryKey:["portal-net-sheet",t],queryFn:async()=>{const{data:n,error:i}=await Ce.rpc("get_portal_net_sheet",{_deal_id:t});if(i)throw i;return n??null}}),{data:r}=BJe(e??void 0);return r!=null&&r.sheet?s.jsxs("section",{className:"space-y-3",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"Your net proceeds"}),s.jsx(elt,{data:r.sheet,agent:r.agent,compact:!0}),s.jsx("a",{href:`/net-sheet/${r.sheet.slug}`,target:"_blank",rel:"noreferrer",className:"inline-block text-sm font-medium text-primary underline-offset-4 hover:underline",children:"Open full net sheet & print"})]}):null}function n0(t){return t==="seller"||t==="listing"}function LO(t){return t==="buyer"||t==="buy-side"}const rlt="/assets/homeowner-garden-C8lI4Nq2.jpg";function nlt(t,e,r,n=30){if(t===null||!(t>0)||!(e>0)||e>100)return null;const i=Math.floor(t/(e/100)/1e3)*1e3,o=i-t,c=r/100/12,a=n*12,f=o<=0?0:c===0?o/a:o*c/(1-Math.pow(1+c,-a));return{price:i,loan:Math.max(0,o),payment:Math.round(f)}}const rU=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),slt=["Kitchen remodel","Bathroom update","Added a bathroom","New roof","Finished basement","Deck or patio","New HVAC","Flooring","Windows","Solar panels","Landscaping","Other"];function ilt({accessKey:t,agentName:e,onDone:r,preview:n=!1}){const[i,o]=N.useState(!1),[c,a]=N.useState([]),[f,m]=N.useState(""),[y,v]=N.useState(""),[w,j]=N.useState(""),[A,C]=N.useState(!1),[I,M]=N.useState(!1),D=z=>{const q=Number(z.replace(/[^0-9.]/g,""));return z.trim()&&q>0?q:null};async function F(){if(!c.length&&!w.trim()){$t.error("Pick at least one update or add a note");return}if(n){$t.info("Preview only — homeowner actions are turned off");return}C(!0);const{error:z}=await Ce.rpc("homeowner_hub_report_renovation",{_key:t,_items:c,_spend:D(f),_value_guess:D(y),_note:w.trim()||null});if(C(!1),z){$t.error("Could not send your updates. Please try again.");return}M(!0),o(!1),r(),$t.success(`${e} will review your updates`)}return s.jsxs("section",{className:"homeowner-valuation py-8 flex flex-wrap justify-between items-center gap-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"homeowner-kicker",children:"TUNE MY VALUE"}),s.jsx("h2",{className:"portal-serif text-2xl mt-2",children:"Made updates to your home?"}),s.jsxs("p",{className:"homeowner-muted text-sm mt-2",children:["Tell ",e," what you’ve improved so your value reflects it. Nothing changes until they review it."]})]}),s.jsxs(Lt,{variant:"outline",className:"homeowner-control",disabled:I,onClick:()=>o(!0),children:[I?s.jsx(pa,{className:"h-4 w-4 mr-2"}):s.jsx(V3e,{className:"h-4 w-4 mr-2"}),I?"Updates sent":"Report home updates"]}),s.jsx(Wa,{open:i,onOpenChange:o,children:s.jsxs(La,{className:"max-h-[90dvh] overflow-y-auto",children:[s.jsxs(Ko,{children:[s.jsx(Po,{children:"What have you updated?"}),s.jsxs(sd,{children:["Only ",e," sees this."]})]}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:slt.map(z=>s.jsxs("label",{className:"flex items-center gap-2 text-sm rounded-md border p-2 cursor-pointer",children:[s.jsx(mj,{checked:c.includes(z),onCheckedChange:q=>a(H=>q?[...H,z]:H.filter(K=>K!==z))}),z]},z))}),s.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"tmv-spend",children:"About how much you spent ($)"}),s.jsx(Or,{id:"tmv-spend",inputMode:"numeric",placeholder:"e.g. 40,000",value:f,onChange:z=>m(z.target.value)})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"tmv-guess",children:"What you think it’s worth ($)"}),s.jsx(Or,{id:"tmv-guess",inputMode:"numeric",placeholder:"e.g. 520,000",value:y,onChange:z=>v(z.target.value)})]})]}),s.jsxs("div",{children:[s.jsx(Br,{htmlFor:"tmv-note",children:"Anything else?"}),s.jsx(qc,{id:"tmv-note",maxLength:1e3,value:w,onChange:z=>j(z.target.value),placeholder:"e.g. Quartz counters, new appliances in 2025"})]}),s.jsx(Lt,{className:"homeowner-primary w-full",disabled:A,onClick:F,children:A?"Sending…":`Send to ${e}`})]})})]})}function alt({equity:t,searchUrl:e}){const[r,n]=N.useState(20),[i,o]=N.useState(6.5),c=nlt(t,r,i);if(!c)return null;const a=e?`${e}${e.includes("?")?"&":"?"}maxPrice=${c.price}`:null;return s.jsxs("section",{className:"homeowner-financial-section py-8","aria-label":"Equity trade-up",children:[s.jsxs("p",{className:"homeowner-kicker flex items-center gap-2",children:[s.jsx(LH,{className:"h-4 w-4"})," YOUR NEXT MOVE"]}),s.jsx("h2",{className:"portal-serif text-2xl mt-2",children:"See what your equity could buy"}),s.jsxs("p",{className:"homeowner-muted text-sm mt-2",children:["Using ",rU(t)," of equity as a ",r,"% down payment."]}),s.jsxs("div",{className:"grid md:grid-cols-2 gap-8 mt-5",children:[s.jsxs("div",{className:"space-y-5",children:[s.jsxs("div",{children:[s.jsxs(Br,{className:"block mb-3",children:["Down payment: ",r,"%"]}),s.jsx(Km,{"aria-label":"Down payment percent",min:5,max:50,step:1,value:[r],onValueChange:f=>n(f[0])})]}),s.jsxs("div",{children:[s.jsxs(Br,{className:"block mb-3",children:["Interest rate: ",i.toFixed(2),"%"]}),s.jsx(Km,{"aria-label":"Interest rate",min:3,max:9,step:.125,value:[i],onValueChange:f=>o(f[0])})]})]}),s.jsxs("div",{children:[s.jsx("p",{className:"homeowner-muted text-sm",children:"Home price up to"}),s.jsx("p",{className:"portal-serif text-4xl tabular-nums",children:rU(c.price)}),s.jsxs("p",{className:"homeowner-muted text-sm mt-2",children:["About ",rU(c.payment),"/mo principal & interest on a 30-year loan. Excludes taxes, insurance and closing costs; not a loan approval."]}),a&&s.jsx(Lt,{asChild:!0,className:"homeowner-primary mt-4",children:s.jsxs("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(ju,{className:"h-4 w-4 mr-2"}),"Browse homes in this range"]})})]})]})]})}function nU({balance:t,rate:e,months:r},n=0){if(t===null||e===null||r===null||t<0||e<0||e>30||r<1||r>600||![t,e,r,n].every(Number.isFinite))return null;const i=e/1200,o=i===0?t/r:t*i/(1-(1+i)**-r),c=Math.min(r,Math.max(0,Math.floor(n))),a=Math.max(0,i===0?t-o*c:t*(1+i)**c-o*((1+i)**c-1)/i);return{payment:o,remaining:a,principalPaid:t-a}}function ML(t,e=new Date){var o,c;if(!t)return 0;const[r,n]=t.split(/[-/T]/).map(Number),i=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"numeric"}).formatToParts(e);return Math.max(0,(Number((o=i.find(a=>a.type==="year"))==null?void 0:o.value)-r)*12+Number((c=i.find(a=>a.type==="month"))==null?void 0:c.value)-n)}function olt(t,e){return t!==null&&e!==null&&Number.isFinite(t)&&Number.isFinite(e)&&t>0&&e>=0?t-e:null}function llt(t){return(t==null?void 0:t.is_won_stage)===!0&&t.is_lost_stage!==!0}function clt(t,e,r,n){if(t===null||e===null||r===null||!(t>0)||e<0||e>30||r<1||r>600||!(n>=0)||![t,e,r,n].every(Number.isFinite))return null;const i=e/1200,o=i===0?t/r:t*i/(1-(1+i)**-r),c=o*r-t;let a=t,f=0,m=0;for(;a>.005&&f<600;){const y=a*i;m+=y,a=a+y-(o+n),f++}return{payment:o,payoffMonths:f,monthsSaved:Math.max(0,r-f),interestSaved:Math.max(0,c-m)}}const pm=t=>t===null?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t);function ult({accessKey:t,standalone:e=!1,preview:r=!1}){var Se,ve,me,ke,Pe,Ee,xe,Ue,Ze,lt,wt,yt;const n=kr(),[i,o]=N.useState(!1),[c,a]=N.useState(!1),[f,m]=N.useState(!1),[y,v]=N.useState(7),[w,j]=N.useState(150),[A,C]=N.useState({}),{data:I,isLoading:M,error:D}=mr({queryKey:["homeowner-hub-public",t],queryFn:async()=>{const{data:gt,error:ft}=await Ce.rpc("homeowner_hub_read",{_key:t});if(ft)throw ft;return gt}});N.useEffect(()=>{I!=null&&I.hub.id&&!r&&Ce.rpc("homeowner_hub_visit",{_key:t})},[t,I==null?void 0:I.hub.id,r]),N.useEffect(()=>{if(e)return document.body.classList.add("client-portal-page","homeowner-hub-page"),()=>document.body.classList.remove("client-portal-page","homeowner-hub-page")},[e]);const F=I==null?void 0:I.hub;function z(){F&&(C(Object.fromEntries(["address","city","state","zip_code","home_value","mortgage_balance","interest_rate","remaining_months"].map(gt=>[gt,String(F[gt]??"")]))),o(!0))}async function q(){if(r){$t.info("Preview only — homeowner actions are turned off");return}a(!0);try{const{error:gt}=await Ce.rpc("homeowner_hub_save",{_key:t,_details:A});if(gt)throw gt;await n.invalidateQueries({queryKey:["homeowner-hub-public",t]}),o(!1),$t.success("Your home details are saved")}catch{$t.error("Could not save. Check the amounts and try again.")}finally{a(!1)}}async function H(){if(r){$t.info("Preview only — homeowner actions are turned off");return}m(!0);try{const{error:gt}=await Ce.rpc("homeowner_hub_request",{_key:t});if(gt)throw gt;await n.invalidateQueries({queryKey:["homeowner-hub-public",t]}),$t.success("Your agent has received your valuation request")}catch{$t.error("Your request could not be sent. Please try again.")}finally{m(!1)}}if(M)return e?s.jsx("div",{className:"homeowner-page flex min-h-screen items-center justify-center",children:s.jsx(zc,{className:"animate-spin"})}):null;if(!F||!I||D)return e?s.jsx("div",{className:"homeowner-page min-h-screen flex items-center justify-center p-6",children:s.jsxs("div",{children:[s.jsx("h1",{className:"portal-serif text-4xl",children:"Homeowner Hub unavailable"}),s.jsx("p",{className:"mt-3",children:"Please ask your agent for your personal link."})]})}):null;const K=nU({balance:F.mortgage_balance,rate:F.balance_source==="property_intel"?null:F.interest_rate,months:F.remaining_months},ML(F.balance_updated_at)),J=(K==null?void 0:K.remaining)??F.mortgage_balance,Q=olt(F.home_value,J),ee=nU({balance:F.mortgage_balance,rate:F.balance_source==="property_intel"?null:F.interest_rate,months:F.remaining_months},ML(F.balance_updated_at)+12),oe=Q===null||F.home_value===null?null:Q-F.home_value*y/100,de=F.remaining_months===null?null:Math.max(1,F.remaining_months-ML(F.balance_updated_at)),ye=clt(J??null,F.balance_source==="property_intel"?null:F.interest_rate,de,w),we=F.valuation_requested_at&&Date.now()-Date.parse(F.valuation_requested_at)<864e5,Le=s.jsxs("section",{className:"homeowner-hub min-w-0","aria-label":"Homeowner Hub",children:[r&&s.jsx("div",{role:"status",className:"sticky top-0 z-50 mb-4 rounded-md border border-primary bg-primary px-4 py-2 text-center text-sm font-medium text-primary-foreground",children:"Preview — the homeowner can't see this banner. Your visit isn't counted and buttons won't send anything."}),s.jsxs("header",{className:"homeowner-heading",children:[s.jsx("img",{src:rlt,alt:"",width:1536,height:768,className:"homeowner-garden",fetchPriority:"high"}),s.jsxs("div",{className:"homeowner-heading-inner",children:[s.jsxs("div",{className:"homeowner-hero-top",children:[s.jsxs("p",{className:"homeowner-kicker flex items-center gap-2",children:[s.jsx(S3,{className:"h-4 w-4"})," PRIVATE HOMEOWNER HUB"]}),s.jsxs(Lt,{variant:"outline",className:"homeowner-hero-control",onClick:z,children:[s.jsx(kye,{className:"h-4 w-4 mr-2"}),"My home details"]})]}),s.jsxs("div",{className:"homeowner-hero-title",children:[s.jsx("p",{className:"homeowner-kicker",children:F.client_name?`AT HOME WITH ${F.client_name.split(" ")[0].toUpperCase()}`:"YOUR HOME · YOUR NEXT CHAPTER"}),s.jsx("h1",{className:"portal-serif mt-3",children:"Homeowner Hub"}),s.jsx("p",{className:"homeowner-hero-subtitle mt-3",children:"A little clarity for your biggest investment."}),s.jsxs("p",{className:"homeowner-address mt-5 flex items-start gap-2",children:[s.jsx(ii,{className:"h-4 w-4 shrink-0 mt-1"}),[F.address,F.city,F.state].filter(Boolean).join(", ")||"Let’s add your home address"]})]})]})]}),s.jsxs("div",{className:"homeowner-content",children:[F.mls_facts&&(()=>{const gt=F.mls_facts,ft=[[gt.beds,"Beds"],[gt.baths,"Baths"],[gt.sqft&&Number(gt.sqft).toLocaleString("en-US"),"Sq ft"],[gt.yearBuilt,"Built"]].filter(([kt])=>kt);return s.jsxs("section",{className:"homeowner-facts flex flex-wrap items-center gap-6 pt-8","aria-label":"Home facts",children:[gt.photo&&s.jsx("img",{src:gt.photo,alt:"Your home",className:"w-28 h-20 rounded-lg object-cover",loading:"lazy"}),s.jsxs("dl",{className:"flex flex-wrap gap-6",children:[ft.map(([kt,Vt])=>s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-xs uppercase tracking-wide",children:Vt}),s.jsx("dd",{className:"portal-serif text-2xl",children:kt})]},Vt)),gt.lastSalePrice&&s.jsxs("div",{children:[s.jsxs("dt",{className:"homeowner-muted text-xs uppercase tracking-wide",children:["Last sold",gt.lastSaleDate?` · ${gt.lastSaleDate.split(/[-/T]/)[0]}`:""]}),s.jsx("dd",{className:"portal-serif text-2xl",children:pm(gt.lastSalePrice)})]})]})]})})(),s.jsxs("div",{className:"homeowner-equity grid gap-8 md:grid-cols-[1.2fr_1fr] py-10",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("p",{className:"homeowner-kicker flex items-center gap-2",children:[s.jsx(Df,{className:"h-4 w-4"})," YOUR HOME, IN NUMBERS"]}),s.jsx("h2",{className:"portal-serif text-2xl mt-3",children:"Estimated home equity"}),s.jsx("p",{className:"portal-serif homeowner-equity-value mt-2 tabular-nums break-words",children:pm(Q)}),s.jsx("p",{className:"homeowner-muted text-sm mt-3 max-w-sm",children:Q===null?"Add a home value and mortgage balance to see your estimate.":"Home value minus estimated remaining mortgage. Not a cash offer."})]}),s.jsxs("div",{className:"homeowner-equity-breakdown flex items-center gap-6",children:[s.jsxs("svg",{viewBox:"0 0 120 120",className:"homeowner-equity-ring shrink-0",role:"img","aria-label":"Estimated equity as a share of your home value",children:[s.jsx("circle",{cx:"60",cy:"60",r:"50",className:"homeowner-ring-track"}),Q!==null&&F.home_value!==null&&s.jsx("circle",{cx:"60",cy:"60",r:"50",className:"homeowner-ring-value",strokeDasharray:`${Math.min(1,Math.max(0,Q/F.home_value))*314.16} 314.16`,transform:"rotate(-90 60 60)"}),s.jsx(ta,{x:"46",y:"46",width:"28",height:"28",className:"homeowner-ring-home"})]}),s.jsxs("dl",{className:"grid gap-5 min-w-0",children:[s.jsxs("div",{children:[s.jsxs("dt",{className:"homeowner-muted text-sm flex items-center gap-2",children:[s.jsx("span",{className:"homeowner-legend homeowner-legend-equity"}),"Home value estimate"]}),s.jsx("dd",{className:"text-2xl tabular-nums mt-1",children:pm(F.home_value)}),s.jsx("p",{className:"homeowner-muted text-xs mt-1",children:F.home_value===null?"Not provided":F.value_source==="property_intel"?"Property-provider estimate":F.value_source==="agent_entered"?((Se=F.mls_facts)==null?void 0:Se.lastSalePrice)===F.home_value?"Last MLS sale price":"Agent-entered estimate":"Homeowner-entered estimate"})]}),s.jsxs("div",{children:[s.jsxs("dt",{className:"homeowner-muted text-sm flex items-center gap-2",children:[s.jsx("span",{className:"homeowner-legend homeowner-legend-mortgage"}),"Mortgage balance"]}),s.jsx("dd",{className:"text-2xl tabular-nums mt-1",children:pm(J)}),s.jsx("p",{className:"homeowner-muted text-xs mt-1",children:F.balance_source==="property_intel"?"Property-provider estimate · not a payoff balance":K?"Projected from your loan details":J===null?"Not provided":"Last balance provided"})]})]})]})]}),F.property_intel_at&&s.jsxs("section",{className:"py-5 border-y space-y-3","aria-label":"Saved property details",children:[s.jsxs("p",{className:"homeowner-muted text-xs",children:["Saved property estimates · ",new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(Date.parse(F.property_intel_at))]}),s.jsxs("dl",{className:"flex flex-wrap gap-6",children:[((ve=F.property_intel)==null?void 0:ve.lender_name)&&s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-xs",children:"Recorded lender"}),s.jsx("dd",{className:"text-sm",children:F.property_intel.lender_name})]}),((me=F.property_intel)==null?void 0:me.years_owned)!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-xs",children:"Recorded years owned"}),s.jsx("dd",{children:F.property_intel.years_owned})]}),((ke=F.property_intel)==null?void 0:ke.last_sale_price)!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-xs",children:"Last recorded sale"}),s.jsx("dd",{children:pm(F.property_intel.last_sale_price)})]})]})]}),s.jsxs("div",{className:"homeowner-financials grid md:grid-cols-2 gap-8 py-8",children:[s.jsxs("section",{className:"homeowner-financial-section min-w-0",children:[s.jsxs("h2",{className:"portal-serif text-2xl flex items-center gap-2",children:[s.jsx(Df,{className:"h-5 w-5"}),"Mortgage momentum"]}),s.jsx("p",{className:"homeowner-muted text-sm mt-2",children:"Principal & interest only; excludes taxes, insurance and extra payments."}),s.jsxs("dl",{className:"grid grid-cols-2 gap-4 mt-5",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-sm",children:"Monthly payment estimate"}),s.jsx("dd",{className:"text-2xl mt-1",children:pm((K==null?void 0:K.payment)??null)})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-sm",children:"Next 12 months’ paydown"}),s.jsx("dd",{className:"text-2xl mt-1",children:pm(ee&&J!==null?J-ee.remaining:null)})]})]}),K&&J!==null&&ee&&s.jsx("svg",{viewBox:"0 0 240 48",className:"w-full h-12 mt-5 homeowner-chart",role:"img","aria-label":"Projected cumulative mortgage principal paid over the next twelve months",children:Array.from({length:12},(gt,ft)=>{const kt=nU({balance:F.mortgage_balance,rate:F.balance_source==="property_intel"?null:F.interest_rate,months:F.remaining_months},ML(F.balance_updated_at)+ft+1),Vt=ee.remainingv(gt[0]??7),className:"homeowner-slider"})]})]}),ye&&s.jsxs("section",{className:"homeowner-financial-section py-8 min-w-0","aria-label":"Pay off sooner",children:[s.jsxs("h2",{className:"portal-serif text-2xl flex items-center gap-2",children:[s.jsx(Df,{className:"h-5 w-5"}),"What if you paid a little extra?"]}),s.jsxs("p",{className:"homeowner-muted text-sm mt-2",children:["Add ",pm(w)," a month to principal and see what changes."]}),s.jsx(Km,{className:"mt-5 max-w-md",min:0,max:1e3,step:25,value:[w],onValueChange:gt=>j(gt[0]),"aria-label":"Extra monthly payment"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-4 mt-5 max-w-md",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-sm",children:"Paid off sooner by"}),s.jsxs("dd",{className:"text-2xl tabular-nums",children:[Math.floor(ye.monthsSaved/12)," yr ",ye.monthsSaved%12," mo"]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"homeowner-muted text-sm",children:"Interest you keep"}),s.jsx("dd",{className:"text-2xl tabular-nums",children:pm(Math.round(ye.interestSaved))})]})]}),s.jsx("p",{className:"homeowner-muted text-xs mt-2",children:"Estimate only; principal & interest, based on the details on file."})]}),s.jsxs("section",{className:"homeowner-valuation py-8 flex flex-wrap justify-between items-center gap-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"homeowner-kicker",children:"A REAL PERSON. A MORE PERSONAL VALUE."}),s.jsx("h2",{className:"portal-serif text-2xl mt-2",children:"What is your home worth today?"}),s.jsxs("p",{className:"homeowner-muted text-sm mt-2",children:["Ask ",((Pe=I.agent)==null?void 0:Pe.name)||"your agent"," for a fresh, local valuation."]})]}),s.jsxs(Lt,{className:"homeowner-primary",disabled:f||!!we,onClick:H,children:[we?s.jsx(pa,{className:"h-4 w-4 mr-2"}):s.jsx(ju,{className:"h-4 w-4 mr-2"}),we?"Valuation requested":f?"Sending…":"Request my home value"]})]}),s.jsx(ilt,{preview:r,accessKey:t,agentName:((Ee=I.agent)==null?void 0:Ee.name)||"your agent",onDone:()=>n.invalidateQueries({queryKey:["homeowner-hub-public",t]})}),s.jsx(alt,{equity:oe??Q,searchUrl:(xe=I.site)!=null&&xe.has_idx?`${I.site.url}/search?statuses=Active`:null}),((Ue=I.site)==null?void 0:Ue.has_idx)&&s.jsxs("section",{className:"homeowner-neighborhood py-10",children:[s.jsx("p",{className:"homeowner-kicker",children:"NEIGHBORHOOD RADAR"}),s.jsx("h2",{className:"portal-serif text-2xl mt-2",children:"See what’s moving around you"}),s.jsx("p",{className:"homeowner-muted text-sm mt-2",children:"Explore your agent’s MLS listings. Asking prices are not sold comparable values."}),s.jsx("div",{className:"flex flex-wrap gap-3 mt-4",children:[["Active","Explore nearby homes"],["Pending","Under contract nearby"],["Sold","Recent sales"]].map(([gt,ft])=>{var kt;return s.jsx(Lt,{asChild:!0,variant:"outline",className:"homeowner-control homeowner-neighborhood-link",children:s.jsxs("a",{href:`${(kt=I.site)==null?void 0:kt.url}/search?q=${encodeURIComponent(F.zip_code||[F.city,F.state].filter(Boolean).join(", "))}&statuses=${gt}`,target:"_blank",rel:"noopener noreferrer",children:[ft,s.jsx(ju,{className:"h-4 w-4 ml-2"})]})},gt)})}),s.jsx("p",{className:"homeowner-muted text-xs mt-3",children:"Availability of pending and sold listings depends on your agent’s MLS permissions."})]}),s.jsxs("footer",{className:"homeowner-advisor flex flex-wrap items-center justify-between gap-4 py-7",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[((Ze=I.agent)==null?void 0:Ze.avatar_url)&&s.jsx("img",{src:I.agent.avatar_url,alt:I.agent.name,className:"w-16 h-16 rounded-full object-cover"}),s.jsxs("div",{children:[s.jsx("p",{className:"homeowner-muted text-xs",children:"Your real estate advisor"}),s.jsx("p",{className:"font-medium",children:(lt=I.agent)==null?void 0:lt.name})]})]}),s.jsxs("div",{className:"flex gap-2",children:[((wt=I.agent)==null?void 0:wt.phone)&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"icon",className:"homeowner-control",children:s.jsx("a",{href:`tel:${I.agent.phone}`,"aria-label":"Call your agent",children:s.jsx(Fn,{className:"h-4 w-4"})})}),((yt=I.agent)==null?void 0:yt.email)&&s.jsx(Lt,{asChild:!0,variant:"outline",size:"icon",className:"homeowner-control",children:s.jsx("a",{href:`mailto:${I.agent.email}`,"aria-label":"Email your agent",children:s.jsx(rs,{className:"h-4 w-4"})})})]})]}),s.jsxs("p",{className:"homeowner-muted text-xs leading-relaxed mt-6",children:["Estimates use details you or your agent provide, including saved property-provider estimates when labeled. No automatic appraisal, verified ownership, live mortgage balance or guaranteed appreciation is implied. ",F.value_updated_at&&`Value last entered ${new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(Date.parse(F.value_updated_at))}.`]})]}),s.jsx(Wa,{open:i,onOpenChange:o,children:s.jsxs(La,{className:"max-h-[90dvh] overflow-y-auto",children:[s.jsx(Ko,{children:s.jsx(Po,{children:"My home details"})}),s.jsxs("form",{onSubmit:gt=>{gt.preventDefault(),q()},className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave unknown amounts blank. Only include this home’s mortgage; additional liens are not included."}),s.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:[["address","Street address"],["city","City"],["state","State"],["zip_code","ZIP code"],["home_value","Estimated home value ($)"],["mortgage_balance","Current mortgage balance ($)"],["interest_rate","Interest rate (%)"],["remaining_months","Months remaining"]].map(([gt,ft])=>s.jsxs("div",{children:[s.jsx(Br,{htmlFor:`hub-${gt}`,children:ft}),s.jsx(Or,{id:`hub-${gt}`,value:A[gt]??"",type:["home_value","mortgage_balance","interest_rate","remaining_months"].includes(gt)?"number":"text",min:gt==="home_value"||gt==="remaining_months"?1:0,max:gt==="interest_rate"?30:gt==="remaining_months"?600:1e9,step:gt==="remaining_months"?1:"any",maxLength:gt==="address"?250:100,onChange:kt=>C(Vt=>({...Vt,[gt]:kt.target.value}))})]},gt))}),s.jsx(Lt,{type:"submit",disabled:c,className:"w-full",children:c?"Saving…":"Save home details"})]})]})})]});return e?s.jsx("div",{className:"homeowner-page min-h-screen",children:s.jsx("div",{className:"homeowner-shell",children:Le})}):Le}function dlt({portal:t,children:e}){var c;const r=llt((c=t==null?void 0:t.deal_pipeline)==null?void 0:c.deal_pipeline_stages),[n,i]=N.useState("transaction"),{data:o}=mr({queryKey:["portal-homeowner-enabled",t==null?void 0:t.slug],queryFn:async()=>{const{data:a,error:f}=await Ce.rpc("homeowner_hub_read",{_key:t.slug});return f?null:a},enabled:r&&!!(t!=null&&t.slug)});return!r||!o?s.jsx(s.Fragment,{children:e}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"homeowner-portal-tabs max-w-5xl mx-auto px-4 py-5",children:s.jsx(vF,{value:n,onValueChange:i,children:s.jsxs(JC,{className:"homeowner-control",children:[s.jsx(Of,{value:"transaction",children:"Your transaction"}),s.jsx(Of,{value:"homeowner",children:"Homeowner Hub"})]})})}),n==="homeowner"?s.jsx("div",{className:"max-w-5xl mx-auto px-5 pb-10",children:s.jsx(ult,{accessKey:t.slug},t.slug)}):e]})}function hlt({dealData:t,agentProfile:e,welcomeMessage:r,isWon:n,branding:i}){var m;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,a=(i==null?void 0:i.cover_photo_url)||null,f=(i==null?void 0:i.tagline)||"Your Real Estate Concierge";return s.jsxs("div",{className:"relative overflow-hidden",children:[s.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[a&&s.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${a})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:a?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),s.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),s.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&s.jsx(yr.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:s.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("img",{src:c,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),e&&s.jsxs(yr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[e.avatar_url?s.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:s.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:s.jsx("img",{src:e.avatar_url,alt:e.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):s.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((m=e.name)==null?void 0:m.charAt(0))||"?"}),s.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:e.name}),s.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:f})]}),s.jsxs(yr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[s.jsx(ta,{className:"w-3 h-3"}),n0(t==null?void 0:t.deal_type)?"Sale":LO(t==null?void 0:t.deal_type)?"Purchase":"Transaction",n&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),s.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(t==null?void 0:t.deal_name)||"Your Transaction"}),s.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),o&&s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[s.jsx(ii,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),s.jsx("span",{children:o})]}),r&&s.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",r,"”"]})]})]})]}),e&&s.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:s.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:s.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.phone&&s.jsxs("a",{href:`tel:${e.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(Fn,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(rs,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),e.phone&&s.jsxs("a",{href:`sms:${e.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(K_,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function ije({targetCloseDate:t,actualCloseDate:e,clientName:r,dealType:n}){if(e||!t)return null;const i=t.split(/[-/T]/),o=new Date(Number(i[0]),Number(i[1])-1,Number(i[2])),a=jZe(o,new Date);if(dT(o)&&!kh(o))return null;const f=kh(o),m=f?"0":String(Math.max(0,a)),y=Math.max(4,Math.min(100,(60-Math.min(60,a))/60*100));return s.jsxs("div",{className:"portal-tile p-8 text-center",children:[s.jsx("p",{className:"portal-eyebrow mb-4",children:f?"The Moment Has Arrived":"Countdown to Closing"}),f?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),s.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[s.jsx(yr.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:m}),s.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:a===1?"day":"days"})]}),s.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),s.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:n0(n)?"Until closing day":"Until you hold the keys"}),s.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:s.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:s.jsx(yr.div,{initial:{width:0},animate:{width:`${y}%`},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 trr(t){return t.type!=="application/pdf"?"Please choose a PDF":t.size?t.size>15*1024*1024?"PDF must be under 15 MB":null:"The PDF is empty"}function flt(t,e){return te.has(r.id))}function nrr(t){return t.reduce((e,r)=>e+r.file_size,0)>25*1024*1024?"Choose documents totaling no more than 25 MB.":null}const mlt={Lead:{expect:"Your agent will learn what matters most to you and your move.",action:"Share your goals, timing, and preferred way to stay in touch."},Consultation:{expect:"Together you will review your options and create a plan.",action:"Bring your questions and any important timing or financing details."},"Agreement Signed":{expect:"Your agent is organizing the next steps with you.",action:"Keep a copy of your signed agreements and confirm your contact details."},Active:{expect:"Your agent will keep you updated as your search or marketing progresses.",action:"Share feedback and let your agent know when your priorities change."},"Under Contract":{expect:"Inspections, financing, and title review move forward according to your contract.",action:"Check your key dates and respond promptly to requests from your agent or lender."},Closing:{expect:"The closing team will coordinate final documents and any remaining requirements.",action:"Confirm your appointment and ID requirements. Verify wire instructions by calling a trusted number."},"Closed Won":{expect:"Your agent can help with post-closing questions and your next chapter.",action:"Save your closing documents somewhere secure."}};function aje({journeyStages:t,currentIndex:e,dealType:r}){const[n,i]=N.useState(e);return N.useEffect(()=>i(e),[e]),t.length?s.jsxs("section",{className:"portal-roadmap",children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),s.jsxs("div",{className:"mb-6 flex flex-wrap items-baseline justify-between gap-2",children:[s.jsx("h2",{className:"portal-serif text-2xl",children:n0(r)?"Your path to closing":"Your path to the keys"}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:["Step ",e+1," of ",t.length]})]}),s.jsx("ol",{className:"space-y-1",children:t.map((o,c)=>{const a=flt(c,e),f=n===c,m=mlt[o.key];return s.jsxs("li",{className:"portal-roadmap-step","data-status":a,children:[s.jsxs(Lt,{variant:"ghost",className:"portal-roadmap-trigger h-auto w-full justify-start gap-3 whitespace-normal py-3 text-left","aria-expanded":f,"aria-current":a==="current"?"step":void 0,onClick:()=>i(f?null:c),children:[s.jsx("span",{className:"portal-roadmap-marker flex h-8 w-8 shrink-0 items-center justify-center rounded-full",children:a==="completed"?s.jsx(pa,{className:"h-4 w-4"}):c+1}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"portal-serif block text-lg",children:o.label}),s.jsx("span",{className:"block text-xs font-normal",children:a==="current"?"You are here":a==="completed"?"Completed":"Ahead of you"})]}),f?s.jsx(bye,{className:"h-4 w-4 shrink-0"}):s.jsx(Wo,{className:"h-4 w-4 shrink-0"})]}),f&&s.jsxs("div",{className:"portal-roadmap-details ml-11 space-y-3 border-l pl-4 pb-4 text-sm",children:[s.jsx("p",{children:o.description}),m&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-1",children:"What to expect"}),s.jsx("p",{children:m.expect})]}),s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-1",children:"Your next move"}),s.jsx("p",{children:m.action})]})]})]})]},o.key)})})]}):null}function oje({currentStage:t,agentUpdate:e,nextStepText:r,nextStepVideoUrl:n}){const i=o=>{var c,a;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=(a=o.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return f?`https://www.loom.com/embed/${f}`:null}return o};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),s.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:t.label}),s.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:t.description}),e&&s.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),s.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",e,"”"]})]}),r&&s.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),s.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:r})]}),n&&s.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("iframe",{src:i(n)||n,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function s0(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 srr(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 a=new Date(c,i,o);if(!(a.getFullYear()!==c||a.getMonth()!==i||a.getDate()!==o))return a}function plt(t){return Array.isArray(t)?t.filter(e=>e&&typeof e.id=="string"&&typeof e.label=="string"&&typeof e.date=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e.date)).map(e=>({id:e.id,label:e.label.trim(),date:e.date.slice(0,10),done:!!e.done,show_in_portal:e.show_in_portal!==!1,notes:e.notes??null,provisional:!!e.provisional,source_key:typeof e.source_key=="string"?e.source_key:null})).sort((e,r)=>e.date.localeCompare(r.date)):[]}function glt(t){return plt(t).filter(e=>e.show_in_portal)}function irr(t,e){const[r,n,i]=t.split(/[-/T]/).map(Number),o=new Date(r,n-1,i+e);return`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`}const ylt=["January","February","March","April","May","June","July","August","September","October","November","December"],xlt=t=>String(t).padStart(2,"0");function lje(t){const e=t.filter(n=>/^\d{4}-\d{2}-\d{2}/.test(n.date||""));return Array.from(new Set(e.map(n=>n.date.slice(0,7)))).sort().map(n=>{const[i,o]=n.split(/[-/T]/).map(Number),c=new Date(i,o-1,1).getDay(),a=new Date(i,o,0).getDate(),f=[];for(let y=0;yw.date.slice(0,10)===v)})}for(;f.length%7;)f.push(null);const m=[];for(let y=0;y{var n;return(n=r.date)==null?void 0:n.startsWith(e)}).sort((r,n)=>r.date.localeCompare(n.date))}const uje=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function vlt({events:t,variant:e="app",provisionalNote:r}){const n=lje(t);if(!n.length)return null;const i=e==="portal",o=i?{color:"hsl(var(--portal-ink))"}:void 0,c=i?{color:"hsl(var(--portal-ink-dim))"}:void 0,a=i?{background:"hsl(var(--portal-surface-2))"}:void 0,f=m=>i?{background:m?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.22)",border:"1px solid hsl(var(--portal-gold) / 0.5)"}:void 0;return s.jsxs("div",{className:"space-y-6",children:[t.some(m=>m.provisional)&&s.jsxs("div",{className:i?"rounded-md p-3 text-xs":"rounded-md border border-accent bg-accent/30 p-3 text-xs",style:i?{border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-ink))"}:void 0,children:[s.jsx("p",{className:"font-semibold uppercase tracking-wide",children:"Seller acceptance unverified"}),s.jsxs("p",{className:"mt-0.5",children:["* ",r||"Provisional dates assume the offer is accepted. They will be recalculated from the actual acceptance date."]})]}),n.map(m=>s.jsxs("div",{className:"break-inside-avoid",children:[s.jsx("h3",{className:i?"portal-serif text-xl mb-2":"text-lg font-semibold mb-2",style:o,children:m.title}),s.jsxs("div",{className:"grid grid-cols-7 gap-1 text-[10px] sm:text-xs",children:[uje.map(y=>s.jsx("div",{className:i?"px-1 uppercase tracking-wider":"px-1 uppercase tracking-wider text-muted-foreground",style:c,children:y},y)),m.weeks.flat().map((y,v)=>s.jsx("div",{className:`min-h-[52px] sm:min-h-[64px] rounded p-1 ${i?"":y!=null&&y.events.length?y.events.every(w=>w.provisional)?"bg-accent/40 border border-accent":"bg-primary/10 border border-primary/40":y?"bg-muted/50":""}`,style:y?y.events.length?f(y.events.every(w=>w.provisional)):a:void 0,children:y&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",style:o,children:y.day}),y.events.map((w,j)=>s.jsxs("div",{className:`leading-tight font-medium ${w.done?"line-through opacity-60":""} ${i?"":"text-primary"}`,style:i?{color:"hsl(var(--portal-gold))"}:void 0,children:[w.label,w.provisional?"*":""]},j))]})},v))]}),s.jsx("ul",{className:"mt-3 space-y-2 text-sm",children:cje(t,m.key).map((y,v)=>s.jsxs("li",{children:[s.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wide",style:o,children:[Ls(s0(y.date),"MMM d"),y.provisional?"*":""," · ",y.label]}),y.note&&s.jsx("p",{className:i?"text-xs":"text-xs text-muted-foreground",style:c,children:y.note})]},v))})]},m.key))]})}const lf=t=>t.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]);function arr(t){var c;const e=lje(t.events),r=window.open("","_blank");if(!r)return!1;const n=t.events.some(a=>a.provisional)?``:"",i=e.map(a=>{const f=a.weeks.flat().map(v=>v?`
${v.day}
${v.events.map(w=>`
${lf(w.label)}${w.provisional?"*":""}
`).join("")}`:''),m=[];for(let v=0;v${f.slice(v,v+7).join("")}`);const y=cje(t.events,a.key).map(v=>`
  • ${lf(Ls(s0(v.date),"MMM d").toUpperCase())}${v.provisional?"*":""}  |  ${lf(v.label.toUpperCase())}${v.note?`
    ${lf(v.note)}`:""}
  • `).join("");return`

    ${lf(t.title)}

    ${lf(t.subtitle||"")}

    ${lf(t.agent||"")}
    ${n}

    ${a.title}

    ${uje.map(v=>``).join("")}${m.join("")}
    ${v.toUpperCase()}
      ${y}
    `}).join(""),o=(c=t.terms)!=null&&c.length?`

    Who does what

      ${t.terms.map(a=>`
    • ${lf(a.label.toUpperCase())}
      ${lf(a.detail)}
    • `).join("")}
    `:"";return r.document.write(`${lf(t.title)} — Transaction Calendar${i}${o}